我有一张图片,它是RGB格式或灰度格式(我通过Gimp进行了转换),现在每次我加载灰度图像,或者只是将其转换为灰度格式时,形状总是显示为[高度,宽度],而没有第三个维度(颜色通道数)。
我知道通常黑白图像是以这种方式存储的,但我特别需要[高度,宽度,1]
的图像形状,就像你会得到的那样,比如:
numpy.zeros(shape=[400, 400, 1])
我有一张图片,它是RGB格式或灰度格式(我通过Gimp进行了转换),现在每次我加载灰度图像,或者只是将其转换为灰度格式时,形状总是显示为[高度,宽度],而没有第三个维度(颜色通道数)。
我知道通常黑白图像是以这种方式存储的,但我特别需要[高度,宽度,1]
的图像形状,就像你会得到的那样,比如:
numpy.zeros(shape=[400, 400, 1])
np.expand_dims
添加“空”维度:>>> a2d = np.ones((100, 200))
>>> a3d = np.expand_dims(a2d, axis=2)
>>> a3d.shape
(100, 200, 1)
或者使用None
或np.newaxis
进行切片:
>>> a2d[..., None].shape # instead of "..." (Ellipsis) you could also use `[:, :, None]`
(100, 200, 1)
我更喜欢使用np.expand_dims
,因为相比于切片操作,它更能明确地展示出发生了什么。
如果需要有条件地使用它,请先检查arr.ndim
:
if arr.ndim == 2:
arr = np.expand_dims(arr, axis=2)
为此目的,有一个内置的np.atleast_3d
函数 -
np.atleast_3d(img)
2D
数组后附加一个新轴,保持输出形状为3D
,对于3D
输入则不做改变,在幕后处理所有内容。In [42]: img = np.random.randint(0,255,(800,600)) # grayscale img
In [43]: np.atleast_3d(img).shape
Out[43]: (800, 600, 1)
In [44]: img = np.random.randint(0,255,(800,600,3)) # RGB img
In [45]: np.atleast_3d(img).shape
Out[45]: (800, 600, 3)
np.array(img, ndmin=3, copy=False)
,但那只是在前面添加了维度。很高兴知道他们还有另一个函数可以添加维度。 :) - MSeifert我使用了np.reshape()
函数将另一个维度添加到灰度图像中。
grayscale = cv2.cvtColor(raw_data, cv2.COLOR_BGR2GRAY)
print(grayscale.shape) # prints (800,600)
grayscale = grayscale.reshape(grayscale.shape[0], grayscale.shape[1], 1)
print(grayscale.shape) # prints (800,600,1)