title: OpenCV: Fit ellipse with most points on contour (instead of least squares)
body: <p>I have a binarized image, which I've already used open/close morphology operations on (this is as clean as I can get it, trust me on this) that looks like so:
  <a href="https://i.stack.imgur.com/hvFJF.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hvFJF.jpg" alt="enter image description here"></a></p>
  
  <p>As you can see, there is an obvious ellipse with some distortion on the top. <strong>NOTE: I do not have prior info as to the size of the circle, and this has to run very quickly (HoughCircles is too slow, I've found).</strong> I'm trying to figure out how to fit an ellipse to it, such that it maximizes the number of points on the fitted ellipse that correspond to edges on the shape. That is, I want a result like this:
  <a href="https://i.stack.imgur.com/txhSt.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/txhSt.jpg" alt="enter image description here"></a></p>
  
  <p>However, I can't seem to find a way in OpenCV to do this. Using the common tools of <code>fitEllipse</code> (blue line) and <code>minAreaRect</code> (green line), I get these results:
  <a href="https://i.stack.imgur.com/0MDha.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0MDha.jpg" alt="enter image description here"></a></p>
  
  <p>Which obviously do not represent the actual ellipse I'm trying to detect. Any thoughts as to how I could accomplish this? Happy to see examples in Python or C++.</p>