【问题标题】:Reading BMP RGBA using python PIL doesn't work使用 python PIL 读取 BMP RGBA 不起作用
【发布时间】:2021-10-06 13:06:58
【问题描述】:

我正在尝试使用 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 的替代方法?

【问题讨论】:

  • 可以分享一下麻烦的BMP文件吗?您可能必须使用 Dropbox 或 Google Drive 或类似工具。

标签: python python-imaging-library


【解决方案1】:

PIL 不支持 32 位图图像。正如official documentation 所说:-

Pillow 读取和写入包含 1LPRGB 数据的 Windows 和 OS/2 BMP 文件。 16 色图像被读取为 P 图像。不支持游程编码。

这就是为什么通常不建议使用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 读取 RGBA bmp 文件?
  • @Protostome 您可以为此使用cv2 (OpenCV) 库。 cv2 在图像处理方面比 PIL 强大得多。
  • 这行得通,谢谢。对于任何未来的访问者 - 这就是我使用 cv2 读取 RGBA BMP 的方式:cv2.imread(FILENAME,cv2.IMREAD_UNCHANGED)
猜你喜欢
  • 2016-02-10
  • 2011-04-05
  • 2012-05-14
  • 1970-01-01
  • 2020-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-28
相关资源
最近更新 更多