使用cv2库遍历python中轮廓的问题

时间:2015-11-27 06:33:16

标签: 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:
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()

错误是:

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'

1 个答案:

答案 0 :(得分:0)

我从未使用过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)

已经有效了。

您似乎正在将迭代器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()