使用python PIL读取BMP RGBA不会';炒锅

使用python PIL读取BMP RGBA不会';炒锅,python,python-imaging-library,Python,Python Imaging Library,我正在尝试使用python PIL读取RGBA BMP,但它似乎不起作用。 以下代码段显示tensorflow bmp_解码函数在此任务中成功,而PIL未成功: def read_image_tf(filename): image_file = tf.read_file(filename, name='read_file') decoded_bmp = tf.io.decode_bmp(bmp_image) return decod

我正在尝试使用python PIL读取RGBA BMP,但它似乎不起作用。 以下代码段显示tensorflow bmp_解码函数在此任务中成功,而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)
当尝试在
Image.open(fh)
上运行
imgobj.convert('RGBA')
时,我只得到一个矩阵,它只包含255的值(100%透明度,这不是每像素正确的alpha值)


PIL中有bug吗?除了使用python读取RGBA,还有其他方法吗?

PIL不支持32位位图图像。作为缔约国:-

枕头读取和写入包含
1
L
p
RGB
数据的Windows和OS/2 BMP文件。16个彩色图像被读取为P图像。不支持运行长度编码

这就是为什么通常建议不要使用
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
输出:-

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

你能分享这个麻烦的BMP文件吗?您可能需要使用Dropbox或Google Drive或类似工具。谢谢您的回答,这很有意义。那么,您建议如何使用python读取RGBA bmp文件呢?@Protostome您可以使用
cv2
(OpenCV)库来实现这一点
cv2
在图像处理方面比PIL强大得多。谢谢。对于任何未来的访问者-这是我使用cv2阅读RGBA BMP的方式:
cv2.imread(文件名,cv2.imread\u不变)