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

时间:2019-03-06 10:41:15

标签: python image image-processing python-imaging-library alpha

枕头包装具有称为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值,但没有区别。

可能出了什么问题?

3 个答案:

答案 0 :(得分:2)

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

看到图像
im_owl.show()

但是当我保存它

im_owl.save()

我能够看到图像已更改。

答案 1 :(得分:2)

尝试使用

im_owl.save("alphadOwl.png")

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

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

答案 2 :(得分: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).

要解决此问题,我们可以修补枕头代码以将PNG格式用作默认值。首先,我们需要找到Pillow软件包的根目录:

import PIL
print(PIL.__path__)

在我的系统上,输出为:

  

[’D:\ Anaconda \ lib \ site-packages \ PIL']

转到此目录并打开文件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通道的图像。

参考

相关问题