[英]How to overlay images with transparent background?
事实上,我找到了适合我的解决方案。 也许这不是一个最佳解决方案,但至少它有效。
主要思想是我使用 PIL 库和方法paste
将 2 张图片合并(粘贴)为 1 个结果,这样我就有了背景和前景。
就我而言,我有图片 1 - 前景和图片 2 - 背景。
我的代码:
# This function fit picture 2(background) for picture 1 . It's pare
def transform (template):
img = Image.open(template)
img_w, img_h = img.size
image = img.resize((img_w+coef_w,img_h+coef_h),Image.ANTIALIAS)
# change coef_w and coef_h to resize to fit template
image.save('updated_picture.png',"PNG")
# This function merge,compose, concat) pictures
def compose (image, template):
img = Image.open(image)
img_w, img_h = img.size
print(img.size)
background = Image.open(template)
print(background.size)
# resize the image
size = background.size
background = background.resize(size, Image.ANTIALIAS)
bg_w, bg_h = background.size
offset = ((bg_w - img_w) // 2, (bg_h - img_h) // 2)
background.paste(img, offset, mask=img)
background.save(f'{image}_final.png', "PNG")
它是如何工作的,我转换模板(耳朵),以便它们位于图片中心,下一个脚本按中心偏移前景,这样我就可以获得下一个结果。
需要转换以使模板变小或变大。 结果将取决于它的模板。 我的意思是在我的情况下耳朵的规模。 在下一张图片中,您可以看到我的意思
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.