Display Images with Matplotlib

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

This tutorial will guide you through the process of displaying images using Matplotlib's imshow function. You will learn how to use different interpolation methods to display images with Matplotlib.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.

Import Required Libraries

The first step is to import the required libraries. In this tutorial, we will be using Matplotlib and NumPy libraries.

import matplotlib.pyplot as plt
import numpy as np

Create Random Grid

The next step is to create a random grid of 4x4 using NumPy library.

np.random.seed(19680801)
grid = np.random.rand(4, 4)

Define Interpolation Methods

Define the list of interpolation methods which we want to use to display images.

methods = [None, 'none', 'nearest', 'bilinear', 'bicubic', 'spline16',
           'spline36', 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric',
           'catrom', 'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos']

Create Subplots

Create subplots to display the images using interpolation methods.

fig, axs = plt.subplots(nrows=3, ncols=6, figsize=(9, 6),
                        subplot_kw={'xticks': [], 'yticks': []})

Display Images

Display the images using the imshow function and different interpolation methods.

for ax, interp_method in zip(axs.flat, methods):
    ax.imshow(grid, interpolation=interp_method, cmap='viridis')
    ax.set_title(str(interp_method))

Show the Plot

Show the plot using the show function of Matplotlib.

plt.tight_layout()
plt.show()

Summary

In this tutorial, you learned how to use Matplotlib's imshow function to display images with different interpolation methods. You also learned how to create subplots and display images on them using Matplotlib.

Other Python Tutorials you may like