hammu
hammu

Reputation: 463

plot several image files in matplotlib subplots

I would like to create a matrix subplot and display each BMP files, from a directory, in a different subplot, but I cannot find the appropriate solution for my problem, could somebody helping me?.

This the code that I have:

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()

I am having the following error after executing:

enter image description here

Upvotes: 24

Views: 82613

Answers (2)

Brian Huey
Brian Huey

Reputation: 1630

The bmp has three color channels, plus the height and width, giving it a shape of (h,w,3). I believe plotting the image gives you an error because the plot only accepts two dimensions. You could grayscale the image, which would produce a matrix of only two dimensions (h,w).

Without knowing the dimensions of the images, you could do something like this:

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()

Upvotes: 6

ralf htp
ralf htp

Reputation: 9422

natively matplotlib only supports PNG images, see http://matplotlib.org/users/image_tutorial.html

then the way is always read the image - plot the image

read image

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

plot image (2 subplots)

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

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

follow the tutorial on http://matplotlib.org/users/image_tutorial.html (because of the import libraries)

here is a thread on plotting bmps with matplotlib: Why bmp image displayed as wrong color with plt.imshow of matplotlib on IPython-notebook?

Upvotes: 40

Related Questions