x, y, w, h = cv2.boundingRect(np.array(cnt))
在执行以上代码时,出现以下错误:
error: OpenCV(4.5.2) C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-k1ohfcms\opencv\modules\imgproc\src\shapedescr.cpp:874: error: (-215:Assertion failed) npoints >= 0 && (depth == CV_32F || depth == CV_32S) in function ‘cv::pointSetBoundingRect’
修改为以下语句可以解决问题:
x, y, w, h = cv2.boundingRect(np.array(cnt[Index]))
报错原因与 cv2.findContours
函数的返回值有关。
findContours
函数返回两个参数,contours
和heridency
。
如果直接把contours
参数传入cv2.boundingRect
函数,会因为contours
维数比需要的维数超出一维。导致以上错误。
解决方法为在contours
后指定某个切片