【问题标题】:How to convert 1d array to 3d array (convert grayscale image so rgb format )?如何将 1d 数组转换为 3d 数组(将灰度图像转换为 rgb 格式)?
【发布时间】:2019-11-27 21:37:57
【问题描述】:

我有一个 numpy 数组格式的图像,我编写了假设 rgb 图像作为输入的代码,但我发现输入由黑白图像组成。

对于应该是 RGB 即 (256,256,3) 维度的图像,我将输入作为灰度 (256,256) 数组图像,我想将其转换为 (256,256,3)

这是我在 numpy 数组中的内容:

[[0 0 0 ... 0 0 0]
 [0 0 0 ... 0 0 0]
 [0 0 0 ... 0 0 0]
 ...
 [0 0 0 ... 0 0 0]
 [0 0 0 ... 0 0 0]
 [0 0 0 ... 0 0 0]]
(256, 256)

这就是我想要的:(对于上面数组中的每个值,相同元素的数组 3 次)

[[[0. 0. 0.]
  [0. 0. 0.]
  [0. 0. 0.]
  ...
  [0. 0. 0.]
  [0. 0. 0.]
  [0. 0. 0.]]]

是否有任何 numpy 函数可以做到这一点? 如果没有,有没有办法在 python 数组中执行此操作并将其转换为 numpy?

【问题讨论】:

    标签: python arrays numpy numpy-ndarray array-broadcasting


    【解决方案1】:

    您可以使用numpy.dstack 沿第三轴堆叠二维数组:

    import numpy as np
    
    a = np.array([[1, 2], [3, 4]])
    b = np.dstack([a, a, a])
    

    结果:

    [[[1 1 1]
      [2 2 2]]
     [[3 3 3]
      [4 4 4]]]
    

    或者使用opencvmerge函数合并3个颜色通道。

    【讨论】:

      【解决方案2】:

      您可以通过两种方式做到这一点:

      1. 您可以为此使用 opencv。要将图像从灰度转换为 RGB:
      import cv2
      import numpy as np
      gray = np.random.rand(256, 256)
      gary2rgb = cv2.cvtColor(gray,cv2.COLOR_GRAY2RGB)
      
      1. 仅使用 numpy,可以通过以下方式进行:
      import numpy as np
      def convert_gray2rgb(image):
          width, height = image.shape
          out = np.empty((width, height, 3), dtype=np.uint8)
          out[:, :, 0] = image
          out[:, :, 1] = image
          out[:, :, 2] = image
          return out
      
      gray = np.random.rand(256, 256)  # gray scale image
      gray2rgb = convert_gray2rgb(gray)
      

      【讨论】:

        猜你喜欢
        • 2021-04-02
        • 1970-01-01
        • 2016-08-16
        • 1970-01-01
        • 2014-02-26
        • 2014-12-22
        • 1970-01-01
        • 2012-11-09
        相关资源
        最近更新 更多