Display an Image as Grayscale in Matplotlib (With Example)


You can use the cmap argument in Matplotlib to easily display images on a grayscale.

The following example shows how to use this argument in practice.

Example: Display Image as Grayscale in Matplotlib

Suppose I have the following image called shapes.JPG that I’d like to display in Matplotlib:

I can use the following syntax to display this image using the original colors:

import numpy as np
import matplotlib.pyplot as plt
from PIL import Image

image=Image.open('shapes.JPG')
plt.imshow(image)
plt.show()

Notice that this image perfectly matches the image I had on file.

In order to display the image on a grayscale, I must use the cmap=’gray’ argument as follows:

import numpy as np
import matplotlib.pyplot as plt
from PIL import Image

#open image
image=Image.open('shapes.JPG')

#convert image to black and white pixels
gray_image=image.convert('L')

#convert image to NumPy array
gray_image_array=np.asarray(gray_image)

#display image on grayscale
plt.imshow(gray_image_array, cmap='gray')
plt.show()

Matplotlib grayscale image

The image has now been converted to a grayscale.

Note: The ‘L’ argument converts the image to black and white pixels. Without first using this line of code, the image will not display as a grayscale.

Additional Resources

The following tutorials explain how to perform other common tasks in Matplotlib:

How to Show Gridlines on Matplotlib Plots
How to Draw Rectangles in Matplotlib
How to Increase Plot Size in Matplotlib
How to Set Axis Ticks in Matplotlib

Leave a Reply

Your email address will not be published. Required fields are marked *