pythonimage-processingcomputer-visionscikit-image

Detect ellipse parameters from a given elliptical mask


I'm following the tutorial from the skimage website to detect edges from a mask and then get the ellipse perimeters.

enter image description here

However, when I run this code I get this:

this

I've reduced the threshold in the hough_ellipse function to 100 because that's the highest value that's working (which at times doesn't work with other masks) and min_size to 10 (for the same reason). I have no experience with with image processing or computer vision and have not found any other way to get the perimeters from large number of masks.


Solution

  • Here is how to do that with fitting to an ellipse in Python/OpenCV.

    • Read the input
    • Convert to gray
    • Threshold
    • Fit ellipse to shape
    • Draw ellipse on input image
    • Save results

    Input:

    enter image description here

    import cv2
    import numpy as np
    
    # read image
    img = cv2.imread('ellipse_shape.png')
    hh, ww = img.shape[:2]
    
    # convert to grayscale
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    
    # threshold to binary and invert
    thresh = cv2.threshold(gray, 252, 255, cv2.THRESH_BINARY)[1]
    
    # fit ellipse
    # note: transpose needed to convert y,x points from numpy to x,y for opencv
    points = np.column_stack(np.where(thresh.transpose() > 0))
    hull = cv2.convexHull(points)
    ((centx,centy), (width,height), angle) = cv2.fitEllipse(hull)
    print("center x,y:",centx,centy)
    print("diameters:",width,height)
    print("orientation angle:",angle)
    
    # draw ellipse on input image
    result = img.copy()
    cv2.ellipse(result, (int(centx),int(centy)), (int(width/2),int(height/2)), angle, 0, 360, (0,0,255), 2)
    
    # show results
    cv2.imshow('image', img)
    cv2.imshow('thresh', thresh)
    cv2.imshow('result', result)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    
    # save results
    cv2.imwrite('ellipse_shape_fitted.png', result)
    

    Resulting ellipse:

    enter image description here

    Ellipse Data:

    center x,y: 291.0881042480469 337.10638427734375
    diameters: 176.3456573486328 207.72769165039062
    orientation angle: 125.05526733398438