PIL Python,在不丢失原始图像特定颜色的情况下对图像进行遮罩

2024-09-30 10:42:17 发布

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

使用PIL,我想在其他图像上屏蔽一个图像

但是,我想保留原始图像的黑色轮廓

示例:
enter image description here

下面是我尝试过的代码。我有不同的形状(圆形、心形、三角形),都有黑色的轮廓。我想在不丢失原始图像的黑色轮廓的情况下将遮罩覆盖在这些形状上,但我不确定如何做到这一点

whead = whead.resize((200, 240))
data = np.array(whead)  
red, green, blue, alpha = data.T 
white_areas = (red == 222) & (blue == 222) & (green == 222)
data[..., :-1][white_areas.T] = ImageColor.getrgb(headhex)
whead2 = Image.fromarray(data)
img.paste(whead2, (0, 30), whead2)

facemask1 = facemask1.resize((200, 240))
data = np.array(facemask1)  
red, green, blue, alpha = data.T 
white_areas = (red == 23) & (blue == 0) & (green == 255)
data[..., :-1][white_areas.T] = ImageColor.getrgb(facemask1hex)
facemask12 = Image.fromarray(data)
img.paste(facemask12, (0, 30), whead2)


Tags: 图像datanpgreenbluered轮廓形状
1条回答
网友
1楼 · 发布于 2024-09-30 10:42:17

由于您要求PIL解决方案,请尝试PIL.ImageChops.multiply

请确保您的图像颜色仅为白色。而且你需要使你的背景透明——如果你的工具不支持alpha频道,那么有很多基于web的背景移除工具可以帮助你


文件

mask.png
enter image description here

outline.png
enter image description here


代码

from PIL import Image, ImageChops

source = Image.open("outline.png")
source = source.convert("RGBA")

mask = Image.open("mask.png")
mask = mask.convert("RGBA")

output = ImageChops.multiply(source, mask)
output.save("output.png")

您需要匹配图像模式,例如,mask.png处于模式RGB,而outline.png处于模式RGBA并将导致ValueError: images do not match

output.png
enter image description here

相关问题 更多 >

    热门问题