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

问题描述 投票:6回答:2

我有一个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)

但结果是:

如果仔细观察(在图形程序中用作无背景),您可以看到棋盘图案。透明线条使得背景图层在两个层都满足的位置也是透明的。但我只想在背景上添加透明线。

我可以解决它:

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

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

python python-imaging-library
2个回答
11
投票

你要做的是将网格合成到背景上,为此你需要使用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)

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

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


0
投票

我无法让上面的例子运行良好。相反,这对我有用:

import numpy as np
import Image
import ImageDraw

def add_craters(image, craterization=20.0, width=256, height=256):

    foreground = Image.new('RGBA', (width, height), (0, 0, 0, 0))
    draw = ImageDraw.Draw(foreground)

    for c in range(0, craterization):
        x = np.random.randint(10, width-10)
        y = np.random.randint(10, height-10)
        radius = np.random.randint(2, 10)
        dark_color = (0, 0, 0, 128)
        draw.ellipse((x-radius, y-radius, x+radius, y+radius), fill=dark_color)

    image_new = Image.composite(foreground, image, foreground)
    return image_new
© www.soinside.com 2019 - 2024. All rights reserved.