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

dan*_*chy 4 python numpy image image-processing computer-vision

我有RGB格式或灰度格式的图像(例如,我通过Gimp对其进行了转换),现在每次我以灰度级加载图像,或者只是将其转换为灰度格式时,形状始终显示[height,width],而没有第三个尺寸(颜色通道数)。

我知道通常黑白图像都是以这种格式存储的,但是我特别需要[height, width, 1]图像形状,即可以得到的图像形状,例如:

numpy.zeros(shape=[400, 400, 1])
Run Code Online (Sandbox Code Playgroud)

Div*_*kar 6

有一个内置的np.atleast_3d正是为此目的 -

np.atleast_3d(img)
Run Code Online (Sandbox Code Playgroud)

这个内置3D函数通过添加一个新轴作为2D数组的最后一个轴来保持输出形状不变,并且不对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)
Run Code Online (Sandbox Code Playgroud)


MSe*_*ert 5

您始终可以使用添加“空”尺寸np.expand_dims

>>> a2d = np.ones((100, 200))
>>> a3d = np.expand_dims(a, axis=2)
>>> a3d.shape
(100, 200, 1)
Run Code Online (Sandbox Code Playgroud)

或用None或切片np.newaxis

>>> a2d[..., None].shape  # instead of "..." (Ellipsis) you could also use `[:, :, None]`
(100, 200, 1)
Run Code Online (Sandbox Code Playgroud)

我喜欢,np.expand_dims因为它比切片更清楚地说明了会发生什么。


如果有条件需要,请arr.ndim首先检查:

if arr.ndim == 2:
    arr = np.expand_dims(arr, axis=2)
Run Code Online (Sandbox Code Playgroud)