错误提示:
OpenCV inRange()进行阈值操作时提示error: (-215:Assertion failed) lb.type() == ub.type() in function ‘cv::inRange’
#VX公众号: 桔子code / juzicode.com
import numpy as np
import cv2
img = cv2.imread('lena.jpg')
lowerb = np.array([100, 100, 100.0])
upperb = np.array([200, 200, 200])
print(lowerb.dtype,upperb.dtype)
img_ret = cv2.inRange(img, lowerb, upperb)
cv2.imshow('raw', img)
cv2.imshow('inrange', img_ret)
cv2.waitKey(0)
cv2.destroyAllWindows()
==========运行结果:
float64 int32
-------------------------------------------------------------------------
error Traceback (most recent call last)
<ipython-input-7-d14addd49cf8> in <module>
6 upperb = np.array([200, 200, 200])
7 print(lowerb.dtype,upperb.dtype)
----> 8 img_ret = cv2.inRange(img, lowerb, upperb)
9 cv2.imshow('raw', img)
10 cv2.imshow('inrange', img_ret)
error: OpenCV(4.5.3) C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-u4kjpz2z\opencv\modules\core\src\arithm.cpp:1782: error: (-215:Assertion failed) lb.type() == ub.type() in function 'cv::inRange'
错误原因:
1、inRange入参的lowerb和upperb参数类型必须一致,但是上述代码中lowerb的类型为float64,upperb的类型为int32。
解决方法:
1、修改upperb的类型为float64,可以将其中一个参数修改为浮点类型,比如upperb = np.array([200, 200, 200.0]),这样upperb的类型也变为float64.
lowerb = np.array([100, 100, 100.0])
upperb = np.array([200, 200, 200.0])
print(lowerb.dtype,upperb.dtype)
2、或者将lowerb中元素的浮点数改为整数:lowerb = np.array([100, 100, 100])
lowerb = np.array([100, 100, 100])
upperb = np.array([200, 200, 200])
print(lowerb.dtype,upperb.dtype)
扩展内容:
如果本文还没有完全解决你的疑惑,你也可以在微信公众号“桔子code”后台给我留言,欢迎一起探讨交流。