我正在尝试在图像上绘制 fitellipse,但轮廓迭代器抛出错误。不知道出了什么问题,因为我是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
迭代器代码取自 scource 中的示例代码错误是:
Traceback (most recent call last):
File "C:Usersdellworkspaceimgrecimgpros.py", line 33, in <module>
for i in contour_iterator(contours):
File "C:Usersdellworkspaceimgrecimgpros.py", line 16, in contour_iterator
contour = contour.h_next()
AttributeError: 'tuple' object has no attribute 'h_next'
谢谢
请使用 cv2 API。新旧混杂是通往灾难的直路。
给你:
_, 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()
http://docs.opencv.org/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html#cv2.fitEllipse
https://github.com/Itseez/opencv/tree/2.4/samples/python2