Unable to display bounding rectangles around contours in OpenCV (Python)

3.1k views Asked by At

I have written this code to draw rectangular boxes around contours drawn in an image, however on running, I get everything right except the boxes, which I don't see at all. What's the error?

for cnt,heir in zip(contours, hierarchy):
    (x,y,w,h) = cv2.boundingRect(cnt);
    cv2.rectangle(im2,(x,y),(x+w,y+h),(0,255,0),2)

cv2.drawContours(im2, contours, -1, (255,255,255), 2);   
cv2.imshow("Contours",im2);

PS. I use OpenCV 3.1.0 and Python 2.7

EDIT: I tried iterating through each contour and in order to check it I modified the code as follows:

for cnt,heir in zip(contours, hierarchy):
    print ('Contour Area:',cv2.contourArea(cnt));
    (x,y,w,h) = cv2.boundingRect(cnt);
    print (x,y,h,w)
    cv2.putText(im2,'worm',(x+w,y+h), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255), 2, cv2.LINE_AA);
    cv2.rectangle(im2,(x,y),(x+w,y+h),(255,0,0),2);

I printed the contour area for each, the values of (x,y,w,h) for each and putting text "worm" for each contour and drawing the rectangular boxes around each contour. However I get just 1 output:

Output for edited code

for an image like:

Source Image

I need to display the text "worm" at each of the worm-like creature. However I just get it once. What are the issues?

2

There are 2 answers

1
thewaywewere On BEST ANSWER

I used to use below code to draw rectangles on the contours detected. Hope it helps.

for contour in contours:
    # get rectangle bounding contour
    [x,y,w,h] = cv2.boundingRect(contour)

    # draw rectangle around contour on original image
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,255),2)
0
EncryptedCamel On

Simply write:

for c in contours:
    (x,y,w,h) = cv2.boundingRect(c);
    cv2.putText(im2,'worm',(x+w,y+h), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255), 2, cv2.LINE_AA);
    cv2.rectangle(im2,(x,y),(x+w,y+h),(255,0,0),2);

cv2.drawContours(im2, contours, -1, (255,255,255), 2);   
cv2.imshow("Contours",im2);

As suggested by furas, zip(contours,hierarchy) will return only one pair if hierarchy has only one. In this case a simple loop over contours list works.