Python ValueError: not enough values to unpack (expected 3, got 2)

Python ValueError: not enough values to unpack (expected 3, got 2)

我得到 python

代码

_, threshold = cv2.threshold(gray_roi, 3, 255, cv2.THRESH_BINARY_INV)
_, contours, _ = cv2.findContours(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
contours = sorted(contours, key=lambda x: cv2.contourArea(x), reverse=True)

错误(第 2 行)

Traceback (most recent call last):
  File "/Users/hissain/PycharmProjects/hello/hello.py", line 17, in <module>
    _, contours, _ = cv2.findContours(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
ValueError: not enough values to unpack (expected 3, got 2)

如何解决?

根据cv2.findContoursdocumentation,函数return只有2个值。您尝试解压 3.

从第二行删除第一个 _(不需要的值)以匹配文档中的签名。

_, threshold = cv2.threshold(gray_roi, 3, 255, cv2.THRESH_BINARY_INV)
contours, _ = cv2.findContours(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
contours = sorted(contours, key=lambda x: cv2.contourArea(x), reverse=True)

一般来说,当您收到此 Python 错误消息时:

ValueError: not enough values to unpack (expected x got y)

搜索您尝试解压 y 个元素的位置,并尝试通过解压 x 个元素来修复它。

请参考OpenCV参考:

https://docs.opencv.org/2.4/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=findcontours#cv2.findContours

findCounters returns(轮廓,层次),所以你的第二行应该是:

contours, hierarchy = cv2.findContours(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)