How to display image as grayscale using Python matplotlib?

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.