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:
JavaScript
x
10
10
1
i=0
2
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
3
ret,thresh = cv2.threshold(gray,1,255,0)
4
contours,hierarchy=cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
5
while contours:
6
if (cv2.contourArea(contours[i]) < 5000 and cv2.arcLength(contours[i],True) < 200 ):
7
cv2.drawContours(img,contours,i,(0,255,0),3)
8
i = i+1
9
contours = contours.h_next()
10
The error is:
JavaScript
1
5
1
Traceback (most recent call last):
2
File "C:UsersNOOR BRARDocumentsCollege Stuff5th SEMe-yantratask1PS1_Task1Task1_Practicetest_imagescountourImagemine.py", line 55, in <module>
3
contours = contours.h_next()
4
AttributeError: 'list' object has no attribute 'h_next'
5
Advertisement
Answer
I have never used h_next but whenever I’ve iterated over contours
JavaScript
1
4
1
for cnt in contours:
2
if (cv2.contourArea(cnt) < 5000 and cv2.arcLength(cnt, True) < 200 ):
3
cv2.drawContours(img, [cnt], -1, (0,255,0), 3)
4
has worked.
It appears that you’re mixing the iterator n_next with [i]…try the following
JavaScript
1
6
1
while contours:
2
if (cv2.contourArea(contours) < 5000 and cv2.arcLength(contours, True) < 200 ):
3
cv2.drawContours(img, [contours], -1, (0,255,0), 3)
4
i = i+1
5
contours = contours.h_next()
6