Python Opencv 混合透明图像

Python Opencv Blend Transparent Image

我有一张背景图片,我想在上面叠加我的透明图片。到目前为止,我已经尝试了很多选项并且 none 效果很好。最后,我找到了以下代码:

processedImagePIL = Image.fromarray(processedImage) #since we use opencv
shuttleImagePIL = Image.fromarray(shuttleIcon) #since we use opencv
blended = Image.blend(processedImagePIL, shuttleImagePIL, alpha=0.5)

但即便如此也给我一个尺寸错误

ValueError: images do not match

我不明白为什么图像大小应该相等,因为我要叠加的是一个小图标,期望它和我的背景一样大有点愚蠢。是否有一种在 Python 中有效的简单算法?任何包或实现都可以。

我的图标:https://ibb.co/fecVOz

我的背景:https://ibb.co/chweGK

好的,我已经通过 OpenCV 运行 搞定了:

# function to overlay a transparent image on background.
def transparentOverlay(backgroundImage, overlayImage, pos=(0, 0), scale=1):
    overlayImage = cv2.resize(overlayImage, (0, 0), fx=scale, fy=scale)
    h, w, _ = overlayImage.shape  # Size of foreground
    rows, cols, _ = backgroundImage.shape  # Size of background Image
    y, x = pos[0], pos[1]  # Position of foreground/overlayImage image

    # loop over all pixels and apply the blending equation
    for i in range(h):
        for j in range(w):
            if x + i >= rows or y + j >= cols:
                continue
            alpha = float(overlayImage[i][j][3] / 255.0)  # read the alpha channel
            backgroundImage[x + i][y + j] = alpha * overlayImage[i][j][:3] + (1 - alpha) * backgroundImage[x + i][y + j]
    return backgroundImage

然后使用如下:

# Overlay transparent images at desired postion(x,y) and Scale.
result = transparentOverlay(processedImage, shuttleIcon, tuple(trackedCenterPoint), 0.7)

似乎解决了我的问题。