Python将椭圆拟合到图像

Sam*_*Sam 12 python opencv ellipse

我有一个使用OpenCV的网络摄像头,我正在尝试实时拟合椭圆.

我目前使用的代码可以工作,但很多时候它无法在图像中使用椭圆.我还可以采用哪种椭圆拟合图像的方法?

当前代码:

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
Run Code Online (Sandbox Code Playgroud)

elps形式在哪里(x_centre,y_centre),(minor_axis,major_axis),angle

以下是我想成功拟合椭圆的示例.当我不想要它时,我当前的代码会失败.

在此输入图像描述

Sam*_*Sam 3

事实证明我错了,只是从函数中获取了第一个椭圆。虽然我认为第一个计算出的椭圆是最正确的,但我实际上要做的是遍历所有椭圆 - 并选择最合适的椭圆来限制图像中的对象。