我有兩個影像,我需要使用 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()
我使用了這個解決方案,但被告知我需要使用口罩.. 幫助?
uj5u.com熱心網友回復:
這是在 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)
結果:

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/325918.html
