如何使用Pi从图像中提取alpha通道

2024-10-16 20:41:26 发布

您现在位置:Python中文网/ 问答频道 /正文

如何从PNG使用枕头输出阿尔法面罩?在

理想情况下,结果将是代表alpha通道的灰度图像。在


Tags: 图像alphapng情况代表灰度枕头理想
1条回答
网友
1楼 · 发布于 2024-10-16 20:41:26
# Open the image and convert it to RGBA, just in case it was indexed
image = Image.open(image_path).convert('RGBA')

# Extract just the alpha channel
alpha = image.split()[-1]

# Unfortunately the alpha channel is still treated as such and can't be dumped
# as-is

# Create a new image with an opaque black background
bg = Image.new("RGBA", image.size, (0,0,0,255))

# Copy the alpha channel to the new image using itself as the mask
bg.paste(alpha, mask=alpha)

# Since the bg image started as RGBA, we can save some space by converting it
# to grayscale ('L') Optionally, we can convert the image to be indexed which
# saves some more space ('P') In my experience, converting directly to 'P'
# produces both the Gray channel and an Alpha channel when viewed in GIMP,
# althogh the file sizes is about the same
bg.convert('L').convert('P', palette=Image.ADAPTIVE, colors=8).save(
                                                                mask_path,
                                                                optimize=True)

相关问题 更多 >