【问题标题】:Python add one more channel to imagePython为图像添加了一个通道
【发布时间】:2018-08-20 14:01:45
【问题描述】:

由于以下错误,我正在尝试添加频道

ValueError: 无法将输入数组从形状 (48,48) 广播到形状 (48,48,1)

代码:

img = cv2.imread(f,0)
resized = cv2.resize(img, (48,48), interpolation = cv2.INTER_AREA)
print(resized.shape) 
(48, 48)

但我需要一个像 (48,48,1) 这样的频道图像。

我该如何解决这个问题?

【问题讨论】:

  • 重塑您的阵列? img = img.reshape(48,48,1)

标签: python python-2.7 opencv tensorflow keras


【解决方案1】:

修改 Aditya 的答案:


y = np.expand_dims(x, axis=1)

axis = 1 将在开头插入新维度,因此您只需将轴的值更改为 = 3。它对我有用。

【讨论】:

    【解决方案2】:

    非常简单!在您的交互式外壳上,只需执行

    >>> y = image.resize(48, 48, 1)

    >>> y.shape

    >>> (48, 48, 1)

    【讨论】:

      【解决方案3】:
      y = np.expand_dims(x, axis=-1)  # Equivalent to x[:,:,np.newaxis]
      

      正如函数所说,它将添加一个额外的维度作为新的 Last Channel

      编辑

      • 轴将是 -1 而不是 1

      【讨论】:

      • 这是不正确的,它返回形状(48, 1, 48)。你是说axis=-1 吗?
      • 是的;我们需要调整它!谢谢
      【解决方案4】:

      另一种解决方法可能是创建一个占位符并填充它。

      ph = np.ones((resized.shape[0], resized.shape[1], 1), dtype='uint8')
      ph[:,:,0] = resized
      

      【讨论】:

        【解决方案5】:

        您可以通过使用拆分和合并操作来做到这一点:

        首先,使用 split 将您的 2 通道图像拆分为两个数组。然后,分别创建为您提供第三个通道的数组。最后将三个数组合并得到一个3通道的Mat。

        这是一个例子:

        c1,c2 = cv2.split(img)
        merged = cv2.merge((c1,c2,arr))
        

        其中 img 是您的 2 通道图像,arr 是包含要添加的通道的数组,合并后的图像包含合并的三个通道。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-10-22
          • 2020-08-08
          • 2021-04-25
          • 1970-01-01
          相关资源
          最近更新 更多