matplotlib - 为什么 bmp 图像在 IPython-notebook 上使用 matplotlib 的 plt.imshow 显示为错误颜色?

标签 matplotlib ipython-notebook

如下图第一张所示,有一个bmp图像,其信息如下图第二张所示。但是在 IPython-notebook 上使用 matplotlib 的 plt.imshow() 函数显示时,颜色错误,如下图第三张。那我能知道原因吗?
谢谢!

enter image description here

enter image description here

enter image description here

原始文件已在 Dropbox https://dl.dropboxusercontent.com/u/26518813/test2.bmp 共享

在 IPython-notebook 上显示图像的代码是:

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

最佳答案

发生这种情况是因为您实际上是使用 matplotlib.pyplot 将图像绘制为矩阵。 Matplotlib 不支持 .bmp native 所以我认为默认cmap存在一些错误。在您的特定情况下,您有一个灰度图像。所以实际上你可以用 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 将拉伸(stretch)到 min max 值。
这是一个不导入 PIL 的解决方案:
img=matplotlib.image.imread(r'/Users/giacomo/Downloads/test2.bmp')
plt.imshow(img,cmap='gray',vmin=0,vmax=255)

或者,您可以使用 PIL 显示图像,也可以将图像转换为 .png前。

如果你想用 PIL.Image 显示图像你可以使用这个:
from PIL import Image
img= Image.open( r'./test/test2.bmp')
img.show()

请注意,如果您使用的是 I-Python Notebook,图像会显示在一个新的外部窗口中

另一种选择是将图像的模式更改为 'P' (调色板编码:每个像素一个字节,带有类 ImagePalette 的调色板将像素转换为颜色)。与 .convert然后用 matplotlib plt.imshow 绘制图像:
convertedimg=img.convert('P')
plt.imshow(convertedimg)

enter image description here

关于matplotlib - 为什么 bmp 图像在 IPython-notebook 上使用 matplotlib 的 plt.imshow 显示为错误颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21641822/

相关文章:

ipython - `get_ipython' 在 IPython/IPython Notebook 的启动脚本中不起作用...?

IPython 笔记本 : Open/select file with GUI (Qt Dialog)

python - 如何在 IPython/Jupyter 笔记本中自动加载配置文件?

python - 使用 Matplotlib 绘制动画股票价格

python - 在连续的绘图命令期间关闭自动颜色循环

python - 如何在 Python 中将直方图的 y 轴值乘以固定数字

visual-studio - 我可以将用于 Visual Studio 的交互式 Python 工具与现有的 ipython 内核连接起来吗

port - 如何在笔记本服务器停止后释放其保留的端口?

python - 如何将手动自定义的 seaborn 图添加到 JointGrid/jointplot

python - 使用 Binned X 值制作条形图 Python