[英]How to overlay images with transparent background?
Let say that I have a 2 pictures that are transparent.假设我有两张透明的图片。 How can I overlay picture 1 to picture 2 so to get a result picture.
如何将图片 1 叠加到图片 2 以获得结果图片。 Picture 1 is also smaller that picture 2. I assume that it can be done with opencv or PIL (GIMP is not allowed)
图1也比图2小。我假设它可以用opencv或PIL完成(不允许GIMP)
And picture number 2 :和图片2:
[ [
That's the result that I want to get:这就是我想要得到的结果:
My approach : I thought that I can be done with opencv function cv.addWeighted(src1, alpha, src2, beta, gamma[, dst[, dtype]])
what I also tried to perform.我的方法:我认为我可以使用我也尝试执行的 opencv 函数
cv.addWeighted(src1, alpha, src2, beta, gamma[, dst[, dtype]])
来完成。 But as the matter in fact major problems are next points: pictures are transparent and the task is to leave pictures with higher resolution.但事实上,主要问题是下一点:图片是透明的,任务是让图片具有更高的分辨率。 Rely on your answers.
依靠你的答案。
As a matter in fact, I find out the solution that suits for me.事实上,我找到了适合我的解决方案。 Perhaps It's not an optimal solution but at least It works.
也许这不是一个最佳解决方案,但至少它有效。
The main idea is that I merge(paste) 2 pictures into 1 result using PIL library and the method paste
, so that I have background and foreground.主要思想是我使用 PIL 库和方法
paste
将 2 张图片合并(粘贴)为 1 个结果,这样我就有了背景和前景。
In my case I have Picture 1 - foreground and Picture 2 - background.就我而言,我有图片 1 - 前景和图片 2 - 背景。
My code :我的代码:
# 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")
How it's work, I transform template(ears) so they would lay on the picture at center and the next one script offset foreground by center so I can get next result.它是如何工作的,我转换模板(耳朵),以便它们位于图片中心,下一个脚本按中心偏移前景,这样我就可以获得下一个结果。
Transform is needed to make template smaller or bigger.需要转换以使模板变小或变大。 The results would depend on of it's template.
结果将取决于它的模板。 I mean the scale of ears in my case.
我的意思是在我的情况下耳朵的规模。 At the next picture you can see what I mean
在下一张图片中,您可以看到我的意思
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.