我正在尝试使用 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
, orRGB
data. 16-colour images are read as P images. Run-length encoding is not supported.
这就是为什么通常建议不要使用 Image.show()
来查看图像,因为它会在显示图像之前将图像转换为 .bmp
。因此,如果图像包含 alpha 值(颜色模式 LA
、RGBA
等的图像),则显示的图像将无法正确显示,并且会出现伪影。
因此,当您尝试在 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/