Python错误集锦:OpenCV add运算时报错error: (-5:Bad argument) When the input arrays in add/subtract/multiply/divide functions have different types, the output array type must be explicitly specified in function ‘cv::arithm_op’

原文链接:http://www.juzicode.com/archives/5921

错误提示:

OpenCV add运算时报错error: (-5:Bad argument) When the input arrays in add/subtract/multiply/divide functions have different types, the output array type must be explicitly specified in function ‘cv::arithm_op’

#VX公众号:桔子code / juzicode.com
import cv2
import numpy as np
print('cv2.__version__:',cv2.__version__)
img = cv2.imread('lena.jpg')[0:256,0:256]
img2 = np.full((256,256,3),55,np.float32)
img_res = cv2.add(img,img2)
cv2.imshow('img_res',img_res)
cv2.waitKey(0)
cv2.destroyAllWindows()
==========运行结果:
cv2.__version__: 4.5.2
---------------------------------------------------------------------------
error                                     Traceback (most recent call last)
<ipython-input-13-db33fa724b48> in <module>
      5 img = cv2.imread('lena.jpg')[0:256,0:256]
      6 img2 = np.full((256,256,3),55,np.float32)
----> 7 img_res = cv2.add(img,img2)
      8 cv2.imshow('img_res',img_res)
      9 cv2.waitKey(0)

error: OpenCV(4.5.2) C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-kuwfz3h3\opencv\modules\core\src\arithm.cpp:674: error: (-5:Bad argument) When the input arrays in add/subtract/multiply/divide functions have different types, the output array type must be explicitly specified in function 'cv::arithm_op'

 

错误原因:

1、图像img的数据类型为unit8,图像2的数据类型为float32,2个图像数据类型不一致时,add,subtract,multiply,divide等算术运算的返回图像需要声明其数据类型。

 

解决方法:

1、在add()函数中增加dtype入参,声明返回图像的数据类型:

#VX公众号:桔子code / juzicode.com
import cv2
import numpy as np
print('cv2.__version__:',cv2.__version__)
img = cv2.imread('lena.jpg')[0:256,0:256]
img2 = np.full((256,256,3),55,np.float32)
print('img.dtype=',img.dtype)
img_res = cv2.add(img,img2,dtype=cv2.CV_8UC3) #声明生成新的img的数据类型
cv2.imshow('img_res',img_res)
cv2.waitKey(0)
cv2.destroyAllWindows()
==========运行结果:
cv2.__version__: 4.5.2 
img.dtype= uint8

扩展内容:

  1. OpenCV-Python教程:图像的加法运算
  2. OpenCV-Python教程:图像的减法运算

 


 

如果本文还没有完全解决你的疑惑,你也可以在微信公众号“桔子code”后台给我留言,欢迎一起探讨交流。

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注