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

3

Image.putalpha() 是 pillow 包中的一个方法,用于添加或更改图像的 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值,但没有看到任何区别。
可能出了什么问题?

你不应该先创建带有 alpha 通道的图像吗?cv2.COLOR_RGB2RGBA - DirtyBit
您可以阅读有关 Image.putalpha() 的文档,它不需要事先带有 alpha 通道的图像。这个问题与 OpenCV 无关。 - jdhao
3个回答

2

Try using

im_owl.save("alphadOwl.png")

然后查看保存的图像。似乎 alpha 通道未应用于 bmp 或 jpg 文件。使用 im.show() 显示的是 bmp 文件。(记录一下,我正在使用 Mac,不知道其他设备上是否使用了不同的应用程序)。最初的回答。

谢谢,看起来图像显示为bmp文件,不使用alpha通道。 - jdhao
值得一提的是,当您将其读回到PIL图像中时会发生什么- alpha通道是否保留? - Pam

2

尝试保存图片并查看。我也无法直接查看来自的图像

Original Answer翻译成"最初的回答"

im_owl.show()

最初的回答是:但是当我保存它时。
im_owl.save()

我可以看到图片已经改变。原始答案翻译成"最初的回答"。

1
正如@sanyam和@Pam所指出的,我们可以保存转换后的图像并且它会正确显示。这是因为在Windows上,在使用系统默认的图像查看器显示之前,图像会被保存为临时BMP文件,根据PIL文档的说明:
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:\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通道的图像。

参考资料


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接