11.1 C
London
Sunday, July 7, 2024
HomePythonMatplotlib in PythonDisplay an Image as Grayscale in Matplotlib (With Example)

Display an Image as Grayscale in Matplotlib (With Example)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories