This is my code for image blending but there is something wrong with the cv2.addweighted() function:
import cv2
import numpy as np
img1 = cv2.imread('1.png')
img2 = cv2.imread('messi.jpg')
dst= cv2.addWeighted(img1,0.5,img2,0.5,0)
cv2.imshow('dst',dst)
cv2.waitKey(0)
cv2.destroyAllWindows()
The error is :
Traceback (most recent call last):
dst= cv2.addWeighted(img1,0.5,img2,0.5,0)
cv2.error: C:\projects\opencv-python\opencv\modules\core\src\arithm.cpp:659: 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
What is the problem? I searched the function and I'm sure that the function is correct. I didn't understand the error!
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:
not np.ndarray
, such as None
. Maybe you havn't read it.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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With