1. expand_dims
numpy.expand_dims(a, axis)
在给定的axis中插入一个新的axis以扩充array的shape。
- axis:需要扩充轴axes的位置
2. squeeze
numpy.squeeze(a, axis=None)
从array中remove轴的大小为1的。
- axis:指定需要remove轴大小为1的轴
>>> x = np.array([[[0], [1], [2]]])
>>> x.shape
(1, 3, 1)
>>> np.squeeze(x).shape
(3,)
>>> np.squeeze(x, axis=0).shape
(3, 1)
>>> np.squeeze(x, axis=1).shape
Traceback (most recent call last):
...
ValueError: cannot select an axis to squeeze out which has size not equal to one
3. repeat
numpy.repeat(a, repeats, axis=None)
重复array中的元素。
- repeats:重复的次数
- axis:沿其重复值的轴。
Axis的理解
可以将其理解为剥洋葱,如下图所示,axis=0表示第一层(对应黑色框),axis=1表示第二层(对应红色框),axis=2表示第三层(对应蓝色框)。
对于axis轴的操作,numpy会沿着第i个下标变化的方向进行操作。
>>> a
array([[1, 2],
[3, 4]])
>>> np.repeat(a, 2, axis=0)
array([[1, 2],
[1, 2],
[3, 4],
[3, 4]])
>>> np.repeat(a, 2, axis=1)
array([[1, 1, 2, 2],
[3, 3, 4, 4]])
4. transpose
numpy.transpose(a, axes=None)
反转或置换数组的轴; 返回修改后的数组。
image = cv2.imread("image-file.jpg") # BGR | HWC order
image = image.transpose(2, 0, 1) # CHW order
# rgb = bgr[...,::-1]
image = image[..., ::-1] # BGR -> RGB
# cv2.cvtColor( src, cv2.COLOR_BGR2GRAY ) -> dst
5. ndarray的属性
- 基础属性
Tuple of array dimensions. | |
Number of elements in the array. | |
ndarray.dtype | dataType |
- 内存分配
Length of one array element in bytes. (数组中一个元素所占用的字节) | |
Total bytes consumed by the elements of the array. (该数值总共占用的字节数) |
6. 创建ndarray
| Return a new array of given shape and type, filled with ones.(给定array的shape和type,值都为1) |
| Return an array of ones with the same shape and type as a given array.(基于一个已有的array得到相应的shape和type) |
| Return a new array of given shape and type, filled with zeros.(给定array的shape和type,值都为0) |
| Return an array of zeros with the same shape and type as a given array.(基于一个已有的array得到相应的shape和type) |