Table of Contents
To display an image as grayscale in Matplotlib, you can use the cmap parameter in the imshow function. This parameter takes a string argument representing a colormap name, such as ‘gray’, ‘bone’, etc. You can also use a custom colormap. As an example, to display a 2D array ‘img’ as grayscale, you would use the following code: plt.imshow(img, cmap=’gray’). This will create a grayscale image of the array.
You can use the cmap argument in Matplotlib to easily display images on a .
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()
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.
The following tutorials explain how to perform other common tasks in Matplotlib: