Python / Contour OpenCV returns "too many values to unpack"

Question:

I’m having a problem with this tutorial: https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_contours/py_contour_features/py_contour_features.html
Indeed, I encounter this error when I try to execute this code:

import numpy as np
import cv2

img = cv2.imread("onepoint.png", 0)

canny_img = cv2.Canny(img,150,200)
ret,thresh = cv2.threshold(canny_img,127,255,0)
contours,hierarchy = cv2.findContours(thresh, 1, 2)

cnt = contours[0]
M = cv2.moments(cnt)
print M

Here is the error:

  File "contours.py", line 13, in <module>
    contours,hierarchy = cv2.findContours(thresh, 1, 2)
ValueError: too many values to unpack

I do not understand why this error occurs. I understand that cv2.findContours (thresh, 1, 2) returns to me 3 "arrays", but why? If a person at the kindness to explain to me I am a taker 🙁

I’m trying to frame the words of this image:

picture

I’m totally new to OpenCV, I guess you’ll understand,

Thank in advance

Asked By: Corentin Mar

||

Answers:

You’ll need to change it to

im, contours,hierarchy = cv2.findContours(thresh, 1, 2)

Or, if you only care about the contours:

(_, contours, _) = cv2.findContours(thresh, 1, 2)

The function has changed in OpenCV 3.

Answered By: Jan