opencv - Python Fit ellipse to an image


Keywords:python 


Question: 

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


2 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.

 

I would define my contours outside of the function, as you don't need to keep re-defining them in this image.

def create_ellipse(thresh,cnt):
    ellipse = cv2.fitEllipse(cnt)
    thresh = cv2.ellipse(thresh,ellipse,(0,255,0),2)
    return thresh

What this code is doing is im taking my thresh image stream and adding an ellipse on top of it. Later on in my code when I want to call it I use the line

thresh = create_ellipse(thresh,cnt)