简体   繁体   中英

plt.gray() is not working and displaying original color image in matplotlib

With the following code, plt.gray() is not working and showing a colour image instead of grayscale. Even I put cmap="gray" separately in plt.imshow , still it is showing the image in colour. Thank you. (Please note, the original image smallimage.jpg is a colour image)

from matplotlib import image as image, pyplot as plt
img  = image.imread('/content/drive/MyDrive/Z ML Lab/data/smallimage.jpg')
plt.gray()
plt.imshow(img, cmap="gray")

Your image is RGB color. From the imshow docstring:

cmap : str or `~matplotlib.colors.Colormap`, default: :rc:`image.cmap`
    The Colormap instance or registered colormap name used to map
    scalar data to colors. This parameter is ignored for RGB(A) data.

Note in particular "This parameter is ignored for RGB(A) data."

If you want to display the image as grayscale, you'll have to "flatten" the colors somehow. There are several ways to do this; one is to display just one of the color channels, eg

plt.imshow(img[:, :, 0], cmap="gray")  # Display the red channel

Another popular method is to take a weighted average of the channels, with weights [0.299, 0.587, 0.113]:

imshow(img @ [0.299, 0.587, 0.113], cmap='gray')

See "Converting colour to grayscale" for more ideas.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM