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

Image pasted with PIL produces artifacts

我有一堆图片需要在其上叠加文字。我使用 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")

但是,我没有在顶部显示漂亮的黑色文本,而是这样:

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

所以我希望有一些漂亮的黑色文字,而不是这些五颜六色的乱七八糟的文字。

有什么想法吗?我缺少一些 PIL 选项?

正如上面 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")

结果: