Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error using cv2.findContours(), with python

I've recently started learning OpenCV on Python.

I'm referring to this tutorial here, to get some help on getting the contours of an image.

My code is -

import cv2
import numpy as np

img = cv2.imread('shapes.jpg', 0)
img = cv2.medianBlur(img, 5)
thresh =     cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
cv2.THRESH_BINARY,11,2)

cv2.imshow('Thresh', thresh)
cv2.waitKey(0)
cv2.destroyAllWindows()

image, contours, hierarchy =   cv2.findContours(thresh.copy(),cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

cv2.drawContours(image, countours, -1, (0,255,0), 3)
cv2.imshow('Contours', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

The first thresholded image is appearing, but after that I get an error message as

Traceback (most recent call last):
  File "contours.py", line 21, in <module>
    image, contours, hierarchy =     cv2.findContours(thresh.copy(),cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
ValueError: need more than 2 values to unpack

Any help to resolve this issue will be appreciated.

like image 315
Souvik Saha Avatar asked Oct 27 '16 07:10

Souvik Saha


3 Answers

Look at this example.

cv2.findContours(...)

only returns two objects, you're trying to unpack it into three.

change that line to this:

contours, hierarchy =   cv2.findContours(thresh.copy(),cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

and it should work.

like image 68
will Avatar answered Oct 16 '22 14:10

will


The tutorial you have linked is for OpenCV version 3. cv2.findContours does return 3 objects in that version.

So either update opencv or use the solution by @will .

like image 26
ham Avatar answered Oct 16 '22 12:10

ham


In version 4.1.2-dev it returns only two values. You have to unpack it with two values and then use cv2.drawContours() to see them. This is the link to the documentation: https://docs.opencv.org/master/d4/d73/tutorial_py_contours_begin.html

like image 44
A.Sha Avatar answered Oct 16 '22 12:10

A.Sha