【问题标题】:Image pasted with PIL produces artifacts使用 PIL 粘贴的图像会产生伪影
【发布时间】:2016-04-07 06:22:38
【问题描述】:

我有一堆图片需要在上面放置文字叠加层。我使用 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 选项?

【问题讨论】:

  • 你试过alpha_composite吗?见this answer
  • 该死的,谢谢。我来自这个答案,但没有进一步滚动......

标签: python png transparency python-imaging-library


【解决方案1】:

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

结果:

【讨论】:

  • 它确实看起来像一个调色板问题 - GIMP 无法处理部分透明的索引 PNG 图像 - 所以,我会说 OP 的背景图像是 indexed.png 并且 PIL 正在强制覆盖索引使用.paste 粘贴时以错误的方式。我想说简单地在背景上应用 .convert 步骤对 OP 有用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-19
相关资源
最近更新 更多