首页 > 解决方案 > 在 Python 中使用 PIL 或 OpenCV 将图像粘贴到具有改变不透明度的两个给定坐标处的另一个图像

问题描述

我有两个带有给定点的图像,每个图像一个点,需要对齐,以便结果图像是两个图像的总和,而图像 2 以 40% 的不透明度粘贴在图像 1 上。我已经考虑了这个问题,但我们的案例并不完全匹配,因为图像坐标是由用户提供的,并且图像的尺寸范围很广。

图 1:图 1

图片2:图 2

最终结果(期望的输出):最终图像

为此,我尝试img.paste()了 PIL 的功能并替换 cv2 中 numpy 图像数组中的值,两者都给出了远非预期的结果。

标签: python-3.xopencvpython-imaging-librarycv2

解决方案


我用ImageMagick制作了两个输入图像,如下所示:

magick -size 300x400 xc:"rgb(1,204,255)" -fill red -draw "point 280,250" 1.png
magick -size 250x80  xc:"rgb(150,203,0)" -fill red -draw "point 12,25"   2.png

在此处输入图像描述 在此处输入图像描述

然后运行以下代码:

#!/usr/bin/env python3
"""
Paste one image on top of another such that given points in each are coincident.
"""

from PIL import Image

# Open images and ensure RGB
im1 = Image.open('1.png').convert('RGB')
im2 = Image.open('2.png').convert('RGB')

# x,y coordinates of point in each image
p1x, p1y = 280, 250
p2x, p2y = 12, 25

# Work out how many pixels of space we need left, right, above, below common point in new image
pL = max(p1x, p2x)
pR = max(im1.width-p1x,  im2.width-p2x)
pT = max(p1y, p2y)
pB = max(im1.height-p1y, im2.height-p2y)

# Create background in solid white
bg = Image.new('RGB', (pL+pR, pT+pB),'white')
bg.save('DEBUG-bg.png')

# Paste im1 onto background
bg.paste(im1, (pL-p1x, pT-p1y))
bg.save('DEBUG-bg+im1.png')

# Make 40% opacity mask for im2
alpha = Image.new('L', (im2.width,im2.height), int(40*255/100))
alpha.save('DEBUG-alpha.png')

# Paste im2 over background with alpha
bg.paste(im2, (pL-p2x, pT-p2y), alpha)
bg.save('result.png')

结果是这样的:

在此处输入图像描述

保存图片名称开头"DEBUG-xxx.png"的行只是为了方便调试,可以去掉。我可以轻松地查看它们以了解代码发生了什么,并且可以通过删除"DEBUG*png".


推荐阅读