如何使用PIL获取PNG图像的alpha值?
如何使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
要获取 RGBA 图像的 Alpha 层,您需要做的是:
或
并且有一种设置 Alpha 层的方法:
透明度键仅用于定义调色板模式(P)中的透明度索引。如果您还想覆盖调色板模式透明度情况并覆盖所有情况,您可以这样做
注意:由于 PIL 中的错误,当 image.mode 为 LA 时需要转换方法。
To get the alpha layer of an RGBA image all you need to do is:
or
And there is a method to set the alpha layer:
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
Note: The convert method is needed when the image.mode is LA, because of a bug in PIL.
您可以通过使用“A”模式将图像转换为字符串,一次性从整个图像中获取 alpha 数据,例如此示例从图像中获取 alpha 数据并将其另存为灰度图像:)
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 :)
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 inimg.info
. Thegetpixel
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.我尝试了这个:
这返回了我期望的结果。然而,我做了一些计算来确定平均值和标准差,结果与 imagemagick 的
fx:mean
函数略有不同。也许转换改变了一些值?我不确定,但这似乎相对微不足道。
I tried this:
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.