Reputation: 347
I'm new to matlab, I have a image and i want to crop all the three circles and store them. My code works for single circle in an image. But fails to work when i have more circles in image.
My code:
im=imread('D:\capture.png');
im_gray = rgb2gray(im);
BW = im2bw(im_gray, graythresh(im));
se = strel('disk',3);
bw2=imopen(BW,se);
bw2=~bw2;
s = regionprops(bw2, 'BoundingBox');
rectangle('Position', s.BoundingBox);
imCrop = imcrop(bw2, s.BoundingBox);
figure, imshow(imCrop);
Any ideas about it?
Upvotes: 0
Views: 1359
Reputation: 104474
You almost have it working. Bear in mind that when you do s.BoundingBox
by itself, you are only extracting the first circle. As such, I would recommend you make a cell array that stores the individual circles for each bounding box, then run a for
loop through all of your bounding boxes. As such, each element in your cell array would be a cropped circle. As such, try doing this:
%// Your code
im=imread('D:\capture.png');
im_gray = rgb2gray(im);
BW = im2bw(im_gray, graythresh(im));
se = strel('disk',3);
bw2=imopen(BW,se);
bw2=~bw2;
s = regionprops(bw2, 'BoundingBox');
%// New code here
circles = cell(1,numel(s));
for idx = 1 : numel(s)
rect = s(idx).BoundingBox;
circles{idx} = imcrop(bw2, rect);
end
circles
will now be a cell array of cropped circles. To access the ith circle, simply do:
imCrop = circles{i};
From your comments, you want to detect the largest and smallest circles. This can easily be done by checking the Area
attribute from regionprops
. You would find the bounding box that generates the minimum and maximum areas. You would need to modify your regionprops
call to include the Area
flag. As such:
s = regionprops(bw2, 'BoundingBox', 'Area');
[~,indMin] = min([s.Area]);
[~,indMax] = max([s.Area]);
circleSmall = circles{indMin};
circleLarge = circles{indMax};
The above code will find the circles with the minimum and maximum area, then extract those corresponding circles, assuming you've run the code to extract all of those circles in that for
loop I wrote earlier. Bear in mind that I had to enclose s.Area
in square braces. The reason why is because when you do this, you'll be able to extract all of the areas as a single array instead of a matrix with singleton dimensions, and min
/max
can't work on something like that.
Upvotes: 1