为什么 cv2.addweighted() 会给出一个错误,即操作既不是“array op array”,也不是“array op scalar”,也不是“scalar op array”?

新手上路,请多包涵

这是我的图像混合代码,但 cv2.addweighted() 函数有问题:

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

错误是:

 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

问题是什么?我搜索了这个函数,我确定这个函数是正确的。我没有理解错误!

原文由 alilolo 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.7k
2 个回答

当你运行这个:

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

错误信息:

 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

可能的原因:

  1. img1/img2 中的一个或多个是 not np.ndarray ,例如 None 。也许你还没有读过它。
  2. img1.shape 不等于 img2.shape 。它们有不同的尺寸。

你应该检查 img1.shapeimg2.shape 在你直接做之前 cv2.addWeighted 如果你不确定它们是否相同大小。

或者,如果你想在大图像上添加小图像,你应该使用 ROI / mask / slice 操作。

原文由 Stackoverflow 发布,翻译遵循 CC BY-SA 3.0 许可协议

正如上面答案中对问题和原因 2 的评论之一所指出的,您还可以尝试调整其中一张图像的大小以匹配另一张图像,然后尝试 addWeighted

您的代码将如下所示:

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

原文由 ace_racer 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进