在Matplotlib子图中绘制多个图像文件

24

我想创建一个矩阵子图,将来自一个目录的每个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()
我执行后出现以下错误:

enter image description here

2个回答

40

原生的Matplotlib仅支持PNG图像,请参见http://matplotlib.org/users/image_tutorial.html

因此,通常的方法是读取图像 - 绘制图像

读取图像

 img1 = mpimg.imread('stinkbug1.png')
 img2 = mpimg.imread('stinkbug2.png')

绘制图像(2个子图)

 plt.figure(1)
 plt.subplot(211)
 plt.imshow(img1)

 plt.subplot(212)
 plt.imshow(img2)
 plt.show()

请按照http://matplotlib.org/users/image_tutorial.html的教程进行学习(因为需要导入库)

这里有一个关于使用 matplotlib 绘制 bmp 图像的讨论:Why bmp image displayed as wrong color with plt.imshow of matplotlib on IPython-notebook?


Ralf,感谢您的回复。如果我理解您的答案,我需要将格式从BMP更改为PNG,然后再次运行我的代码?您没有提到我的代码,如果我有PNG而不是BMP,您认为我的代码会运行吗?再次感谢。 - hammu
对于第一次尝试,我建议像http://matplotlib.org/1.3.1/users/pyplot_tutorial.html#pyplot-tutorial和上面的帖子一样保持简单。如果它有效,您可以添加更复杂的功能。 - ralf htp

6
有三个颜色通道,加上高度和宽度,形状为(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()

Brian,如果我按照你的建议运行它,似乎进程会陷入无限循环(内存错误)。 - hammu
我认为您的两个嵌套循环存在问题。请参考上面修订过的代码片段。 - Brian Huey
你好,Brian,经过多次尝试,我无法获得我想要的结果,我将文件格式更改为JPG,并且现在我的列表“bmps”包含了我的JPG文件。在运行您的建议后,我收到以下消息:IndexError: index 2 is out of bounds for axis 0 with size 2。 - hammu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接