我正在尝试使用python PIL读取RGBA BMP,但似乎不起作用。 以下代码段显示tensorflow bmp_decode函数在此任务中成功完成,而PIL则未成功
abc = 'With three words'
#x = abc.split()
x = list()
for i in range(len(abc)):
if abc[i] == ' ':
y = x.append(abc[:i])
continue
print(x)
输出:
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)
上运行imgobj.convert('RGBA')
时,我得到的矩阵只包含255(透明度为100%,这不是每个像素的正确Alpha值)。
PIL中是否有错误?除了使用python读取RGBA之外,还有其他选择吗?
答案 0 :(得分:2)
PIL 不支持32位位图图像。正如official documentation所述:-
枕头读取和写入包含
1
,L
,P
或RGB
数据的Windows和OS / 2 BMP文件。将16色图像读取为P图像。不支持行程编码。
因此,通常建议不要使用Image.show()
查看图像,因为它会在显示图像之前将其转换为.bmp
。因此,如果图像包含alpha值(彩色模式LA
,RGBA
等图像),则显示的图像将无法正确显示,并且会出现伪像。
因此,当您尝试在PIL中打开具有.bmp
颜色空间的RGBA
图像时,颜色空间将被截断为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