如何使用PIL获取PNG图像的alpha值?

发布于 2024-08-15 19:40:33 字数 374 浏览 7 评论 0原文

如何使用 PIL 检测 PNG 图像是否具有透明 Alpha 通道?

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

通过上面的代码我们知道PNG图像是否有alpha通道,但是如何获取alpha值呢?

我在 img.info 字典中没有找到“透明度”键,如 PIL 的网站

我正在使用 Ubuntu 和 zlib1g,zlibc 软件包已经安装。

How to detect if a PNG image has transparent alpha channel or not using PIL?

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

With above code we know whether a PNG image has alpha channel not not but how to get the alpha value?

I didn't find a 'transparency' key in img.info dictionary as described at PIL's website

I'm using Ubuntu and zlib1g, zlibc packages are already installed.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

单身狗的梦 2024-08-22 19:40:33

要获取 RGBA 图像的 Alpha 层,您需要做的是:

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

alpha = img.split()[-1]

并且有一种设置 Alpha 层的方法:

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]

注意:由于 PIL 中的错误,当 image.mode 为 LA 时需要转换方法。

To get the alpha layer of an RGBA image all you need to do is:

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

or

alpha = img.split()[-1]

And there is a method to set the alpha layer:

img.putalpha(alpha)

The transparency key is only used to define the transparency index in the palette mode (P). If you want to cover the palette mode transparency case as well and cover all cases you could do this

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

Note: The convert method is needed when the image.mode is LA, because of a bug in PIL.

土豪 2024-08-22 19:40:33

您可以通过使用“A”模式将图像转换为字符串,一次性从整个图像中获取 alpha 数据,例如此示例从图像中获取 alpha 数据并将其另存为灰度图像:)

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

You can get the alpha data out of whole image in one go by converting image to string with 'A' mode e.g this example get alpha data out of image and saves it as grey scale image :)

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")
匿名。 2024-08-22 19:40:33

img.info 涉及整个图像 - RGBA 图像中的 alpha 值是每个像素的,所以它当然不会出现在 img.info 中代码>.图像对象的 getpixel 方法,给定坐标作为参数,返回一个元组,其中包含该像素的(在本例中为四个)波段的值 - 该元组的最后一个值将是 A ,阿尔法值。

The img.info is about the image as a whole -- the alpha-value in an RGBA image is per-pixel, so of course it won't be in img.info. The getpixel method of the image object, given a coordinate as argument, returns a tuple with the values of the (four, in this case) bands for that pixel -- the tuple's last value will then be A, the alpha value.

峩卟喜欢 2024-08-22 19:40:33
# 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())
# 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())
嘿嘿嘿 2024-08-22 19:40:33

我尝试了这个:

from PIL import Image
import operator, itertools

def get_alpha_channel(image): 
   try: 
      alpha_index = image.getbands().index('A')
   except ValueError:
      # no alpha channel, so convert to RGBA
      image = image.convert('RGBA')
      alpha_index = image.getbands().index('A')
   alpha_getter = operator.itemgetter(alpha_index)
   return itertools.imap(alpha_getter, image.getdata())

这返回了我期望的结果。然而,我做了一些计算来确定平均值和标准差,结果与 imagemagick 的 fx:mean 函数略有不同。

也许转换改变了一些值?我不确定,但这似乎相对微不足道。

I tried this:

from PIL import Image
import operator, itertools

def get_alpha_channel(image): 
   try: 
      alpha_index = image.getbands().index('A')
   except ValueError:
      # no alpha channel, so convert to RGBA
      image = image.convert('RGBA')
      alpha_index = image.getbands().index('A')
   alpha_getter = operator.itemgetter(alpha_index)
   return itertools.imap(alpha_getter, image.getdata())

This returned the result that I was expecting. However, I did some calculation to determine the mean and standard deviation, and the results came out slightly different from imagemagick's fx:mean function.

Perhaps the conversion changed some of the values? I'm unsure, but it seems relatively trivial.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文