【问题标题】:convert a grayscale image into 3 channel image将灰度图像转换为 3 通道图像
【发布时间】:2020-09-04 23:13:02
【问题描述】:

我想将具有形状(高度,宽度)的灰度图像数据集转换为具有形状(高度,宽度,3)的 3 通道图像数据集,我使用了此处发布的解决方案 convert a grayscale image to a 3-channel image,它给出了以下内容错误:


    TypeError                                 Traceback (most recent call last)
<ipython-input-57-f7b70a125ab8> in <module>()
      1 X_mult = mult_imgs(X)
----> 2 plot_samples(X_mult, n=10)

6 frames
/usr/local/lib/python3.6/dist-packages/matplotlib/image.py in set_data(self, A)
    697                 or self._A.ndim == 3 and self._A.shape[-1] in [3, 4]):
    698             raise TypeError("Invalid shape {} for image data"
--> 699                             .format(self._A.shape))
    700 
    701         if self._A.ndim == 3:

TypeError: Invalid shape (77, 77, 3, 3) for image data

完整代码为:

def load_data(dir_path):
    X = []
    for file in tqdm((os.listdir(dir_path))):
        if not file.startswith('.'):
            img = cv2.imread(dir_path + '//' + file)
            X.append(img)
    X = np.array(X)
    print(f'{len(X)} images loaded from {dir_path} directory.')
    return X

dir_path = '/content/drive/My Drive/oskar'
X = load_data(dir_path)


def plot_samples(X, n=50):
    """
    Creates a gridplot for desired number of images (n) from the specified set
    """
    np.random.shuffle(X)
    imgs = X[:n]
    j = 10
    i = int(n/j)

    plt.figure(figsize=(15,6))
    c = 1
    for img in imgs:
        plt.subplot(i,j,c)
        plt.imshow(img)

        plt.xticks([])
        plt.yticks([])
        c += 1
    plt.show()

plot_samples(X, n=30)


def mult_imgs(set_name):
    """
    Convert one channel images to 3 channels
    """
    set_new = []
    for img in set_name:
        new_img = np.stack((img,)*3, axis=-1) 
        #new_img = np.stack((img,) * 3), axis=1)
        set_new.append(new_img)
    return np.array(set_new) 


X_mult = mult_imgs(X)
plot_samples(X_mult, n=10)

我正在使用 google colab,这就是为什么在函数声明之后调用函数。 执行最后一个函数时出现错误。 有人可以帮帮我!

【问题讨论】:

  • cv2.cvtColor(image,cv2.COLOR_GRAY2BGR)
  • @AlexAlex 我试过了,它给出了以下错误:输入图像中的通道数无效:> 'VScn::contains(scn)' > where > 'scn' is 3

标签: python numpy image-processing


【解决方案1】:

您的灰度图像似乎不是(width,height) 的形状,而是常规的 rgb 图像,只有所有通道具有相同的强度,因此形状为(width,height,3)

您使用的答案代码假定您有一个形状为(width, height) 的灰度图像,但由于您的图像有一个额外的尺寸,它会产生一个无效的形状(77, 77, 3, 3)。您可以像这样删除额外的维度:

img = img[:,:,0]

在您的第一个函数中,您可以毫无问题地应用您链接的答案。

在调用 OpenCV 时,首先将图像加载为灰度图像,默认为 RGB:

img = cv2.imread(dir_path + '//' + file, 0)

【讨论】:

  • 图像的形状(宽度,高度)但正如你所说的OpenCV改变它们的形状,所以解决方案是添加``` img = img[:,:,0] ```或只需将 cv2.IMREAD_UNCHANGED 添加到 imread 函数中
猜你喜欢
  • 2018-03-29
  • 2011-04-18
  • 1970-01-01
  • 2019-03-15
  • 1970-01-01
  • 2020-10-20
  • 2022-12-20
  • 1970-01-01
相关资源
最近更新 更多