Python 值错误:解包时值数量不足(期望 3,实际得到 2)

3

我将为以下目的学习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)

如何解决?


这个回答解决了你的问题吗?想要找到轮廓 -> ValueError: not enough values to unpack (expected 3, got 2), this appears。 - Ceopee
2个回答

3
根据 cv2.findContours文档,该函数仅返回两个值。您尝试解包 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 个元素来修复它。


1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接