我需要将透明映射(索引(PNG转换为RGBA。通常情况下,透明度是由一种单一的颜色定义的,基于Pillow和Numpy的以下代码可以工作:
from PIL import Image
import numpy as np
indexed = Image.open("mapped_image.png")
if indexed.mode == "P":
is_transparent = False
# check if transparent
transp_byte = indexed.info.get("transparency", -1)
for _, index in indexed.getcolors():
if index == transp_byte:
is_transparent = True
break
# convert indexed image to Numpy array
indexed_as_np = np.asarray(indexed)
# convert indexed image to RGB
image = indexed.convert("RGB")
# if transparency is confirmed then create the mask
if is_transparent:
mask = np.zeros(indexed_as_np.shape, dtype="uint8")
mask[indexed_as_np != transp_byte] = 255
# add mask to rgb image
mask = Image.fromarray(mask)
image.putalpha(mask)
elif indexed.mode == 'PA':
image = indexed.convert("RGBA")
我的问题是,我必须管理透明度由多个值定义的图像,实际上是一个二进制值。在这种情况下,transparen_byte变成类似于:
b'x00x0ex19#.8BLVqx8ex80`x9axfex17.xb7Fxd2xeaxfdxfe`xfexdfx9dx86xd1xc0xd9|xbexa6xa4xfdtxc2x8a'
我应该如何将这样的二进制信息转换为有效的掩码?
实际上,答案比预期的要简单,因为Pillow已经包含了这样的功能。以下代码解决了这个问题,并简化了我的原始代码:
from PIL import Image
indexed = Image.open("mapped_image.png")
if indexed.mode == "P":
# check if transparent
is_transparent = indexed.info.get("transparency", False)
if is_transparent is False:
# if not transparent, convert indexed image to RGB
image = indexed.convert("RGB")
else:
# convert indexed image to RGBA
image = indexed.convert("RGBA")
elif indexed.mode == 'PA':
image = indexed.convert("RGBA")