如何使用Pillow

时间:2016-08-03 22:58:09

标签: python pillow

如何使用Pillow从PNG导出alpha遮罩?

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

2 个答案:

答案 0 :(得分:2)

# 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)

答案 1 :(得分:1)

如果您只需要一个频道,则有一种更新、更有效的方法:image.getchannel()

这也会返回一个新的图像,模式为“L”,它减少了几个额外的保存步骤。

例如:

image = Image.open( inputImagePath ).convert( 'RGBA' )
alphaChannelImage = image.getchannel( 'A' ) # Mode 'L'

# If you want a paletted image to save space (optional line)
alphaChannelImage.convert( 'P', palette=Image.ADAPTIVE )

alphaChannelImage.save( outputImagePath )