首页 > 解决方案 > 将透明图像合并到另一个背景

问题描述

我有 2 张图片如下,均为 RGBA 格式 背景

目的

我想将对象覆盖到背景中的固定区域。但是,我的代码产生了一个奇怪的结果: 在此处输入图像描述

有人可以看看我的代码,看看我错在哪里。提前致谢

import numpy as np
import matplotlib.pyplot as plt
import cv2
import glob
from PIL import Image
bg = np.array(Image.open('background.png'))
obj = np.array(Image.open('object.png'))

#RESIZE BACKGROUND
scale_percent = 50 # percent of original size
width = int(bg.shape[1] * scale_percent / 100)
height = int(bg.shape[0] * scale_percent / 100)
dim = (width, height)
bg = resized = cv2.resize(bg, dim, interpolation = cv2.INTER_AREA)

#RESIZE OBJECT
scale_percent = 80 # percent of original size
width = int(obj.shape[1] * scale_percent / 100)
height = int(obj.shape[0] * scale_percent / 100)
dim = (width, height)
# resize image
obj = resized = cv2.resize(obj, dim, interpolation=cv2.INTER_AREA)


#create ROI
rows, cols, channels = obj.shape
bg_rows, bg_cols, bg_channels = bg.shape
roi = bg[bg_rows-rows:bg_rows:, bg_cols-cols:bg_cols:]

img2gray = cv2.cvtColor(obj, cv2.COLOR_BGR2GRAY)
ret, mask = cv2.threshold(img2gray, 220, 255, cv2.THRESH_BINARY_INV)

mask_inv = cv2.bitwise_not(mask)

img1_bg = cv2.bitwise_and(roi, roi, mask=mask_inv)

img2_fg = cv2.bitwise_and(obj, obj, mask=mask)

dst = cv2.add(img1_bg, img2_fg)
bg[bg_rows-rows:bg_rows:, bg_cols-cols:bg_cols:] = dst
Image.fromarray(bg)

标签: pythonpython-3.xopencv-python

解决方案


您应该使用枕头库中的 ImageDraw() 函数。它将通过提供与第二张图像相同的模式来解决您的问题。


推荐阅读