【问题标题】:Python ValueError: not enough values to unpack (expected 3, got 2)Python ValueError:没有足够的值来解包(预期 3,得到 2)
【发布时间】:2020-06-08 01:18:24
【问题描述】:

我正在获取 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)

错误(第二行)

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)

如何解决?

【问题讨论】:

标签: python pycharm iterable-unpacking opencover


【解决方案1】:

根据cv2.findContoursdocumentation,函数只返回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: 没有足够的值来解包(预期 x 得到 y

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

【讨论】:

    【解决方案2】:

    请参考OpenCV参考:

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

    findCounters 返回(轮廓、层次结构),所以你的第二行应该是:

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

    【讨论】:

      猜你喜欢
      • 2017-07-04
      • 2020-07-17
      • 2019-09-24
      • 2017-09-14
      • 1970-01-01
      • 2019-01-05
      • 2020-09-28
      • 2021-10-07
      • 2022-01-21
      相关资源
      最近更新 更多