如何在 python 中将黑白图像转换为 3 维数组



我有RGB格式或灰度格式的图像(我通过Gimp转换了它,比方说(,现在每次我以灰度加载图像,或者只是将其转换为灰度格式时,形状总是显示[高度,宽度]而没有第三维(颜色通道的数量(。

我知道通常黑白图像以这种格式存储,但我特别需要[height, width, 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)

或用Nonenp.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.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)

最新更新