Draw line and Cut off Circuler area

删除回忆录丶 提交于 2020-01-11 11:54:42

问题


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,'noiseReduced.png')
subplot(2,3,1),imshow(bw);
[~, threshold] = edge(bw, 'sobel');
fudgeFactor = .5;
im = edge(bw,'sobel', threshold * fudgeFactor);
subplot(2,3,2), imshow(im), title('binary gradient mask');

se = strel('disk',5);
closedim = imclose(im,se);
subplot(2,3,3), imshow(closedim), title('Connected Cirlces');
cc = bwconncomp(closedim);

S = regionprops(cc,'Centroid'); //returns the centers S(2) for innercircle
numPixels = cellfun(@numel,cc.PixelIdxList);
[biggest,idx] = min(numPixels);
im(cc.PixelIdxList{idx}) = 0;
subplot(2,3,4), imshow(im), title('Inner Cirlces Only');
c = S(2);

My target is now to draw a red cirle around the circular object(see image) and cut the circle region(area) from the original image 'I' and save the cropped area as image or perform other tasks. How can I do it?


回答1:


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:




回答2:


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.



来源:https://stackoverflow.com/questions/40723326/draw-line-and-cut-off-circuler-area

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!