OpenCV断言失败:(-215:断言失败)npoints> = 0&& (深度== CV_32F ||深度== CV_32S)

这是做错了事:

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

imutils.is_cv2()返回False,即使它应该返回True.如果您不希望删除此依赖项,请更改为:

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]


我找到了原因.您关注的教程可能是在OpenCV 4发布之前发布的. OpenCV 3已更改 返回image, contours, hierarchy,而 OpenCV 4的cv2.findContours(...) 返回contours, hierarchy.因此,在OpenCV 4之前,可以正确地说,如果您使用OpenCV 2,则应该为contours[0],否则为contours[1].如果您仍然希望拥有这种兼容性",则可以更改为:


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]