使用 opencv 和 numpy 在另一个图像上叠加图像

overlay image on another image with opencv and numpy

我有两张图片,我需要使用 numpy 和 opencv 使用 numpy 蒙版将前景叠加在背景之上。

import numpy as np
import cv2
import matplotlib.pyplot as plt

background = cv2.imread("background.jpg")
foreground = cv2.imread("foreground.png")
foreground = cv2.cvtColor(foreground ,cv2.COLOR_BGR2GRAY)
background = cv2.cvtColor(background ,cv2.COLOR_BGR2GRAY)

arr = []
for i in range(foreground.shape[1]): #parse forground pixels
    temp_row = []
    for j in range(foreground.shape[0]):
        if((foreground [i][j] == 0)):#if pixel transperant draw background
            temp_row.append(background[i][j])
        else: # draw forground
            temp_row.append(foreground[i][j])
    arr.append(temp_row)

res_im = np.array(arr)
plt.figure()
plt.imshow(res_im, cmap='gray', vmin=0, vmax=255)
plt.show()

我使用了这个解决方案,但被告知我需要使用面具..帮助?

这是 Python/Opencv 中的一种方法。

  • 读取透明前景图像
  • 阅读背景图片
  • 从前景图像中提取 alpha 通道
  • 从前景图像中提取 BGR 通道
  • 使用np.where条件
  • 将它们组合在一起
  • 保存结果

前面:

返回:

import cv2
import numpy as np

# read foreground image
img = cv2.imread('front.png', cv2.IMREAD_UNCHANGED)

# read background image
back = cv2.imread('back.png')

# extract alpha channel from foreground image as mask and make 3 channels
alpha = img[:,:,3]
alpha = cv2.merge([alpha,alpha,alpha])

# extract bgr channels from foreground image
front = img[:,:,0:3]

# blend the two images using the alpha channel as controlling mask
result = np.where(alpha==(0,0,0), back, front)

# save result
cv2.imwrite("front_back.png", result)

# show result
cv2.imshow("RESULT", result)
cv2.waitKey(0)

结果: