Search code examples
pythonopencvpython-imaging-libraryoverlay

OpenCV throws a bad argument error when using addWeighted()


I am trying to add an overlay on top of an image using cv2.addWeighted(...) but it throws the following error:

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'

This error doesn't make sense to me because I checked the docs and my arguments were appropriate. This is my code.

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

Update

So the overlay works now but there are some issues. I made the following change to my code:

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

This is what happens when I change the color on the overlay.

enter image description here

New full code:

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')


Solution

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

    Set color to overlay:

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