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 globimport cv2import 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 ScratchRead All images
file = 'D:\BinaryStudy\demo\Images\*.tif'glob.glob(file)# Using List Comprehension to read all imagesimages = [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=(8, 8))# Define row and cols in the figurerows, cols = 2, 2# Display first four imagesfor j in range(0, cols*rows):fig.add_subplot(rows, cols, j+1)plt.imshow(images[j])plt.show()
Output:
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 figurerows, cols = 2, 3for i in range(0, len(images), rows*cols):fig=plt.figure(figsize=(8, 8))for j in range(0, cols*rows):fig.add_subplot(rows, cols, j+1)plt.imshow(images[i+j])plt.show()
Comments
Post a Comment