如何用PIL获取PNG图像的透明度值?

32 投票
5 回答
55878 浏览
提问于 2025-04-15 17:22

如何使用PIL检测PNG图片是否有透明的alpha通道?

img = Image.open('example.png', 'r')
has_alpha = img.mode == 'RGBA'

通过上面的代码,我们可以知道一张PNG图片是否有alpha通道,但我们该如何获取alpha值呢?

我在img.info字典中没有找到'transparency'这个键,正如在PIL的网站上所描述的那样。

我正在使用Ubuntu,并且已经安装了zlib1g和zlibc包。

5 个回答

4
# python 2.6+

import operator, itertools

def get_alpha_channel(image):
    "Return the alpha channel as a sequence of values"

    # first, which band is the alpha channel?
    try:
        alpha_index= image.getbands().index('A')
    except ValueError:
        return None # no alpha channel, presumably

    alpha_getter= operator.itemgetter(alpha_index)
    return itertools.imap(alpha_getter, image.getdata())

当然可以!请把你想要翻译的内容发给我,我会帮你把它变得简单易懂。

6

你可以通过将图像转换为字符串的方式,一次性提取整个图像的透明度数据,使用'A'模式。例如,这个例子就是从图像中获取透明度数据,并将其保存为灰度图像哦 :)

from PIL import Image

imFile="white-arrow.png"
im = Image.open(imFile, 'r')
print im.mode == 'RGBA'

rgbData = im.tostring("raw", "RGB")
print len(rgbData)
alphaData = im.tostring("raw", "A")
print len(alphaData)

alphaImage = Image.fromstring("L", im.size, alphaData)
alphaImage.save(imFile+".alpha.png")
63

要获取一张RGBA图片的透明度层,你只需要这样做:

red, green, blue, alpha = img.split()

或者

alpha = img.split()[-1]

还有一种方法可以设置透明度层:

img.putalpha(alpha)

透明色键只是在调色板模式(P)中用来定义透明度的。如果你想同时处理调色板模式的透明情况,并且覆盖所有情况,你可以这样做:

if img.mode in ('RGBA', 'LA') or (img.mode == 'P' and 'transparency' in img.info):
    alpha = img.convert('RGBA').split()[-1]

注意:当图片的模式是LA时,需要使用convert方法,这是因为PIL里有个bug。

撰写回答