使用cv2库在python中遍历等高线时遇到的问题

使用cv2库在python中遍历等高线时遇到的问题,python,python-2.7,image-processing,opencv-contour,Python,Python 2.7,Image Processing,Opencv Contour,我正在设计一种算法,在该算法中,我必须遍历图像中的每个轮廓,并对其应用一个条件。我正在使用cv2库来实现这一点。代码如下: 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: i

我正在设计一种算法,在该算法中,我必须遍历图像中的每个轮廓,并对其应用一个条件。我正在使用cv2库来实现这一点。代码如下:

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()
i=0
灰色=cv2.CVT颜色(img,cv2.COLOR\U BGR2GRAY)
ret,thresh=cv2。阈值(灰色,1255,0)
等高线,层次=cv2.findContours(阈值,cv2.RETR\u树,cv2.CHAIN\u近似值\u简单)
而等高线:
如果(cv2.等高线面积(等高线[i])小于5000且cv2.弧长(等高线[i],真)小于200):
cv2.等高线图(img,等高线图,i,(0255,0),3)
i=i+1
等高线=等高线。h_next()
错误是:

Traceback (most recent call last):
File "C:\Users\NOOR BRAR\Documents\College Stuff\5th SEM\e-yantra\task1\PS1_Task1\Task1_Practice\test_images\countourImagemine.py", line 55, in <module>
contours = contours.h_next()
AttributeError: 'list' object has no attribute 'h_next'
回溯(最近一次呼叫最后一次):
文件“C:\Users\NOOR BRAR\Documents\College Stuff\5th SEM\e-yantra\task1\PS1\u task1\task1\u Practice\test\u images\countourImagemine.py”,第55行
等高线=等高线。h_next()
AttributeError:“list”对象没有属性“h_next”

我从未使用过h_next,但每当我在轮廓上迭代时

for cnt in contours:
    if (cv2.contourArea(cnt) < 5000 and cv2.arcLength(cnt, True) < 200 ):
        cv2.drawContours(img, [cnt], -1, (0,255,0), 3)
对于轮廓中的cnt:
如果(cv2.轮廓面积(cnt)<5000且cv2.弧长(cnt,真)<200):
cv2.等高线图(img,[cnt],-1,(0255,0),3)
他成功了

似乎您正在将迭代器n_next与[i]混合使用……请尝试以下操作

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()
while等高线:
如果(cv2.等高线面积(等高线)<5000,cv2.弧长(等高线,真)<200):
cv2.等高线图(img,[等高线],-1,(0255,0),3)
i=i+1
等高线=等高线。h_next()

我从未使用过h_next,但每当我在轮廓上迭代时

for cnt in contours:
    if (cv2.contourArea(cnt) < 5000 and cv2.arcLength(cnt, True) < 200 ):
        cv2.drawContours(img, [cnt], -1, (0,255,0), 3)
对于轮廓中的cnt:
如果(cv2.轮廓面积(cnt)<5000且cv2.弧长(cnt,真)<200):
cv2.等高线图(img,[cnt],-1,(0255,0),3)
他成功了

似乎您正在将迭代器n_next与[i]混合使用……请尝试以下操作

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()
while等高线:
如果(cv2.等高线面积(等高线)<5000,cv2.弧长(等高线,真)<200):
cv2.等高线图(img,[等高线],-1,(0255,0),3)
i=i+1
等高线=等高线。h_next()