I am using OpenCV 2.4.11 with Python 2.7.9 on Windows 8.1. I was trying to fit ellipses onto my contours and I came across something that I can't figure out.
When I call cv2.fitEllipse and get the return value and then pass the return value directly into cv2.ellipse with the following code, the ellipses drawn onto the screen are perfect and make the optimal fit around my contours:
contours, hierarchy = cv2.findContours(binaryimage,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
for ind, cont in enumerate(contours):
elps = cv2.fitEllipse(cont)
#Feed elps directly into cv2.ellipse
cv2.ellipse(displayframe,elps,(0,0,255))
cv2.imshow("Perfectly fitted ellipses", displayframe)
The results for the above are
However, when I try to parse the actual ellipse parameters and draw the ellipse manually by passing in those parameters (see code below), it creates a "bloated" version of the ellipse that gives itself a very comfortable (yet annoying) bracket of space around the contour, as follows:
contours, hierarchy = cv2.findContours(binaryimage,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
for ind, cont in enumerate(contours):
(x,y),(MA,ma),angle = cv2.fitEllipse(cont)
#feed the parsed parameters into cv2.ellipse
cv2.ellipse(displayframe,(x,y),(MA, ma),angle,0,360,(0,0,255))
cv2.imshow("Ellipses NOT fitting the contours properly",displayframe)
The results for this annoying phenomena are:
Yes, I know that using the first method solves the problem drawing the correct ellipses. But I want to know why it is doing this because, in actual fact, I will need the parameters of the ellipses in order to do some blob tracking and if the parameters that are parsed end up giving wide unfitting ellipses like that, is it really accurate? Is the problem with the cv2.ellipse() drawing function? Any ideas on what is going wrong? Are the ellipse parameters coming out of the cv2.fitEllipse function accurate?
解决方案
You are plotting the width and height of the returned bounding box. You should plot half width and height, since the axes of the ellipse would be half width and height of its bounding box
cv2.ellipse(displayframe,(x,y),(MA/2, ma/2),angle,0,360,(0,0,255))