0
0
Matplotlibdata~5 mins

Displaying images with imshow in Matplotlib

Choose your learning style9 modes available
Introduction

We use imshow to show pictures or image data on the screen. It helps us see what the image looks like in a simple way.

You want to check how an image looks after loading it from a file.
You need to visualize the results of image processing or editing.
You want to display a heatmap or matrix as an image.
You are exploring data that is stored as pixels or colors.
You want to compare two images side by side visually.
Syntax
Matplotlib
matplotlib.pyplot.imshow(X, cmap=None, interpolation=None)

# X is the image data (array or matrix)
# cmap sets the color map (for grayscale or color)
# interpolation smooths the image display

X is usually a 2D or 3D array representing the image pixels.

cmap is useful for grayscale images to choose how shades appear.

Examples
Shows a random 10x10 grayscale image with default colors.
Matplotlib
import matplotlib.pyplot as plt
import numpy as np

image = np.random.rand(10, 10)
plt.imshow(image)
plt.show()
Displays the same image in grayscale colors.
Matplotlib
plt.imshow(image, cmap='gray')
plt.show()
Shows a random 10x10 color image with RGB channels.
Matplotlib
color_image = np.random.rand(10, 10, 3)
plt.imshow(color_image)
plt.show()
Sample Program

This program creates a small 5x5 image where pixel values increase from top-left to bottom-right. It shows the image with a color map and a color bar to explain the colors.

Matplotlib
import matplotlib.pyplot as plt
import numpy as np

# Create a simple 5x5 image with a gradient
image = np.array([[i + j for j in range(5)] for i in range(5)])

plt.imshow(image, cmap='viridis')
plt.colorbar()  # Show color scale
plt.title('Simple Gradient Image')
plt.show()
OutputSuccess
Important Notes

Always call plt.show() to display the image window.

You can add plt.colorbar() to show the color scale next to the image.

Images can be grayscale (2D arrays) or color (3D arrays with 3 channels for RGB).

Summary

imshow shows image data as a picture.

You can control colors with cmap and smoothness with interpolation.

Use plt.show() to see the image on screen.