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:
for an image like:
I need to display the text "worm" at each of the worm-like creature. However I just get it once. What are the issues?
I used to use below code to draw rectangles on the contours detected. Hope it helps.