fitellipse not fitting

I get this result when fitting an ellipse to a contour (the contour is green, the fitted ellipse in blue)

Here's the original image :

Why doesn't it fit?

Here is the code :

----------

gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)

# Threshold the images
thresh1 = cv2.threshold(gray1, 127, 255, cv2.THRESH_BINARY)[1]

contours = cv2.findContours(thresh1.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[1]

cnt1 = contours[0]

# draw contours found
cv2.drawContours(img1, [cnt1], 0, green, 2)

# Fit an ellipse to the contours
ellipse = cv2.fitEllipse(cnt1)

# Draw the ellipse on the image
cv2.ellipse(img1,ellipse,(255,255,0),2)

cv2.imshow("ellipse fit 1", img1)

edit retag close merge delete

1

I'm getting the same results. I'll have a look at it tomorrow. I tried skipping the contour and simply adding every point on the line, but still the same.

( 2017-01-05 00:15:21 -0600 )edit

May be related to this bug! https://github.com/opencv/opencv/issu...

( 2017-01-05 00:50:11 -0600 )edit

Is there another free Python Function/library that I could use to fit an ellipse?

( 2017-01-05 09:03:30 -0600 )edit

Sort by ยป oldest newest most voted

Ok, I found the paper that the algorithm comes from, and there are some differences. Hewing closer to the original algorithm fixes the problem, at least for this example.

Namely, there is a comment in fitEllipse

// A - C signs inverted as proposed by APP


then three lines with negatives. If those negatives are removed, you get the correct answer.

This also fixes #4515 and #6544. That makes me happy, so I'll run the tests and commit the changes.

EDIT: Hmm, it is failing some tests though. More work to do.

more

@Tetragram Are you saying that we should change these lines

Ad[i*5] = -(double)p.x * p.x; // A - C signs inverted as proposed by APP
Ad[i*5 + 1] = -(double)p.y * p.y;
Ad[i*5 + 2] = -(double)p.x * p.y;


to this

Ad[i*5] = (double)p.x * p.x; // A - C signs inverted as proposed by APP
Ad[i*5 + 1] = (double)p.y * p.y;
Ad[i*5 + 2] = (double)p.x * p.y;

( 2017-01-06 04:35:27 -0600 )edit

If yes then the Results are pretty bad than before! I guess This is not helping!

( 2017-01-06 04:53:13 -0600 )edit

That is what I was saying. It does fix the sample, and it fixed the test cases in bug #4515 and 6544. It apparently does not work for all scenarios though. I am still working on it and will see if I can get something working for all test cases.

( 2017-01-06 17:45:24 -0600 )edit

Tetragramm, any news on the fitellipse fix? Thanks

( 2017-01-11 18:45:51 -0600 )edit

They say no news is good news. In this case however, it's just frustrating. 3 papers, 1 algorithm. And I still can't get the output of the math to match the constraints given in the papers. I'm setting up to use matlab to make sure it isn't the library I'm using.

I am still working on it though.

( 2017-01-11 19:13:16 -0600 )edit

Thanks for the update!

( 2017-01-11 19:23:05 -0600 )edit