not*_*ing 5 python mask python-imaging-library
我正在尝试使用黑白图像来掩盖 image1 的某些区域,并使用 Pillow 将其粘贴到 python 中的 image2 上。我尝试过使用“PIL.Image.composite(image1, image2, mask)”,但它不起作用或者我做错了什么。抱歉,我不再有该代码,我剩下的唯一代码是
from PIL import Image, ImageEnhance, ImageOps, ImageDraw, ImageFilter
import os
avatars = []
for img in os.listdir():
if img.endswith(".png") is True:
avatars.append(img)
#open the images
mask = image.open("./masks/roundmask.png")
avatar1 = Image.open(avatars[0]).resize((128,128))
avatar2 = Image.open(avatars[1]).resize((128,128))
"""
mask the image avatar1 using the mask image and paste it on top of avatar2
"""
end = Image.open("./template/image.png").paste(avatar1, (190,93)).paste(avatar2, (420,38))
end.save("./finished/end.png")
Run Code Online (Sandbox Code Playgroud)
我只能猜测您要么尝试使用不兼容的图像尺寸(它们的尺寸都略有不同),要么您的模式错误。无论如何,从这两个输入图像和这个掩码开始:
这就是你需要的:
#!/usr/bin/env python3
from PIL import Image
# Load images, discard pointless alpha channel, set appropriate modes and make common size
av1 = Image.open('avatar1.png').convert('RGB').resize((500,500))
av2 = Image.open('avatar2.png').convert('RGB').resize((500,500))
mask = Image.open('mask.png').convert('L').resize((500,500))
# Composite and save
Image.composite(av1,av2,mask).save('result.png')
Run Code Online (Sandbox Code Playgroud)
顺便说一句,您可以使用 ImageMagick 在终端的命令行上执行相同的操作:
magick avatar1.png avatar2.png mask.png -composite result.png
Run Code Online (Sandbox Code Playgroud)
关键词:Python、图像处理、PIL、Pillow、复合、掩模、遮蔽、混合。