KhalifaYakub
KhalifaYakub

Reputation: 5

Is there a reason findContours is giving me an error even though it shouldn't?

---------------------------------------------------------------------------

ValueError Traceback (most recent call last) in 1 im = image_list[4] 2 ret,thresh = cv2.threshold(im,127,255,0) ----> 3 image, contours, hierarchy = cv2.findContours(thresh , cv2.RETR_TREE , cv2.CHAIN_APPROX_SIMPLE) 4 image = cv2.drawContours(image, contours, -1, (0,255,0), 3) 5

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

Upvotes: 0

Views: 137

Answers (1)

fmw42
fmw42

Reputation: 53089

Different versions of OpenCV return different numbers of items from cv2.findContours.

OpenCV 4 and OpenCV 2 have similar behavior returning two items, whereas OpenCV 3 returns three items.

Your version apparently only wants 2 items. So try

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


or if you want something version independent, then if you need the hierarchy use

contours = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
hierarchy = contours[1] if len(contours) == 2 else contours[2]
contours = contours[0] if len(contours) == 2 else contours[1]


or if you just want the contours simply

contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]


Upvotes: 1

Related Questions