fitting a circle to a binary image

前端 未结 5 963
Happy的楠姐
Happy的楠姐 2020-12-15 12:48

I have been using skim age\'s thresholding algorithms to get some binary mask. For example, I obtain binary images like this:

5条回答
  •  清酒与你
    2020-12-15 13:27

    Here is a solution that tries to make an optimal circle fit via minimization. It soon becomes apparent that the bubble isn't a circle :) Note the use of "regionprops" for easily determining area, centroid, etc. of regions.

    Circle fit to bubble

    from skimage import io, color, measure, draw, img_as_bool
    import numpy as np
    from scipy import optimize
    import matplotlib.pyplot as plt
    
    
    image = img_as_bool(color.rgb2gray(io.imread('bubble.jpg')))
    regions = measure.regionprops(image)
    bubble = regions[0]
    
    y0, x0 = bubble.centroid
    r = bubble.major_axis_length / 2.
    
    def cost(params):
        x0, y0, r = params
        coords = draw.circle(y0, x0, r, shape=image.shape)
        template = np.zeros_like(image)
        template[coords] = 1
        return -np.sum(template == image)
    
    x0, y0, r = optimize.fmin(cost, (x0, y0, r))
    
    import matplotlib.pyplot as plt
    
    f, ax = plt.subplots()
    circle = plt.Circle((x0, y0), r)
    ax.imshow(image, cmap='gray', interpolation='nearest')
    ax.add_artist(circle)
    plt.show()
    

提交回复
热议问题