下面的例子是将img2作为水印打到bg上,注意:img2是一个背景透明的png
import cv2 from PIL import Image def merge_image(bg, img2, top_left): # 打开背景 bg = Image.fromarray(bg.astype('uint8')).convert('RGB') # 创建底图 target = Image.new('RGBA', (bg.size[0], bg.size[1]), (0, 0, 0, 0)) # 打开水印 img2_scale = img2.copy() # img2_scale = cv2.resize(img2_scale, (w2, h2)) img2_scale = Image.fromarray(img2_scale.astype('uint8')).convert('RGBA') # 分离透明通道 r, g, b, a = img2_scale.split() # 将背景贴到底图 bg.convert("RGBA") target.paste(bg, (0, 0)) # 将水印贴到底图 img2_scale.convert("RGBA") startX = top_left[0] startY = top_left[1] target.paste(img2_scale, (startX, startY), mask=a) target = np.array(target) return target bg = cv2.imread(r'bg.jpg') img2 = cv2.imread(r'logo.png', cv2.IMREAD_UNCHANGED) top_left = (10, 10) res = merge_image(bg, img2, top_left) cv2.imshow('1', res) cv2.waitKey(100000)