使用 PIL 粘贴的图像会产生伪影

use*_*412 3 python png transparency python-imaging-library

我有一堆图像,需要在其上放置文本叠加层。我使用 GIMP(具有透明度的 PNG)创建了叠加层,并尝试将其粘贴到其他图像的顶部:

from PIL import Image

background = Image.open("hahn_echo_1.png")
foreground = Image.open("overlay_step_3.png")

background.paste(foreground, (0, 0), foreground)
background.save("abc.png")
Run Code Online (Sandbox Code Playgroud)

然而,我得到的不是在顶部显示漂亮的黑色文本,而是:

破碎的形象

overlay.png 在 Gimp 中看起来像这样:

覆盖 Gimp

所以我希望看到一些漂亮的黑色文本,而不是这种五颜六色的混乱。

有任何想法吗?我缺少一些 PIL 选项吗?

use*_*412 5

如上所述vrs,使用alpha_composite这样的答案:How to merge a transparent png image with another image using PIL

就可以了。确保图像处于正确的模式 (RGBA)。

完整的解决方案:

from PIL import Image

background = Image.open("hahn_echo_1.png").convert("RGBA")
foreground = Image.open("overlay_step_3.png").convert("RGBA")
print(background.mode)
print(foreground.mode)

Image.alpha_composite(background, foreground).save("abc.png")
Run Code Online (Sandbox Code Playgroud)

结果:

结果

  • 它确实看起来像一个调色板问题 - GIMP 无法处理具有部分透明度的索引 PNG 图像 - 所以,我想说 OP 的背景图像是一个 indexed.png 并且 PIL 在粘贴时强制覆盖以错误的方式索引.粘贴`。我想说,简单地在背景上应用“.convert”步骤就可以为OP工作。 (2认同)