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

问题描述 投票:4回答:3

我有RGB格式或灰度格式的图像(我通过Gimp转换它,让我们说),现在我每次以灰度加载图像,或者只是将其转换为灰度格式,形状总是说[高度,宽度]没有第三尺寸(颜色通道的数量)。

我知道通常黑白图像以这种格式存储,但我特别需要[height, width, 1]图像形状,你会得到的,让我们说:

numpy.zeros(shape=[400, 400, 1])
python image numpy image-processing computer-vision
3个回答
5
投票

您始终可以使用np.expand_dims添加“空”维度:

>>> a2d = np.ones((100, 200))
>>> a3d = np.expand_dims(a, 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)

3
投票

完全有一个内置的np.atleast_3d用于此目的 -

np.atleast_3d(img)

这个内置程序负责通过将一个新轴作为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)

0
投票

只是为了添加另一个可能的解决方案,可以使用以下内容(请参阅np.reshape):

import numpy as np

img = np.random.randint(0,255,(800,600))  # grayscale img
print(img.shape)  # prints (800, 600)

img = np.reshape(img.shape[0], img.shape[1], 1)
print(img.shape)  # prints (800, 600, 1)

如上所述,这只是另一种可能的解决方案。我不确定这与其他建议的答案相比有多有效,它们看起来更加优雅和干净。

© www.soinside.com 2019 - 2024. All rights reserved.