How to Load and Visualize Multiple Images in Python

In this post we learn how to read/ load multiple images in Python and also how to display multiple images in a single figure. We use OpenCV to read the image and Matplotlib library to display multiple images.

Import Necessary Libraries

import glob
import cv2
import matplotlib.pyplot as plt

Read and Display a Single Image 

file = 'D:\BinaryStudy\demo\Images\image001.tif'
image = cv2.imread(file)
cv2.imshow('display', image)
cv2.waitKey(0)
cv2.destrouAllWindows() 

You may be interested in the below article.

Different Ways to Load Images in Python from Scratch

Read All images

file = 'D:\BinaryStudy\demo\Images\*.tif' 
glob.glob(file)
# Using List Comprehension to read all images
images = [cv2.imread(image) for image in glob.glob(file)]

Now we have loaded all the images in the list named "images". We apply here List Comprehension to read all the images in a list.

To check what is the type and length of the "images" use type() and len().

type(images)
len(images)

Output:

list
69

We have loaded 69 images in a list named "images".

Display Some Images

We define a figure to display the multiple images. Here we display 4 images in two rows and two columns. Have a look at the following Python code.

# Define a figure of size (8, 8)
fig=plt.figure(figsize=(88))
# Define row and cols in the figure
rows, cols = 22
# Display first four images
for j in range(0, cols*rows):
  fig.add_subplot(rows, cols, j+1)
  plt.imshow(images[j])
plt.show()

Output:

Display Multiple Images in a Single Figure
First Four Images in Single Figure

Display All Images

We display all the images in the list "images". See the bellow Python 3 code.

# Define row and cols in the figure
rows, cols = 23
for i in range(0len(images), rows*cols):
    fig=plt.figure(figsize=(88))
    for j in range(0, cols*rows):
        fig.add_subplot(rows, cols, j+1)
        plt.imshow(images[i+j])
    plt.show()

Comments