chenzhongpu
chenzhongpu

Reputation: 6861

Why does pyplot display wrong grayscale image?

I have a grayscale image:

enter image description here

But plt.inshow displays a wrong image (clearly, it differs from the origin one):

from PIL import Image
import matplotlib.pyplot as plt
import matplotlib.cm as cm
img = Image.open('...')
plt.imshow(image, cmap=cm.gray)

the output is

enter image description here

I tried the img.show() method, and it can display the same image as the origin one.

My question is: how to display grayscale image correctly using pyplot?

I have tried Display image as grayscale using matplotlib, but it dose not work still.

Upvotes: 3

Views: 1040

Answers (1)

tmdavison
tmdavison

Reputation: 69076

imshow will by default stretch and normalise the data so the minimum value becomes black and the maximum becomes white. You data currently is within the range 90 to 138, so it will map 90->black and 138->white.

To prevent this happening, you can give imshow the real min and max; in this case I think you want to set vmin=0, vmax=255. Try this:

plt.imshow(img, cmap=cm.gray, vmin=0, vmax=255)

For me that reproduces your original image.

Upvotes: 7

Related Questions