首页 > 解决方案 > 使用 imshow python 在一个目录中显示多个图像

问题描述

我正在尝试在一个目录中显示多个图像。

import os
import cv2
import numpy as np
import random
import math

import matplotlib
from matplotlib.pyplot import imshow
from matplotlib import pyplot as plt
import matplotlib.image as mpimg
%matplotlib inline

dir_path = 'img'
images = os.listdir(dir_path)
img_paths = [os.path.join(dir_path, i) for i in images]
img_paths.sort()
img_all = np.array([cv2.cvtColor(cv2.imread(p), cv2.COLOR_BGR2RGB) for p in img_paths])


def display_helper(images, cmap=None):
    fig, ax = plt.subplots(nrows=20, ncols=2, figsize=(15,6))
    for a in ax:
        a.imshow(img, interpolation='none')

display_helper(img_all)

但我得到这个错误

AttributeError: 'numpy.ndarray' object has no attribute 'imshow'

如何使用 imshow 显示多个图像?

谢谢!

标签: pythonmatplotlibimshow

解决方案


问题就在这里

fig, ax = plt.subplots(nrows=20, ncols=2, figsize=(15,6))

这给出ax了一个np.array形状(20,2)。所以当你这样做时for a in axa是一个np.array2。要修复它,请将以下行更改为:

for a in ax.flatten():

推荐阅读