Why bmp image displayed as wrong color with plt.imshow of matplotlib on IPython-notebook?

陌路散爱 提交于 2019-12-21 03:03:33

问题


There is a bmp image just as shown the first picture bellow, and its information is list as the second picture bellow. But when display with plt.imshow() function of matplotlib on IPython-notebook, it has the wrong color, just as the third picture bellow. So can I know the reason?
Thanks!


The original file has shared at dropbox https://dl.dropboxusercontent.com/u/26518813/test2.bmp

And the code to show image on IPython-notebook is:

%pylab inline --no-import-all
from PIL import Image
plt.imshow(Image.open("./test/test2.bmp")) 

回答1:


This happen because you are actually plotting the image as matrix with matplotlib.pyplot. Matplotlib doesn't support .bmpnatively so I think there are some error with the default cmap. In your specific case you have a grayscale image. So in fact you can change the color map to grayscale with cmap="gray".

from PIL import Image
img= Image.open(r'./test/test2.bmp')
plt.imshow(img,cmap='gray',vmin=0,vmax=255)

Note you have to set vmin and vmax if you want to reproduce the same luminance of your original image otherwise I think python by default will stretch to min max the values. This is a solution without importing PIL:

img=matplotlib.image.imread(r'/Users/giacomo/Downloads/test2.bmp')
plt.imshow(img,cmap='gray',vmin=0,vmax=255)

Alternatively you can use PIL to show the image or you can convert your image to a .png before.

If you want show the image with PIL.Image you can use this:

from PIL import Image
img= Image.open( r'./test/test2.bmp')
img.show()

Note if you are using I-Python Notebook the image is shown in a new external window

Another option is to change the mode of the image to 'P' (Palette encoding: one byte per pixel, with a palette of class ImagePalette translating the pixels to colors). With .convert and then plot the image with matplotlib plt.imshow:

convertedimg=img.convert('P')
plt.imshow(convertedimg)



来源:https://stackoverflow.com/questions/21641822/why-bmp-image-displayed-as-wrong-color-with-plt-imshow-of-matplotlib-on-ipython

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!