如何在 python 中将黑白图像转换为具有 3 个维度的数组?

How to convert black and white image to array with 3 dimensions in python?

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

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