user4933255
user4933255

Reputation:

In PIL, why isn't convert('L') turning image grayscale?

For a program I'm writing, I need to convert an RGB image to grayscale and read it as a NumPy array using PIL.

But when I run the following code, it converts the image not to grayscale, but to a strange color distortion a bit like the output of a thermal camera, as presented.

Any idea what the problem might be?

Thank you!

http://www.loadthegame.com/wp-content/uploads/2014/09/thermal-camera.png

from PIL import Image
from numpy import *
from pylab import *

im = array(Image.open('happygoat.jpg').convert("L"))

inverted = Image.fromarray(im)

imshow(inverted)
show()

Upvotes: 3

Views: 12624

Answers (2)

Anurag Gupta
Anurag Gupta

Reputation: 509

Add this code to view/display an image:

from PIL import Image;  
from numpy import *       
from pylab import *    

im = array(Image.open('happygoat.jpg').convert("L"));   

inverted = Image.fromarray(im);    
inverted   

Upvotes: -2

orlp
orlp

Reputation: 117691

matplotlib's imshow is aimed at scientific representation of data - not just image data. By default it's configured to use a high constrast color palette.

You can force it to display data using grayscale by passing the following option:

import matplotlib.cm
imshow(inverted, cmap=matplotlib.cm.Greys_r)

Upvotes: 11

Related Questions