How to detect and draw contours using OpenCV in Python?

singhuist picture singhuist · Jan 5, 2017 · Viewed 9.3k times · Source

I wrote the following code to detect and draw contours:

img = cv2.imread('test2.tif');

if not img is None:
    imgray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY);
    ret,thresh = cv2.threshold(imgray,127,255,0);
    contours,hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE);

    #draw a three pixel wide outline 
    cv2.drawContours(img,contours,-1,(0,255,0),3);

And here is the error I received:

Traceback (most recent call last): File "C:/Users/R.K.singh/Desktop/Image processing/intro-to-contours.py", line 10, in contours,hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE); ValueError: too many values to unpack

What is wrong? I am using Python 2.7 and OpenCV 3.1.0

Answer

user6542516 picture user6542516 · Jan 5, 2017

Change the following line. You are using OpenCV 3.1.0 but you have coded using OpenCV 2.7.x.

(cnts, _) = cv2.findContours(thresh.copy(), cv2.RETR_TREE,
      cv2.CHAIN_APPROX_SIMPLE)

Also this link will help you.