OpenCV throws a bad argument error when using addWeighted()

Question:

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

Asked By: oo92

||

Answers:

The logo and the the overlay objects have a different dtype causing a parsing error. To fix this, you must specify the dtype of the output in the addWeighted command. Here is an example with a type 32 output:

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

Sources / Additional References:
https://github.com/Prasad9/ImageAugmentationTypes/issues/2

Answered By: DapperDuck
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
Answered By: Hihikomori
F1=np.round(im1*0.3,0)
F2=np.round(im2*0.7,0)
F3=F1+F2
img=np.uint8(F3)
plt.imshow(img)
plt.show()