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")
CodePudding user response:
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, e.g.
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.