【问题标题】:Merging background with transparent image in PIL在 PIL 中将背景与透明图像合并
【发布时间】:2012-04-14 14:10:41
【问题描述】:

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


【解决方案1】:

您要做的是将网格合成到背景上,为此您需要使用Image.blend 或Image.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 在已删除答案中指出的那样。)

【讨论】:

  • 左边有一个看不见的白色
【解决方案2】:

我无法让上述示例正常工作。相反,这对我有用:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-08
    • 1970-01-01
    • 2011-11-10
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多