Python Opencv混合透明图像

时间:2018-08-08 05:56:01

标签: python opencv-python

我有一个背景图片,我想在上面叠加透明图片。到目前为止,我已经尝试了很多选择,但都没有一个很好的选择。最后,我找到了以下代码:

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

1 个答案:

答案 0 :(得分:0)

好的,我已经通过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)

似乎解决了我的问题。