python - 在 PIL 中将背景与透明图像合并

标签 python python-imaging-library

我有一个 png 图像作为背景,我想向这个背景添加一个透明网格,但这并没有像预期的那样工作。在我应用透明网格的地方,背景图像被转换为​​透明。

我在做:

from PIL import Image, ImageDraw

map_background = Image.open(MAP_BACKGROUND_FILE).convert('RGBA')
map_mesh = Image.new('RGBA', (width, height), (0, 0, 0, 0))
draw = ImageDraw.Draw(map_mesh)

# Create mesh using: draw.line([...], fill=(255, 255, 255, 50), width=1)
...

map_background.paste(map_mesh, (0, 0), map_mesh)

但结果是:

enter image description here

仔细看可以看到一个棋盘图案(图形程序中用作无背景)。透明线使背景层在两层相交的地方也变得透明。但我只想在背景上添加透明线。

我可以解决它:

map_background.paste((255,255,255), (0, 0), map_mesh)

但是由于我对不同的线条使用不同的颜色,所以我必须为每种颜色制作这个过程。如果我有 100 种颜色,那么我需要 100 层,这不是很好的解决方案。

最佳答案

您要做的是将网格合成到背景上,为此您需要使用 Image.blendImage.composite .这是一个使用后者将具有随机 alpha 值的红线合成到白色背景上的示例:

import Image, ImageDraw, random
background = Image.new('RGB', (100, 100), (255, 255, 255))
foreground = Image.new('RGB', (100, 100), (255, 0, 0))
mask = Image.new('L', (100, 100), 0)
draw = ImageDraw.Draw(mask)
for i in range(5, 100, 10):
    draw.line((i, 0, i, 100), fill=random.randrange(256))
    draw.line((0, i, 100, i), fill=random.randrange(256))
result = Image.composite(background, foreground, mask)

从左到右:
[背景] [面具] [前景] [结果]

background mask foreground composite

(如果您愿意将结果写回到背景图像,那么您可以使用 Image.paste 的屏蔽版本之一,正如 Paulo Scardine 在已删除的答案中指出的那样。)

关于python - 在 PIL 中将背景与透明图像合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9950634/

相关文章:

python - 将 RGB 颜色转换为调色板中最接近的颜色(网络安全颜色)?

python - 如何使用paste()重叠两个或多个图像?

python - 尝试裁剪图像并使用 pydicom 保存 dicom,

python - Django Rest Framework使用url加载指定模型

javascript - Pyqt5 从 QtWebChannel 移动窗口

python - 我应该使用 Python casefold 吗?

python - 谷歌应用引擎: "could not initialize images API" even though PIL is installed

python - matplotlib 中的逐步线图

python - Django DRF - 通过权限限制对 ListView 的访问

python - 使用 PIL 从 macbook isight 捕获帧