Soltius
Soltius

Reputation: 2273

OpenCV's fitEllipse() fails to detect obvious ellipse's correct dimensions

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

Upvotes: 0

Views: 1899

Answers (1)

Miki
Miki

Reputation: 41775

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

Upvotes: 1

Related Questions