Display image as grayscale using matplotlib

Viewed 566865

I'm trying to display a grayscale image using matplotlib.pyplot.imshow(). My problem is that the grayscale image is displayed as a colormap. I need it to be grayscale because I want to draw on top of the image with color.

I read in the image and convert to grayscale using PIL's Image.open().convert("L")

image = Image.open(file).convert("L")

Then I convert the image to a matrix so that I can easily do some image processing using

matrix = scipy.misc.fromimage(image, 0)

However, when I do

figure()  
matplotlib.pyplot.imshow(matrix)  
show()

it displays the image using a colormap (i.e. it's not grayscale).

What am I doing wrong here?

9 Answers

try this:

import pylab
from scipy import misc

pylab.imshow(misc.lena(),cmap=pylab.gray())
pylab.show()

Use no interpolation and set to gray.

import matplotlib.pyplot as plt
plt.imshow(img[:,:,1], cmap='gray',interpolation='none')

When the image has purple & yellow color.

change way of saving image:
plt.imsave(...., cmap='gray')

plt.imshow(img[:,:,0], cmap='gray')

plt.imshow(img[:,:,1], cmap='gray')

plt.imshow(img[:,:,2], cmap='gray')

should work. But, the issue with this approach is that it is not true gray. It only changes one of RGB channel to gray.

look below.

from sklearn.datasets import load_sample_image
flower = load_sample_image("flower.jpg")

plt.subplot(1,4,1)
plt.imshow(flower)
plt.axis("off")
plt.title("Original")

# R level to gray
plt.subplot(1,4,2)
plt.imshow(flower[:,:,0], cmap='gray')
plt.axis("off")
plt.title("R to gray")


# G leval to gray
plt.subplot(1,4,3)
plt.imshow(flower[:,:,1], cmap='gray')
plt.axis("off")
plt.title("R to gray")

# B leval to gray
plt.subplot(1,4,4)
plt.imshow(flower[:,:,2], cmap='gray')
plt.axis("off")
plt.title("R to gray")

plt.show()

[Result images]

Related