I am designing an algorithm in which I have to traverse through every contour in an image and apply a condition on it. I am using OpenCV library to do this. And the code is as follows:
i=0 gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) ret,thresh = cv2.threshold(gray,1,255,0) contours,hierarchy=cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) while contours: if (cv2.contourArea(contours[i]) < 5000 and cv2.arcLength(contours[i],True) < 200 ): cv2.drawContours(img,contours,i,(0,255,0),3) i = i+1 contours = contours.h_next()
The error is:
Traceback (most recent call last): File "C:UsersNOOR BRARDocumentsCollege Stuff5th SEMe-yantratask1PS1_Task1Task1_Practicetest_imagescountourImagemine.py", line 55, in <module> contours = contours.h_next() AttributeError: 'list' object has no attribute 'h_next'
Advertisement
Answer
I have never used h_next but whenever I’ve iterated over contours
for cnt in contours: if (cv2.contourArea(cnt) < 5000 and cv2.arcLength(cnt, True) < 200 ): cv2.drawContours(img, [cnt], -1, (0,255,0), 3)
has worked.
It appears that you’re mixing the iterator n_next with [i]…try the following
while contours: if (cv2.contourArea(contours) < 5000 and cv2.arcLength(contours, True) < 200 ): cv2.drawContours(img, [contours], -1, (0,255,0), 3) i = i+1 contours = contours.h_next()