python - 使用python PIL读取BMP RGBA不起作用

标签 python python-imaging-library

我正在尝试使用 python PIL 读取 RGBA BMP,但它似乎不起作用。 以下代码段显示tensorflow bmp_decode函数在此任务中成功,而PIL则没有:

def read_image_tf(filename):
    image_file = tf.read_file(filename, name='read_file')                    
    decoded_bmp = tf.io.decode_bmp(bmp_image)
    return decoded_bmp
def read_img_pil(filename):
    img = np.asarray(Image.open(fh))
    return img

img = K.eval(read_image_tf(<FILENAME>))
print (img.shape)
img = read_img_pil(<FILENAME>)
print (img.shape)

输出:

(3892, 3892, 4)
(3892, 3892, 3)

当尝试在 Image.open(fh) 上运行 imgobj.convert('RGBA') 时,我只是得到一个仅包含 255 (100 % 透明度,这不是每个像素的正确 Alpha 值)。

PIL 是否有错误?有没有使用 python 读取 RGBA 的替代方法?

最佳答案

PIL 不支持 32 位位图图像。作为official documentation状态:-

Pillow reads and writes Windows and OS/2 BMP files containing 1, L, P, or RGB data. 16-colour images are read as P images. Run-length encoding is not supported.

这就是为什么通常建议不要使用 Image.show() 来查看图像,因为它会在显示图像之前将图像转换为 .bmp。因此,如果图像包含 alpha 值(颜色模式 LARGBA 等的图像),则显示的图像将无法正确显示,并且会出现伪影。

因此,当您尝试在 PIL 中打开具有 RGBA 颜色空间的 .bmp 图像时,颜色空间会被截断为 RGB

示例:-

from PIL import Image

# creating an red colored image with RGBA color space and full opacity
img = Image.new("RGBA", (100, 100), (255, 0, 0, 255))

# displaying the color mode of the image
print(img.mode)

# saving the image as a .bmp (bitmap)
img.save("new.bmp")

# Opening the previously saved .bmp image (having color mode RGBA)
img = Image.open("new.bmp")

# displaying the mode of the .bmp file
print(img.mode)

输出:-

RGBA
RGB

关于python - 使用python PIL读取BMP RGBA不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56920801/

相关文章:

python - 使用 Python 图像库 (PIL) 绘制抗锯齿线

python - 强制 Pillow 生成 TrueColor 类型的图像,而我只使用黑白

python - 返回 None 或元组并解包

Python 按日期和时间对 CSV 进行排序

python - 我需要在 SVM 中计算预测时间的历史记录吗?

python - 如何从python中的图像中去除白色模糊

python-3.x - 如何将 ImageTk 转换为图像?

python - python中的变量范围和Try Catch

python - 在没有 Nans 的情况下组合 DataFrame

Python Mysqldb游标没有属性 'fetchAll'