import cv2
import numpy as np
import random
读取两个图像
image1 = cv2.imread('image1.jpg')
image2 = cv2.imread('image2.jpg')
将image1转换为灰度图像
gray_image1 = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)
创建掩码,黑色部分为0,非黑色部分为255
_, mask = cv2.threshold(gray_image1, 1, 255, cv2.THRESH_BINARY)
反转掩码
mask_inv = cv2.bitwise_not(mask)
获取图像1中有效区域的高度和宽度
height1, width1, _ = image1.shape
获取图像2的高度和宽度
height2, width2, _ = image2.shape
生成随机位置
random_y = random.randint(0, height2 - height1)
random_x = random.randint(0, width2 - width1)
创建ROI(Region of Interest),确保不超出图像2的范围
roi = image2[random_y:random_y + height1, random_x:random_x + width1]
创建ROI的反向掩码
roi_bg = cv2.bitwise_and(roi, roi, mask=mask_inv)
获取图像1中有效区域的前景
fg = cv2.bitwise_and(image1, image1, mask=mask)
合并前景和背景
dst = cv2.add(roi_bg, fg)
将合并后的图像放回图像2的相应位置
image2[random_y:random_y + height1, random_x:random_x + width1] = dst
显示结果
cv2.imshow('Merged Image', image2)
cv2.waitKey(0)
cv2.destroyAllWindows()