在matplotlib子图中打印多个图像文件

在matplotlib子图中打印多个图像文件,matplotlib,Matplotlib,我想创建一个矩阵子图,并将每个BMP文件从一个目录显示在不同的子图中,但我找不到解决问题的适当方法,有人能帮我吗 这是我拥有的代码: import os, sys from PIL import Image import matplotlib.pyplot as plt from glob import glob bmps = glob('*trace*.bmp') fig, axes = plt.subplots(3, 3) for arch in bmps: i = Image

我想创建一个矩阵子图,并将每个BMP文件从一个目录显示在不同的子图中,但我找不到解决问题的适当方法,有人能帮我吗

这是我拥有的代码:

import os, sys
from PIL import Image
import matplotlib.pyplot as plt
from glob import glob

bmps = glob('*trace*.bmp')

fig, axes = plt.subplots(3, 3)

for arch in bmps:
    i = Image.open(arch)
    iar = np.array(i)
    for i in range(3):
        for j in range(3):
            axes[i, j].plot(iar)
            plt.subplots_adjust(wspace=0, hspace=0)
plt.show()
执行后,我出现以下错误:


本机matplotlib仅支持PNG图像,请参阅

然后方法总是读取图像-绘制图像

读取图像

绘图图像(2个子绘图)

按照上的教程进行操作(因为有导入库)


下面是一个使用matplotlib绘制bmp的线程:

bmp有三个颜色通道,加上高度和宽度,使其形状为(h,w,3)。我相信绘制图像会给你一个错误,因为绘图只接受二维。您可以对图像进行灰度化,这将生成一个只有二维(h,w)的矩阵

在不知道图像尺寸的情况下,您可以执行以下操作:

for idx, arch in enumerate(bmps):
    i = idx % 3 # Get subplot row
    j = idx // 3 # Get subplot column
    image = Image.open(arch)
    iar_shp = np.array(image).shape # Get h,w dimensions
    image = image.convert('L') # convert to grayscale
    # Load grayscale matrix, reshape to dimensions of color bmp
    iar = np.array(image.getdata()).reshape(iar_shp[0], iar_shp[1])
    axes[i, j].plot(iar)
 plt.subplots_adjust(wspace=0, hspace=0)
 plt.show()

拉尔夫,谢谢你的回复。如果我理解你的答案,我需要将格式从BMP更改为PNG,然后再次运行我的代码?你没有提到我的代码,如果我用PNG代替BMP,你认为我的代码会运行吗?再次感谢。对于第一次尝试,我会让它像在和上面的帖子一样简单。如果它有效,你可以添加更复杂的功能Brian,如果我按照你的建议运行它,进程似乎进入无限循环(内存错误),我认为你的两个嵌套循环有问题。您好,Brian,经过几次尝试,我无法获得我想要的结果,我将格式文件更改为JPG,现在我的列表“BMP”包含我的JPG文件。在我运行您的建议后,我得到以下消息:IndexError:索引2超出大小为2的轴0的界限
 plt.figure(1)
 plt.subplot(211)
 plt.imshow(img1)

 plt.subplot(212)
 plt.imshow(img2)
 plt.show()
for idx, arch in enumerate(bmps):
    i = idx % 3 # Get subplot row
    j = idx // 3 # Get subplot column
    image = Image.open(arch)
    iar_shp = np.array(image).shape # Get h,w dimensions
    image = image.convert('L') # convert to grayscale
    # Load grayscale matrix, reshape to dimensions of color bmp
    iar = np.array(image.getdata()).reshape(iar_shp[0], iar_shp[1])
    axes[i, j].plot(iar)
 plt.subplots_adjust(wspace=0, hspace=0)
 plt.show()