使用 cv2 库在 python 中遍历轮廓时出现问题
Problems in traversing contours in python using cv2 library
我正在设计一种算法,我必须在其中遍历图像中的每个轮廓并对其应用条件。我正在使用 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 Stuffth 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'
我从未使用过 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()
我正在设计一种算法,我必须在其中遍历图像中的每个轮廓并对其应用条件。我正在使用 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 Stuffth 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'
我从未使用过 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()