python - 在 matplotlib 的子图中显示 OpenCV 图像

标签 python opencv matplotlib

我在 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 channel )

enter image description here

我做错了什么?

最佳答案

您错误地使用了 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)

关于python - 在 matplotlib 的子图中显示 OpenCV 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59704471/

相关文章:

python - 如何在 PyCharm 中获取 Tensorflow 的代码补全?

python - 使用Python访问JSON文件,得到 "Memory Error"

c++ - 如何通过引用返回一个 vector ,隐含地期望一个空 vector 作为输入?

c++ - 在 Linux Mint 17.1 64 位(未声明/不是类型)上尝试 "make"C++ 项目时从 cstdlib 编译错误和类似错误

matplotlib - 在 matplotlib 的等高线图中孵化 NaN 区域

python - 为什么 pandas 的类别/垃圾箱用左括号写,但用右括号写?

python - 安装 pyspider - "python setup.py egg_info"失败,错误代码为 1

image-processing - 在opencv中,如何将灰度图像复制并缩放到另一个彩色图像

python - 边不显示在使用 Networkx 的图形中 - Python

python - 与未排序数据相交的 matplotlib 图