Why does cv2.addweighted() give an error that the operation is neither 'array op array', nor 'array op scalar', nor ' scalar op array'?

When you run this:

dst= cv2.addWeighted(img1,0.5,img2,0.5,0)

Error info:

error: (-209) The operation is neither 'array op array' 
(where arrays have the same size and the same number of channels), 
nor 'array op scalar', nor 'scalar op array' in function cv::arithm_op

Possible reasons:

  1. One or more of the img1/img2 is not np.ndarray, such as None. Maybe you havn't read it.
  2. img1.shape does not equal to img2.shape. They have different size.

You should check img1.shape and img2.shape before you directly do cv2.addWeighted if you are not sure whether they are the same size.

Or, if you want to add small image on the big one, you should use ROI/mask/slice op.


As pointed in one of the comments for the question and reason 2 in the answer above, you could also try to resize one of the images to match the other and then try the addWeighted.
Your code would then look like the below:

import cv2
import numpy as np

img1 = cv2.imread('1.png')
img2 = cv2.imread('messi.jpg')

# Read about the resize method parameters here: https://docs.opencv.org/2.4/modules/imgproc/doc/geometric_transformations.html?highlight=resize#resize
img2_resized = cv2.resize(img2, (img1.shape[1], img1.shape[0]))
dst = cv2.addWeighted(img1, 0.7, img2_resized, 0.3, 0)

cv2.imshow('dst',dst)
cv2.waitKey(0)
cv2.destroyAllWindows()