添加Alpha通道时图像不会改变

问题描述 投票:3回答:3

枕头包有一个名为Image.putalpha()的方法,用于添加或更改图像的alpha通道。

我尝试使用这种方法,发现我无法改变图像的背景颜色。原始图像是

enter image description here

这是我添加alpha的代码

from PIL import Image

im_owl = Image.open("owl.jpg")

alpha = Image.new("L", im_owl.size, 50)
im_owl.putalpha(alpha)

im_owl.show()

生成的图像与原始图像没有什么不同。我尝试过不同的alpha值,看不出差异。

可能出错了什么?

python image image-processing python-imaging-library alpha
3个回答
2
投票

尝试保存图像并查看它。我也无法直接看到图像

im_owl.show()

但是当我救了它

im_owl.save()

我能够看到图像发生了变化。


2
投票

尝试使用

im_owl.save("alphadOwl.png")

然后查看保存的图像。似乎alpha通道不适用于bmp或jpg文件。这是一个用im.show()显示的bmp文件

(为了记录,我在Mac上,我不知道im.show()是否在其他设备上使用不同的应用程序)。


1
投票

正如@sanyam和@Pam指出的那样,我们可以保存转换后的图像并正确显示。这是因为在Windows上,根据PIL documentation,图像在使用系统默认图像查看器显示之前保存为临时BMP文件:

Image.show(title=None, command=None)

    Displays this image. This method is mainly intended for debugging purposes.

    On Unix platforms, this method saves the image to a temporary PPM file, and calls
    either the xv utility or the display utility, depending on which one can be found.

    On macOS, this method saves the image to a temporary BMP file, and opens it with
    the native Preview application.

    On Windows, it saves the image to a temporary BMP file, and uses the standard BMP
    display utility to show it (usually Paint).

要解决此问题,我们可以修补Pillow代码以使用PNG格式作为默认值。首先,我们需要找到Pillow包的根:

import PIL
print(PIL.__path__)

在我的系统上,输出是:

[“d:\蟒蛇\飞跃\站点包\丸“]

转到此目录并打开文件ImageShow.py。我在行register(WindowsViewer)之后添加以下代码:

    class WindowsPNGViewer(Viewer):
        format = "PNG"

        def get_command(self, file, **options):
            return ('start "Pillow" /WAIT "%s" '
                    '&& ping -n 2 127.0.0.1 >NUL '
                    '&& del /f "%s"' % (file, file))

    register(WindowsPNGViewer, -1)

之后,我可以正确显示alpha通道的图像。

参考

© www.soinside.com 2019 - 2024. All rights reserved.