gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 00:26:53 25 4
gpt4 key购买 nike

如下图第一张所示,有一个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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com