python调用cv2.findContours时报错:ValueError: not enough values to unpack (expected 3, got 2)

完整代码如下:

import cv2
import numpy as np

img = np.zeros((200, 200), dtype=np.uint8)
img[50:150, 50:150] = 255

ret, thresh = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
image, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
color = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
img = cv2.drawContours(color, contours, -1, (0,255,0), 2)

cv2.imshow("contours", color)
cv2.waitKey()
cv2.destroyAllWindows()

但是cv2.findContours报如下错误:
ValueError: not enough values to unpack (expected 3, got 2)

python版本为3.6,opencv为4.0.0

把OpenCV 降级成3.4.3.18 就可以了,在终端输入pip install opencv-python==3.4.3.18

是哪一行出错了? 根据提示,是你参数少给了一个,应该给出三个,但你只给了两个。看下API文档说明

报错的意思是说 cv2.findContours 只返回了两个值,但是你想要三个值。

cv2.findContours 只返回 contours, hierarchy,没有 image 返回。

opencv3.2以后就不会输出三个值了,不是参数数量的问题而是预期参数个数的错误