下面的代码将使用覆盖图像的alpha通道将其正确地混合到背景图像中,使用x和y设置覆盖图像的左上角。import cv2

import numpy as np

def overlay_transparent(background, overlay, x, y):

background_width = background.shape[1]

background_height = background.shape[0]

if x >= background_width or y >= background_height:

return background

h, w = overlay.shape[0], overlay.shape[1]

if x + w > background_width:

w = background_width - x

overlay = overlay[:, :w]

if y + h > background_height:

h = background_height - y

overlay = overlay[:h]

if overlay.shape[2] < 4:

overlay = np.concatenate(

[

overlay,

np.ones((overlay.shape[0], overlay.shape[1], 1), dtype = overlay.dtype) * 255

],

axis = 2,

)

overlay_image = overlay[..., :3]

mask = overlay[..., 3:] / 255.0

background[y:y+h, x:x+w] = (1.0 - mask) * background[y:y+h, x:x+w] + mask * overlay_image

return background

这段代码将改变背景,因此如果您希望保留原始背景图像,请创建一个副本。

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐