x, y, w, h = cv2.boundingRect(np.array(cnt))
When the above code is executed, the following error occurs:
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’
Modifying the following statement can solve the problem:
x, y, w, h = cv2.boundingRect(np.array(cnt[Index]))
The reason for the error is related to the return value of the cv2.findContours
function.
The findContours
function returns two parameters, contours and heridency.
If the contours parameter is directly passed into the cv2.boundingRect function
, it will be because the contours dimension exceeds the required dimension by one dimension. Cause the above error.
The solution is to specify a slice after contours