Skip to content
Advertisement

How to detect and draw contours using OpenCV in Python?

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

Advertisement

Answer

In order to emphasize Selchuk’s point, the syntax involving OpenCV 3.x has changed a little bit. It has a different return value when it comes to cv2.findContours. It returns the following image, contours, hierarchy.

Previous versions of OpenCV, however, return only contours, hierarchy. They do not return the image.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement