Categories
Python Answers

How to display image as grayscale using Python matplotlib?

Spread the love

Sometimes, we want to display image as grayscale using Python matplotlib.

In this article, we’ll look at how to display image as grayscale using Python matplotlib.

How to display image as grayscale using Python matplotlib?

To display image as grayscale using Python matplotlib, we can use thge imshow method with the cmap argument set to 'gray'.

For instance, we write

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

fname = 'image.png'
image = Image.open(fname).convert("L")
arr = np.asarray(image)
plt.imshow(arr, cmap='gray', vmin=0, vmax=255)
plt.show()

to open the image.png file with Image.open.

And then we convert the image to a NumPy array with np.asarray.

Then we call imshow with the arr NumPy array and cmap set to 'gray' to render the image as a grayscale image.

Then we call show to show the image.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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