61

How do I use the matlib function plt.imshow(image) to display multiple images?

For example my code is as follows:

for file in images:
    process(file)

def process(filename):
    image = mpimg.imread(filename)
    <something gets done here>
    plt.imshow(image)

My results show that only the last processed image is shown effectively overwriting the other images

1

5 Answers 5

60

To display the multiple images use subplot()

plt.figure()

#subplot(r,c) provide the no. of rows and columns
f, axarr = plt.subplots(4,1) 

# use the created array to output your multiple images. In this case I have stacked 4 images vertically
axarr[0].imshow(v_slice[0])
axarr[1].imshow(v_slice[1])
axarr[2].imshow(v_slice[2])
axarr[3].imshow(v_slice[3])
2
  • 2
    What is v_slice here? @AadharBhatt Oct 12, 2021 at 17:36
  • 1
    @WhyMeasureTheory It stands for vertical slice, as we are using 4 images which are sacked vertically. Nov 3, 2021 at 5:21
48

You can set up a framework to show multiple images using the following:

import matplotlib.pyplot as plt
import matplotlib.image as mpimg

def process(filename: str=None) -> None:
    """
    View multiple images stored in files, stacking vertically

    Arguments:
        filename: str - path to filename containing image
    """
    image = mpimg.imread(filename)
    # <something gets done here>
    plt.figure()
    plt.imshow(image)

for file in images:
    process(file)

This will stack the images vertically

1
12

In first instance, load the image from file into a numpy matrix

from typing import Union,List
import numpy
import cv2
import os
def load_image(image: Union[str, numpy.ndarray]) -> numpy.ndarray:
    # Image provided ad string, loading from file ..
    if isinstance(image, str):
        # Checking if the file exist
        if not os.path.isfile(image):
            print("File {} does not exist!".format(imageA))
            return None
        # Reading image as numpy matrix in gray scale (image, color_param)
        return cv2.imread(image, 0)

    # Image alredy loaded
    elif isinstance(image, numpy.ndarray):
        return image

    # Format not recognized
    else:
        print("Unrecognized format: {}".format(type(image)))
        print("Unrecognized format: {}".format(image))
    return None

Then you can plot multiple image using the following method:

import matplotlib.pyplot as plt
def show_images(images: List[numpy.ndarray]) -> None:
    n: int = len(images)
    f = plt.figure()
    for i in range(n):
        # Debug, plot figure
        f.add_subplot(1, n, i + 1)
        plt.imshow(images[i])

    plt.show(block=True)

The show_images method take in input a list of images that you can read iteratively using the load_image method.

3

Using a plt.show() after plt.imshow(image) while in the for loop worked for me.

for file in images:
    process(file)
    
def process(filename):
    image = mpimg.imread(filename)
    # <something gets done here>
    plt.imshow(image)
    plt.show()
1
0

Building on Aadhar Bhatt's answer:

from matplotlib.image import imread
import matplotlib.pyplot as plt

v_slice = [] #create an empty list called v_slice
for i in range(0,4):
    image = imread("test.png") #Here I load the same image 4 times-replace this  with code that generates images
    v_slice.append(image)


#Aadhar Bhatt's answer
plt.figure()
#subplot(r,c) provide the no. of rows and columns
f, axarr = plt.subplots(4,1) 
# use the created array to output your multiple images. In this case I have stacked 4 images vertically
axarr[0].imshow(v_slice[0])
axarr[1].imshow(v_slice[1])
axarr[2].imshow(v_slice[2])
axarr[3].imshow(v_slice[3])
3
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Jan 19, 2023 at 5:30
  • How do you view the output?
    – Jeff Bezos
    Feb 1, 2023 at 21:30
  • So, I just ran the code above in a jupyter notebook cell. You can literally just copy/paste my code into jupyter notebook. Make sure that you have a file called test.png that is in the same directory as your project. (The default directory is C:/Users/yourusername if you're not sure where your project is). Then the output (picture) will appear below the cell. I installed Anaconda Navigator and then Jupyter notebook, instructions here: sparkbyexamples.com/python/install-anaconda-jupyter-notebook Feb 2, 2023 at 22:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.