3

I am getting python for,

Code

_, 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)

Error (2nd line)

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)

How to resolve it?

Yam Mesicka
  • 6,243
  • 7
  • 45
  • 64
Sazzad Hissain Khan
  • 37,929
  • 33
  • 189
  • 256
  • Does this answer your question? [Want to find contours -> ValueError: not enough values to unpack (expected 3, got 2), this appears](https://stackoverflow.com/questions/54164630/want-to-find-contours-valueerror-not-enough-values-to-unpack-expected-3-go) – Ceopee Feb 11 '21 at 08:14

2 Answers2

3

According to cv2.findContours documentation, the function return only 2 values. You try to unpack 3.

Remove the first _ (unwanted value) from the second line to match the signature from the documentation.

_, 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)

Generally speaking, when you get this Python error message:

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

Search where you try to unpack y elements, and try to fix it by unpacking x elements.

Yam Mesicka
  • 6,243
  • 7
  • 45
  • 64
1

Please refer to the OpenCV reference:

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

findCounters returns (contours, hierarchy), so your second lines should be:

contours, hierarchy = cv2.findContours(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
Chase Liu
  • 46
  • 3