python - 将透明图像合并到另一个背景
问题描述
我想将对象覆盖到背景中的固定区域。但是,我的代码产生了一个奇怪的结果:
有人可以看看我的代码,看看我错在哪里。提前致谢
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)
解决方案
您应该使用枕头库中的 ImageDraw() 函数。它将通过提供与第二张图像相同的模式来解决您的问题。
推荐阅读
- php - 如何处理下拉列表中不再存在的现有下拉值?
- java - 无法将 Json 字符串转换为 Java 对象
- ios - 在 Xcode 11 和 iOS 13 上切换 UISwith 时应用卡住了
- mysql - SQL:为什么订票需要交易?
- html - Excel VBA to activate selectitem in web and go web for data
- postgresql - 比较表中的行对
- r - Several find and replace from text file
- pdf-generation - Angular @Input ngIf 和 PDF 的生成
- javascript - 为什么我的猫鼬 findOne 查询返回多个结果
- swift - Swift 5 中从日期时间字符串到当前时间的天数时差