OpenCV 在使用 addWeighted() 时抛出错误参数错误

OpenCV throws a bad argument error when using addWeighted()

我正在尝试使用 cv2.addWeighted(...) 在图像顶部添加叠加层,但它会引发以下错误:

dst = cv2.addWeighted(logo, alpha, overlay, 1-alpha, 0)
cv2.error: OpenCV(4.4.0) /tmp/pip-req-build-99ib2vsi/opencv/modules/core/src/arithm.cpp:691: error: (-5:Bad argument) When the input arrays in add/subtract/multiply/divide functions have different types, the output array type must be explicitly specified in function 'arithm_op'

这个错误对我来说没有意义,因为我检查了文档并且我的论点是合适的。这是我的代码。

def overlay(path):
    logo = cv2.imread(path, cv2.IMREAD_UNCHANGED)
    alpha = logo[:, :, 3]

    overlay = np.zeros(logo.shape, dtype=np.uint8)
    overlay[:, :, 2] = alpha
    overlay[:, :, 3] = alpha

    alpha = 0.5

    dst = cv2.addWeighted(logo, alpha, overlay, 1-alpha, 0)

    pil_image = Image.fromarray(dst).convert('RGBA')

    return pil_image

更新

叠加层现在可以使用了,但存在一些问题。我对我的代码进行了以下更改:

dst = cv2.addWeighted(logo, alpha, overlay, 1 - alpha, 0, dtype=cv2.CV_32F).astype(np.uint8)

这是我更改叠加层颜色时发生的情况。

新的完整代码:

def overlay(path):
    logo = cv2.imread(path, cv2.IMREAD_UNCHANGED)
    alpha = logo[:, :, 3]

    overlay = np.zeros(logo.shape, dtype=np.uint8)
    overlay[:, :, 2] = alpha
    r = 0
    g = 255
    b = 0
    overlay[:, :, :3] = r, g, b
    # overlay[:, :, 3] = alpha

    alpha = 0.5

    dst = cv2.addWeighted(logo, alpha, overlay, 1 - alpha, 0, dtype=cv2.CV_32F).astype(np.uint8)

    pil_image = Image.fromarray(dst).convert('RGBA')

徽标和覆盖对象具有不同的数据类型,导致解析错误。要解决此问题,您必须在 addWeighted 命令中指定输出的数据类型。这是一个 32 类型输出的示例:

dst = cv2.addWeighted(logo, alpha, overlay, 1-alpha, 0, dtype=cv2.CV_32F).astype(np.uint8)

来源/其他参考资料:
https://github.com/Prasad9/ImageAugmentationTypes/issues/2

dst = cv2.addWeighted(logo, alpha, overlay, 1-alpha, 0, dtype=cv2.CV_32F).astype(np.uint8)

设置要叠加的颜色:

r = 10
g = 190
b = 100
a = 255
overlay[:, :] = r,g,b,a