Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Fit ellipse to an image

I have a webcam feed using OpenCV, and I am trying to fit an ellipse in real time.

The code I am using at the moment works, but it fails to fit an ellipse to the image a lot of the time. What other methods of ellipse fitting to an image can I pursue?

Current code:

def find_ellipses(img): #img is grayscale image of what I want to fit
        ret,thresh = cv2.threshold(img,127,255,0)
        _,contours,hierarchy = cv2.findContours(thresh, 1, 2)

        if len(contours) != 0:
            for cont in contours:
                if len(cont) < 5:
                    break
                elps = cv2.fitEllipse(cont)
                return elps  #only returns one ellipse for now
        return None

Where elps is of the form (x_centre,y_centre),(minor_axis,major_axis),angle

Here is an example of what I want to successfully fit an ellipse to. My current code fails with this image when I don't want it to.

enter image description here

like image 720
Sam Avatar asked Jul 22 '16 16:07

Sam


1 Answers

Turns out I was wrong is just getting the first ellipse from the function. While I thought the first calculated ellipse was the most correct one, what I actually had to do was go through all the ellipses - and choose the most suitable one that bounded the object in the image.

like image 65
Sam Avatar answered Nov 01 '22 18:11

Sam