contour.h_next()错误:元组对象没有属性'h_next
我正在尝试在一张图片上绘制一个椭圆,但轮廓迭代器出现了错误。因为我对opencv还不太熟悉,所以不太确定哪里出了问题。
这是主要的代码:
img = cv2.imread("img.png")
height, width, depth = img.shape
img01 = np.zeros((height,width,3), np.uint8)
img1gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
img1blur=cv2.GaussianBlur(img1gray,(5,5),0)
img1canny=cv2.Canny(img1blur,125, 300, apertureSize=5)
img1bin=cv2.adaptiveThreshold(img1canny,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,13,2)
contours=cv2.findContours(img1bin,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
for i in contour_iterator(contours):
if len(i)>=6:
PointArray2D32f = cv.CreateMat(1,len(i),cv.CV_32F)
for (j, (x, y)) in enumerate(i):
PointArray2D32f[0, j] = (x, y)
gray = cv.CV_RGB(100, 100, 100)
cv.DrawContours(img01, i, gray, gray,0,1,8,(0,0))
(center, size, angle)=cv2.fitEllipse(contours)
center = (cv.Round(center[0]), cv.Round(center[1]))
size = (cv.Round(size[0] * 0.5), cv.Round(size[1] * 0.5))
color = cv.CV_RGB(random.randrange(256),random.randrange(256),random.randrange(256))
cv.Ellipse(img01, center, size,angle, 0, 360,color, 2, cv.CV_AA, 0)
cv2.imshow("result",img01)
这是轮廓迭代器的代码:(这个函数出错了)
def contour_iterator(contour):
while contour:
yield contour
contour = contour.h_next()//line of error
这个迭代器的代码是从源代码中的示例代码里拿来的,错误信息是:
Traceback (most recent call last):
File "C:\Users\dell\workspace\imgrec\imgpros.py", line 33, in <module>
for i in contour_iterator(contours):
File "C:\Users\dell\workspace\imgrec\imgpros.py", line 16, in contour_iterator
contour = contour.h_next()
AttributeError: 'tuple' object has no attribute 'h_next'
谢谢你
1 个回答
0
请使用cv2这个接口。把旧的和新的混在一起,肯定会出问题。
给你提供一些信息:
_, contours, hierarchy = cv2.findContours(img1bin,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
cv2.drawContours( img, contours,-1, (128,255,255), 2)
for cnt in contours:
if len(cnt) > 5: # at least 5 pts needed
box = cv2.fitEllipse(cnt)
cv2.ellipse(img,box,(0,0,200), 2)
cv2.imshow('contours', img)
cv2.waitKey()