OpenCV Assertion failed: (-215:Assertion failed) npoints >= 0 && (depth == CV_32F || depth == CV_32S)

This is doing the wrong thing:

contours = contours[0] if imutils.is_cv2() else contours[1]

imutils.is_cv2() is returning False even though it should return True. If you don't mind to remove this dependency, change to:

contours = contours[0]

I found out the reason. Probably, the tutorial you are following was published before OpenCV 4 was released. OpenCV 3 changed cv2.findContours(...) to return image, contours, hierarchy, while OpenCV 2's cv2.findContours(...) and OpenCV 4's cv2.findContours(...) return contours, hierarchy. Therefore, before OpenCV 4, it was correct to say that if you use OpenCV 2 it should be contours[0] else contours[1]. If you still want to have this "compatibility", you can change to:

contours = contours[1] if imutils.is_cv3() else contours[0]

In OpenCV4, cv2.findContours has only 2 return values. Contours being the FIRST value

contours, _ = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

Note that I added underscore to let go of the other return value of hierarchy


 (x, y, w, h) = cv2.boundingRect(contour.astype(np.int))