How can I get ellipse coefficient from fitEllipse function of OpenCV?

前端 未结 2 544
逝去的感伤
逝去的感伤 2020-12-05 06:00

I want to extract the red ball from one picture and get the detected ellipse matrix in picture.

Here is my example:

I threshold the picture, find the contou

相关标签:
2条回答
  • 2020-12-05 06:39

    Here is some code that worked for me which I based on the other responses on this thread.

    def getConicCoeffFromEllipse(e):
        # ellipse(Point(xc, yc),Size(a, b), theta)
        xc = e[0][0]
        yc = e[0][1]
        a = e[1][0]/2
        b = e[1][1]/2
        theta = math.radians(e[2])
        # See https://en.wikipedia.org/wiki/Ellipse
        # Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0 is the equation
        A = a*a*math.pow(math.sin(theta),2) + b*b*math.pow(math.cos(theta),2)
        B = 2*(b*b - a*a)*math.sin(theta)*math.cos(theta)
        C = a*a*math.pow(math.cos(theta),2) + b*b*math.pow(math.sin(theta),2)
        D = -2*A*xc - B*yc
        E = -B*xc - 2*C*yc
        F = A*xc*xc + B*xc*yc + C*yc*yc - a*a*b*b
        coef = np.array([A,B,C,D,E,F]) / F
        return coef
    
    def getConicMatrixFromCoeff(c):
        C = np.array([[c[0], c[1]/2, c[3]/2], # [ a, b/2, d/2 ]
                     [c[1]/2, c[2], c[4]/2],  # [b/2,  c, e/2 ]
                     [c[3]/2, c[4]/2, c[5]]])  # [d/2], e/2, f ]
        return C
    
    0 讨论(0)
  • 2020-12-05 06:52

    The function fitEllipse returns a RotatedRect that contains all the parameters of the ellipse.

    An ellipse is defined by 5 parameters:

    • xc : x coordinate of the center
    • yc : y coordinate of the center
    • a : major semi-axis
    • b : minor semi-axis
    • theta : rotation angle

    You can obtain these parameters like:

    RotatedRect e = fitEllipse(points);
    
    float xc    = e.center.x;
    float yc    = e.center.y;
    float a     = e.size.width  / 2;    // width >= height
    float b     = e.size.height / 2;
    float theta = e.angle;              // in degrees
    

    You can draw an ellipse with the function ellipse using the RotatedRect:

    ellipse(image, e, Scalar(0,255,0)); 
    

    or, equivalently using the ellipse parameters:

    ellipse(res, Point(xc, yc), Size(a, b), theta, 0.0, 360.0, Scalar(0,255,0));
    

    If you need the values of the coefficients of the implicit equation, you can do like (from Wikipedia):

    So, you can get the parameters you need from the RotatedRect, and you don't need to change the function fitEllipse. The solve function is used to solve linear systems or least-squares problems. Using the SVD decomposition method the system can be over-defined and/or the matrix src1 can be singular.

    For more details on the algorithm, you can see the paper of Fitzgibbon that proposed this fit ellipse method.

    0 讨论(0)
提交回复
热议问题