0

So I know that fitEllipse has some mishaps (see this question for example), but why does it here fail completely to find an obvious ellipse's dimensions ? Am I missing something ?

import numpy as np
import cv2

img=cv2.imread(my_input_image,0)

#this will be the result image where I'll draw the found ellipse in red
img_res=cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)


nzs=cv2.findNonZero(img)

#calling fitEllipse on the non zeros
ellipse=cv2.fitEllipse(nzs)

#drawing the found ellipse
img_res=cv2.ellipse(img_res,ellipse,(0,0,255),thickness=3)

Input image (8bit binary image) : enter image description here

Output image (RBG) :
enter image description here

FindNonZero() and ellipse() seem to be working ok AFAICT.
The issue is in fitEllipse(), printing its result shows it is off Ouput of print(ellipse) yields

((270.2370300292969, 174.11227416992188), (130.22764587402344, 216.85084533691406), 116.81776428222656)

where according to documentation (OK, documentation of OCV2.4 but I don't think this function's behavior has changed in 3.2), the 3rd and 4th numbers are the width and length of the rotated rectangle. But here, they are smaller than the ones actually needed.

I'm using Python 2.7 and OpenCV 3.2

Community
  • 1
  • 1
Soltius
  • 2,162
  • 1
  • 16
  • 28

1 Answers1

1

The fitEllipse functions works correctly, but you gave it the wrong input.

You should give as input the contour of the ellipse, not all the points inside the ellipse.

You can easily get the contour using an edge detection algorithm, e.g, cv2.Canny

Miki
  • 40,887
  • 13
  • 123
  • 202
  • Ahha, as usual, I feel dumb.. Although this could maybe be made clearer in the documentation ? Thanks anyhow – Soltius Apr 10 '17 at 14:26
  • The nane is pretty clear by itself, actually :) You want to fit an ellipse to a set of points... the point thus should belong to the ellipse. Remember that only points on the boundary satisfy the ellipse equation (i.e.=0). Points inside are <0, outside >0 – Miki Apr 10 '17 at 14:29
  • I see what you mean, I was so focused on my application that I considered this function as a "fitDisc()" in my mind ! – Soltius Apr 10 '17 at 14:33