我想将一个填充纯色的半透明矩形添加到已加载的半透明 PNG 中。这是我正在使用的输入图像示例:
该图像加载了标准cv2.IMREAD_UNCHANGED
标志,以便完美保留 alpha 通道。该输入图像存储在image
多变的。
这是我到目前为止的代码:
# get image dimensions
imgHeight, imgWidth = image.shape[:2]
# create empty overlay layer with 4 channels
overlay = np.zeros((imgHeight, imgWidth, 4), dtype = "uint8")
# draw semi-transparent red rectangle
overlay[200:300, 0:imgWidth] = (0, 0, 255, 200)
# extract alpha channel from overlay
alpha = cv2.split(overlay)[3]
# compute mask
mask = (np.multiply(alpha, 1.0 / 255))[:, :, np.newaxis]
# blend input image and overlay
output = cv2.convertScaleAbs(overlay * mask + image * (1 - mask))
这是我得到的结果:
乍一看看起来可以接受。我们的输入图像中间有一个半透明矩形。然而,经过仔细检查,我们可以在混合 alpha 通道时观察到奇怪的行为(用箭头标记):
似乎 Alpha 根本没有混合,这导致原始图像像素只是完全不透明或完全透明。
也许我将透明 PNG 与半透明形状混合的方法远非理想。作为旁注,我确实尝试过cv2.addWeighted
方法,但结果更糟。
我希望解决方案仅限于 OpenCV 和/或 Numpy。任何帮助将不胜感激。