繁体   English   中英

Pillow/NP:当透明度为二进制格式时,如何将透明映射(索引)PNG 转换为 RGBA

[英]Pillow/NP: how to convert transparent mapped (indexed) PNG to RGBA when transparency is in binary format

我需要将透明映射(索引)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")

我的问题是我必须管理透明度由多个值定义的图像,实际上是一个二进制值。 我在这种情况下 transp_byte 变成了:

b'\x00\x0e\x19#.8BLVq\x8e\x80`\x9a\xfe\x17.\xb7F\xd2\xea\xfd\xfe`\xfe\xdf\x9d\x86\xd1\xc0\xd9|\xbe\xa6\xa4\xfdt\xc2\x8a'

我应该如何将此类二进制信息转换为有效的掩码?

实际上,答案比预期的要简单,因为 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")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM