Python 使椭圆适合图像

Python Fit ellipse to an image

我有一个使用 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

其中 elps 的形式为 (x_centre,y_centre),(minor_axis,major_axis),angle

这是我想要成功拟合椭圆的示例。当我不希望它出现时,我当前的代码因该图像而失败。

我会在函数之外定义我的轮廓,因为您不需要在此图像中不断重新定义它们。

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

这段代码所做的是获取我的 thresh 图像流并在其上添加一个椭圆。稍后在我的代码中,当我想调用它时,我使用行

thresh = create_ellipse(thresh,cnt)

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