📜  使用Python OpenCV 进行透明覆盖

📅  最后修改于: 2022-05-13 01:55:51.343000             🧑  作者: Mango

使用Python OpenCV 进行透明覆盖

在本文中,我们将了解如何使用Python OpenCV 进行透明叠加。

为了让这个程序正常工作,首先我们需要两个输入:背景图像、叠加图像。然后我们将创建一个与背景图像具有相同维度的 NumPy 数组,所有值都为 0。然后我们将使用该数组和叠加层创建一个蒙版。

现在我们程序的主要部分将使用cv2.addWeighted()方法完成覆盖。

cv2.addWeighted() :这个方法基本上是计算两个输入数组的平均加权和来返回一个输出数组。

图片可以从这里下载:Geekslogo,背景

下面是实现:

Python3
import cv2
import numpy as np
 
# Loading our images
# Background/Input image
background = cv2.imread('Assets/img1.jpg') 
 
# Overlay image
overlay_image = cv2.imread('Assets/overlay3.png') 
 
# Resize the overlay image to match the bg image dimensions
overlay_image = cv2.resize(overlay_image, (1000, 1000))
h, w = overlay_image.shape[:2]
 
# Create a new np array
shapes = np.zeros_like(background, np.uint8)
 
# Put the overlay at the bottom-right corner
shapes[background.shape[0]-h:, background.shape[1]-w:] = overlay_image
 
# Change this into bool to use it as mask
mask = shapes.astype(bool)
 
# We'll create a loop to change the alpha
# value i.e transparency of the overlay
for alpha in np.arange(0, 1.1, 0.1)[::-1]:
   
    # Create a copy of the image to work with
    bg_img = background.copy()
    # Create the overlay
    bg_img[mask] = cv2.addWeighted(bg_img, 1 - alpha, shapes,
                                   alpha, 0)[mask]
 
    # print the alpha value on the image
    cv2.putText(bg_img, f'Alpha: {round(alpha,1)}', (50, 200),
                cv2.FONT_HERSHEY_PLAIN, 8, (200, 200, 200), 7)
 
    # resize the image before displaying
    bg_img = cv2.resize(bg_img, (630, 630))
    cv2.imshow('Final Overlay', bg_img)
    cv2.waitKey(0)


输出: