【问题标题】:overlay image on another image with opencv and numpy使用 opencv 和 numpy 在另一个图像上叠加图像
【发布时间】:2021-10-18 18:14:01
【问题描述】:

我有两个图像,我需要使用 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 numpy opencv


    【解决方案1】:

    这是在 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)
    

    结果:

    【讨论】:

      猜你喜欢
      • 2011-07-05
      • 2018-10-11
      • 2021-12-19
      • 2012-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-03
      相关资源
      最近更新 更多