PIL中背景与透明图像的融合

2024-04-26 13:27:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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层什么不是很好的解决方案。


Tags: 图像image网格mappng颜色地方width
2条回答

您要做的是将网格组合到背景上,为此需要使用^{}^{}。下面是一个使用后者将带有随机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)

从左到右:
[背景][遮罩] [前景] [结果]

backgroundmaskforegroundcomposite

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

我很难让上面的例子起作用。相反,这对我有效:

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

相关问题 更多 >