为什么在IPython笔记本上使用matplotlib的plt.imshow将bmp图像显示为错误的颜色? [英] Why bmp image displayed as wrong color with plt.imshow of matplotlib on IPython-notebook?
问题描述
有一个bmp图像,如第一个图像波纹管所示,其信息列在第二个图像波纹管中.但是,当在IPython笔记本上使用matplotlib的plt.imshow()函数显示时,它的颜色错误,就像下面的第三个图片一样.我能知道原因吗?
谢谢!
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!
原始文件已在Dropbox https://dl.dropboxusercontent.com/上共享. u/26518813/test2.bmp
The original file has shared at dropbox https://dl.dropboxusercontent.com/u/26518813/test2.bmp
在IPython笔记本上显示图像的代码为:
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"))
推荐答案
之所以会发生这种情况,是因为您实际上是使用matplotlib.pyplot将图像绘制为矩阵. Matplotlib本机不支持.bmp
,因此我认为默认cmap会有一些错误.在您的特定情况下,您有一个灰度图像.因此,实际上您可以使用cmap="gray"
将颜色图更改为灰度.
This happen because you are actually plotting the image as matrix with matplotlib.pyplot. Matplotlib doesn't support .bmp
natively 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)
请注意,如果要再现原始图像的相同亮度,则必须设置vmin和vmax,否则我认为python默认情况下会拉伸到min max值. 这是不导入PIL的解决方案:
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)
或者,您可以使用PIL显示图像,也可以将图像转换为.png
.
Alternatively you can use PIL to show the image or you can convert your image to a .png
before.
如果要使用PIL.Image
显示图像,可以使用以下方法:
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()
请注意,如果您使用的是I-Python Notebook,则图像会显示在新的外部窗口中
另一种选择是将图像的模式更改为'P'
(调色板编码:每个像素一个字节,使用ImagePalette类的调色板将像素转换为颜色).使用.convert
,然后使用matplotlib plt.imshow
绘制图像:
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)
这篇关于为什么在IPython笔记本上使用matplotlib的plt.imshow将bmp图像显示为错误的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!