Draw line and Cut off Circuler area

后端 未结 2 418
半阙折子戏
半阙折子戏 2021-01-23 08:19

I have got the below Image after running the below code.

file=\'grayscale.png\';
I=imread(file);
bw = im2bw(I);
bw = bwareaopen(bw,870);
imwrite(bw,\'n         


        
相关标签:
2条回答
  • 2021-01-23 08:48

    The convexhull of the white pixels will give you a fairly good approximation of the circle. You can find the center as the centroid of the area of the hull and the radius as the average distance from the center to the hull vertices.

    0 讨论(0)
  • 2021-01-23 08:58

    Alternatively, you can optimize/fit the circle with least r that contains all the points:

    bw = imread('http://i.stack.imgur.com/il0Va.png');
    [yy xx]=find(bw);
    

    Now, let p be a three vector parameterizing a circle: p(1), p(2) are the x-y coordinates of the center and p(3) its radii. Then we want to minimize r (i.e., p(3)):

    obj = @(p) p(3);
    

    Subject to all points inside the circle

    con = @(p) deal((xx-p(1)).^2+(yy-p(2)).^2-p(3).^2, []);
    

    Optimizing with fmincon:

    [p, fval] = fmincon(obj, [mean(xx), mean(yy), size(bw,1)/4], [],[],[],[],[],[],con);
    

    Yields

    p =
    471.6397  484.4164  373.2125
    

    Drawing the result

    imshow(bw,'border','tight');
    colormap gray;hold on;
    t=linspace(-pi,pi,1000);
    plot(p(3)*cos(t)+p(1),p(3)*sin(t)+p(2),'r', 'LineWidth',1);
    

    You can generate a binary mask of the same size as bw with true in the circle and false outside

    msk = bsxfun(@plus, ((1:size(bw,2))-p(1)).^2, ((1:size(bw,1)).'-p(2)).^2 ) <= p(3).^2;
    

    The mask looks like:

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