首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用Pillow从图像中提取alpha通道

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

Stack Overflow用户
提问于 2016-08-04 06:58:09
回答 2查看 4.3K关注 0票数 1

如何使用Pillow从PNG导出一个alpha蒙版?

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-08-04 06:58:09

代码语言:javascript
运行
复制
# 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)
票数 4
EN

Stack Overflow用户

发布于 2021-01-15 02:48:30

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

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

例如:

代码语言:javascript
运行
复制
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 )
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38754957

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档