代码之家  ›  专栏  ›  技术社区  ›  Schütze

Python Opencv混合透明图像

  •  0
  • Schütze  · 技术社区  · 6 年前

    我有一个背景图像,我想覆盖我的透明图像。到目前为止,我已经尝试了很多选择,但没有一个效果好。最后,我找到了以下代码:

    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 回复  |  直到 6 年前
        1
  •  0
  •   Schütze    6 年前

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

    似乎解决了我的问题。