这是一个相当大的过程,主要是因为在不同大小的图像上添加图像需要很多步骤。我建议您检查下面代码中的所有中间步骤,以了解会发生什么。
我使用 HSV-colorspace 将签名与背景分开,如果签名或背景有其他颜色,这很容易适应。
我还没有找到@BahramdunAdil 使用的copyTo()-方法的python 绑定。您可以改用numpy.copyto() 功能。为此,我会将您推荐给this answer。
我使用了一种不同的技术:将图像叠加到另一个图像之上,首先创建一个与签名大小相同的子图像。可以将签名添加到子图像中,然后将其放回主图像中。
或者,您可以采用阈值签名并使用@renedv1 的方法来保存 alpha 图像。为此使用sign_masked 图像。由于 HSV 范围,您可以创建更清晰的结果。 (注意:考虑到 sign_masked 的背景是黑色的)
结果:
代码:
import numpy as np
import cv2
# load image
sign = cv2.imread("sign.jpg")
bg_img = cv2.imread("green_area.jpg")
# Convert BGR to HSV
hsv = cv2.cvtColor(sign, cv2.COLOR_BGR2HSV)
# define range of HSV-color of the signature
lower_val = np.array([0,0,0])
upper_val = np.array([179,255,150])
# Threshold the HSV image to get a mask that holds the signature area
mask = cv2.inRange(hsv, lower_val, upper_val)
# create an opposite: a mask that holds the background area
mask_inv= cv2.bitwise_not(mask)
# create an image of the signature with background excluded
sign_masked = cv2.bitwise_and(sign,sign,mask=mask)
# get the dimensions of the signature
height, width = sign.shape[:2]
# create a subimage of the area where the signature needs to go
placeToPutSign = bg_img[0:height,0:width]
# exclude signature area
placeToPutSign_masked = cv2.bitwise_and(placeToPutSign, placeToPutSign, mask=mask_inv)
# add signature to subimage
placeToPutSign_joined = cv2.add(placeToPutSign_masked, sign_masked)
# put subimage over main image
bg_img[0:height,0:width] = placeToPutSign_joined
# display image
cv2.imshow("result", bg_img)
cv2.waitKey(0)
cv2.destroyAllWindows()