Reputation: 151
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!
Upvotes: 11
Views: 21296
Reputation: 1
the cv2.resize() function takes the (width, height) as argument, which is different from what the img.shape shows (height,width) for example: img1 = cv2.imread("./1.jpg") img2 = cv2.imread("./2.jpg") img1.shape is (200,300) and img2.shape is (200,290) to resize img2 into (200,300) you have to run: img2= cv2.resize(img2, (300,200)) then you can make sure they are in the same shape
Upvotes: 0
Reputation: 21
even i was getting the same error. Its because of different sizes of images,then i used ROI(Region of Image), i,e., just take a portion of the image which is same as another image size. use this code:
part=img[0:168,0:300]
Then you get same size images and then perform operations on them.
Upvotes: 2
Reputation: 536
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()
Upvotes: 6
Reputation: 18331
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.
Upvotes: 15