【问题标题】:How to convert black and white image to array with 3 dimensions in python?如何在python中将黑白图像转换为3维数组?
【发布时间】:2017-10-06 19:16:20
【问题描述】:

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

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

numpy.zeros(shape=[400, 400, 1])

【问题讨论】:

  • 发布的解决方案是否对您有用?
  • 是的,两种解决方案都有效,我忘记将其中一个标记为已接受,谢谢提醒!

标签: python image numpy image-processing computer-vision


【解决方案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)

【讨论】:

    【解决方案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 那里词穷了。编辑使其更有意义。
    【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 2021-02-27
      • 2018-12-14
      • 1970-01-01
      • 1970-01-01
      • 2016-05-17
      • 2019-08-13
      • 2011-11-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多