Draw line and Cut off Circuler area

2019-03-02 02:01发布

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

enter image description here

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?

2条回答
Viruses.
2楼-- · 2019-03-02 02:09

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);

enter image description here

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:

enter image description here

查看更多
一纸荒年 Trace。
3楼-- · 2019-03-02 02:20

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.

查看更多
登录 后发表回答