I am trying to find the the largest object in an image and remove any other objects in the image that are smaller than it.
This is what I have but I cannot get it to work.
l=bwlabel(BW);
%the area of all objects in the image is calculated
stat = regionprops(l,'Area','PixelIdxList');
[maxValue,index] = max([stat.Area]);
%remove any connected areas smaller than the biggest object
BW2=bwareaopen(BW,[maxValue,index],8);
subplot(5, 5, 4);
imshow(BW2, []);
I am working with digital mammograms such as these. I am trying to remove all objects from the image except for the breast region.
If you would like to continue with the
bwlabel
approach, you may use this -Code
Output
Use
bwconncomp
instead since it returns the coordinate indexes for region in a separate cell, where the size of each is easily discerned:The
PixelIdxList
field is a cell array with the indexes of coordinates for each region. The length of each array is the size of each region:Then you can easily make a new image with just this component:
EDIT: From the comments, the need to crop the output image so that the region comes to the edges can be addressed with
regionprops
using the 'BoundingBox' option:which gives you a rectangle
s.BoundingBox
which you can use to crop withBW3 = imcrop(BW2,s.BoundingBox);
.