Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 659
alilolo Avatar asked Dec 19 '17 09:12

alilolo


2 Answers

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.

like image 107
Kinght 金 Avatar answered Oct 31 '22 18:10

Kinght 金


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()
like image 36
ace_racer Avatar answered Oct 31 '22 18:10

ace_racer