使用PIL和Imageio正确加载二进制掩码/GIF

2024-09-29 19:27:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须在Python中加载包含二进制掩码的gif

inputmask

import numpy as np

from PIL import Image
import imageio

from matplotlib import pyplot as plt


maskPIL = np.array(Image.open('mask.gif'))


maskIO = np.array(imageio.imread('mask.gif'))


plt.subplot(1,2,1)
plt.title('PIL Mask')
plt.imshow(maskPIL,cmap='Greys')


plt.subplot(1,2,2)
plt.title('ImageIO Mask')
plt.imshow(maskIO,cmap='Greys')

plt.show()

Result

为什么这两种方法表现不同?

PIL版本:8.0.1

imageio版本:2.9.0


Tags: fromimageimportpiltitleasnpplt
1条回答
网友
1楼 · 发布于 2024-09-29 19:27:24

如果您这样做:

im = Image.open('mask.gif')
print(im)

输出

<PIL.GifImagePlugin.GifImageFile image mode=P size=683x512 at 0x7FC0C86FF430>

您将看到您的图像是一个调色板图像-因为mode=P。这意味着图像中的值不是RGB或灰度值,而是索引到调色板中。如果您查看调色板:

np.array(im.getpalette()).reshape(256,3)
Out[25]: 
array([[255, 255, 255],      < - palette entry 0
       [  0,   0,   0],      < - palette entry 1
       [  2,   2,   2],
       [  3,   3,   3],
       [  4,   4,   4],
       [  5,   5,   5],
       ...
       ...

您将看到条目0是rgb(255255),因此这意味着无论您的图像中哪里有零,它都应该显示为白色!无论图像中的哪个位置有一个,它都应该显示为黑色

如果您想要正确的值,如灰度,则需要将图像转换为L模式,然后所有像素都将是实际的灰度值:

maskPIL = np.array(Image.open('mask.gif').convert('L'))

更充分的解释here

相关问题 更多 >

    热门问题