How To Use Imshow In Python

In this tutorial, we will learn how to use the imshow function in Python. The imshow function is a part of matplotlib, which is a powerful 2D plotting library for Python.

It allows us to visualize images in various formats, such as JPG, BMP, and PNG, directly from our code. The imshow function takes an input image in the form of a 2D or 3D array and displays it on an axes system.

Let’s dive into the steps to use imshow in Python.

Step 1: Install the matplotlib library

First, ensure that you have the matplotlib library installed on your machine. If you do not have it already, you can use the following command to install it using pip:

Step 2: Import required libraries

Next, we need to import the necessary libraries for our code. We will need matplotlib.pyplot and NumPy as follows:

Step 3: Load or create the image

Before we can use imshow to display the image, we first need to load or create the image itself. In this example, we’ll create a simple image using a 2D NumPy array of random values:

The above code snippet creates an image of dimensions 10×10, filled with random grayscale values between 0 and 1.

Alternatively, if you want to load an existing image from your file system, you can use the imageio library, which provides a simple interface to read and save image data. First, install the imageio library using pip:

Then, you can load an image as follows:

Step 4: Display the image using imshow

Now that we have our image, we can display it using the imshow function from matplotlib.pyplot:

The imshow function will display the image array provided as an argument, and “” will display the image in a window.

Step 5: Customize the display (optional)

You can further customize the display of the image by using additional options available with imshow. For instance, you can change the color map, apply interpolation, and set axis labels:

The above code sets the color map to grayscale, applies the nearest-neighbor interpolation, and adds labels to the axis.

Full Code Example

Here is the complete code for displaying a random 10×10 grayscale image using the imshow function:



In this tutorial, we learned how to use the imshow function in Python for displaying images. The imshow function is an essential tool for visualizing and plotting images within your code, whether they are preloaded or generated.

Practice using different customization options and various types of images for a better understanding of the imshow function in Python.