opencv出现Exception: Contours tuple must have length 2 or 3, otherwise OpenCV changed their cv2

本人使用的是python3.7+opencv4,而cv2.findContours()返回的值数量和类型依版本而异,比如

opencv3的findContours()返回三个值,第一个是图像,第二个是边缘,第三个是hierarchy--一种评价层级的系统。

opencv出现Exception: Contours tuple must have length 2 or 3, otherwise OpenCV changed their cv2_第1张图片

opencv4的findContours()返回两个值,第一个是边缘,第二个是hierarchy--一种评价层级的系统。

opencv出现Exception: Contours tuple must have length 2 or 3, otherwise OpenCV changed their cv2_第2张图片

opencv出现Exception: Contours tuple must have length 2 or 3, otherwise OpenCV changed their cv2_第3张图片

如果不确定版本可以这样,用一个条件语句判断返回值的数量:

items = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = items[0] if len(items) == 2 else items[1]

参考资料:

https://stackoverflow.com/questions/56158518/contours-tuple-must-have-length-2-or-3-otherwise-opencv-changed-their-cv-findco

https://docs.opencv.org/master/d3/dc0/group__imgproc__shape.html#gadf1ad6a0b82947fa1fe3c3d497f260e0

你可能感兴趣的:(opencv,python,数字图像处理,python)