【问题标题】:Show OpenCV image in matplotlib's subplots在 matplotlib 的子图中显示 OpenCV 图像
【发布时间】:2020-01-12 13:50:26
【问题描述】:

我在 matplotlib 的子图中显示 OpenCV 图像时遇到问题

#Read random images from multiple directories
import random
animals = os.listdir('signs/train')
sample_images = []
for a in animals:
  dirname = 'signs/train/' + a
  files = random.sample(os.listdir(dirname), 5)
  files = [dirname + '/' + im for im in files]
  sample_images.extend(files)

del files, dirname,   animals
print(sample_images)

# Output: ['signs/train/rooster/00000327.jpg', 'signs/train/rooster/00000329.jpg', 'signs/train/rooster/00000168.jpg', ...,  'signs/train/rooster/00000235.jpg', 'signs/train/rooster/00000138.jpg']

#Read using OpenCV and show in matplotlib's subplots

fig, ax = plt.subplots(12, 5,figsize=(15,15), sharex=True)
for idx, si in enumerate(sample_images):
  i = idx % 5 # Get subplot row
  j = idx // 5 # Get subplot column
  image = cv2.imread(si)
  image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) 
  image = cv2.resize(image, (64, 64))
  ax[i, j].plot(image)
plt.show()

我已经检查过每个图像是否已成功加载并使用 opencv 调整大小,但我不知道为什么我在matplotlibsubplot 上绘制它们时不断收到以下错误。


ValueError                                Traceback (most recent call last)

<ipython-input-56-38cc921c1724> in <module>()
     10   #image = Image.open(si)
     11   #print(type(image))
---> 12   ax[i, j].plot(image)
     13 plt.show()

3 frames

/usr/local/lib/python3.6/dist-packages/matplotlib/axes/_base.py in _xy_from_xy(self, x, y)
    271         if x.ndim > 2 or y.ndim > 2:
    272             raise ValueError("x and y can be no greater than 2-D, but have "
--> 273                              "shapes {} and {}".format(x.shape, y.shape))
    274 
    275         if x.ndim == 1:

ValueError: x and y can be no greater than 2-D, but have shapes (64,) and (64, 64, 3)

编辑 我忘了提到我已经尝试在一张图像上进行测试,并且它可以工作(即使它是 JPG 格式并且仍然使用 RGB 通道)

我做错了什么?

【问题讨论】:

    标签: python opencv matplotlib


    【解决方案1】:

    您错误地使用了ax.plot(),因为它只绘制了 y 与 x 数据。正确的函数是 plt.imshow(),这是 matplotlib 的内置函数,用于显示图像数据。下面的示例有效,可以根据您的目的进行扩展。

    import cv2 as cv
    from matplotlib import pyplot as plt
    image1 = cv.imread('image1.jpg')
    image2 = cv.imread('image2.jpg')
    plt.subplot(1, 2, 1)
    plt.imshow(image1)
    plt.subplot(1, 2, 2)
    plt.imshow(image2)
    

    【讨论】:

    • 详细一点,也不全错。斧头应该使用“imshow”而不是“情节”,一切正常
    【解决方案2】:

    参考这个post,它讨论了matplotlib子图中的图像,似乎只支持PNG文件类型。

    另请参阅链接中的image tutorial

    我认为错误是因为 subplot 只接受二维图像,并且由于 JPG 具有三个颜色通道,matplotlib 不确定将哪些信息映射到 x 和 y 维度。

    【讨论】:

      【解决方案3】:

      plot 的意图应该只适用于 2d 数据(例如灰度图像),当您添加 3d 图像时,您应该使用imshow 来代替它。因此,您只需将ax[i, j].plot(image) 替换为ax[i, j].imshow(image),一切都会好起来的。

      【讨论】:

        猜你喜欢
        • 2015-10-05
        • 2017-09-08
        • 2017-08-30
        • 2013-10-31
        • 1970-01-01
        • 2017-07-27
        • 1970-01-01
        相关资源
        最近更新 更多