如何基于透明python合并两个图像

Luc*_*eto 1 python opencv

我需要加入两个图像,其中基本图像具有透明背景,我已经尝试使用

图片01

在此输入图像描述

图像和照片我需要将她放在空白处的第二个图像中

在此输入图像描述

预期结果和这个

在此输入图像描述

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

dim = (425, 425)

apple = mpimg.imread('image.png')
apple = cv2.resize(apple, dim)

banana = mpimg.imread('image2.png')
banana = cv2.resize(banana, dim)


_ = plt.imshow(apple)
_ = plt.show()

_ = plt.imshow(banana)
_ = plt.show()

list_images = [apple, banana]

def blend(list_images): # Blend images equally.

    equal_fraction = 1.0 / (len(list_images))

    output = np.zeros_like(list_images[0])

    for img in list_images:
        output = output + img * equal_fraction

    output = output.astype(np.uint8)
    _ = plt.imshow(output)
    return output


output = blend(list_images)

_ = plt.imshow(output)
Run Code Online (Sandbox Code Playgroud)

Jer*_*uke 6

您可以轻松地利用 alpha(透明)通道来实现此目的。不幸的是,当我尝试使用 读取帧图像时cv2.IMREAD_UNCHANGED,它没有适当的 Alpha 通道。根据你的结果,圆角之外的区域是白色的。

因此,使用您的帧图像,我创建了 Alpha 通道并使用了以下内容。

# Reading images
tr = cv2.imread('frame.png')
la = cv2.imread('sunset.jpg')

# resizing
dim = (425, 425)
tr = cv2.resize(tr, dim)
la = cv2.resize(la, dim)

# Finding the largest contour (white region) from the first channel in frame
th = cv2.threshold(tr[:,:,0],127,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]
contours, hierarchy = cv2.findContours(th, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
c = max(contours, key = cv2.contourArea)

# Draw the largest contour onto a mask
black = np.zeros((tr.shape[0], tr.shape[1]), np.uint8)
mask = cv2.drawContours(black,[c],0,255, -1)
Run Code Online (Sandbox Code Playgroud)

遮罩图像:我们希望日落图像出现在白色区域

在此输入图像描述

# Create 3-channel mask of float datatype
alpha = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)/255.0

# Perform blending and limit pixel values to 0-255
blended = cv2.convertScaleAbs(tr*(1-alpha) + la*alpha)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述