6

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.

chappjc
  • 30,359
  • 6
  • 75
  • 132
user1853871
  • 249
  • 5
  • 21

2 Answers2

7

Use bwconncomp instead since it returns the coordinate indexes for region in a separate cell, where the size of each is easily discerned:

>> BW = [1 0 0; 0 0 0; 0 1 1]; % two regions
>> CC = bwconncomp(BW)
CC = 
    Connectivity: 8
       ImageSize: [3 3]
      NumObjects: 2
    PixelIdxList: {[1]  [2x1 double]}

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:

>> numPixels = cellfun(@numel,CC.PixelIdxList)
numPixels =
     1     2
>> [biggestSize,idx] = max(numPixels)
biggestSize =
     2
idx =
     2

Then you can easily make a new image with just this component:

BW2 = false(size(BW));
BW2(CC.PixelIdxList{idx}) = true;

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:

s  = regionprops(BW2, 'BoundingBox');

which gives you a rectangle s.BoundingBox which you can use to crop with BW3 = imcrop(BW2,s.BoundingBox);.

chappjc
  • 30,359
  • 6
  • 75
  • 132
  • I wonder if you could guide me on how to crop this biggest region so that it touches all four corners of the image? I'm not too sure how to go about this, would a bounding box be the best method? – user1853871 Mar 20 '14 at 17:37
  • 1
    @user1853871 Sure, see `regionprops` with the `'BoundingBox'` option: `s = regionprops(BW2, 'BoundingBox');` which gives you a rectangle `s.BoundingBox` which you can use to crop with `BW3 = imcrop(BW2,s.BoundingBox);`. Thanks for accepting and also please upvote now that you have the required rep! – chappjc Mar 20 '14 at 17:47
  • @user1853871 Awesome, thanks! Just noticed you recently hit the rep requirement to vote up is all. – chappjc Mar 20 '14 at 18:44
5

If you would like to continue with the bwlabel approach, you may use this -

Code

BW = im2bw(imread('coins.png')); %%// Coins photo from MATLAB Library

[L, num] = bwlabel(BW, 8);
count_pixels_per_obj = sum(bsxfun(@eq,L(:),1:num));
[~,ind] = max(count_pixels_per_obj);
biggest_blob = (L==ind);

%%// Display the images
figure,
subplot(211),imshow(BW)
subplot(212),imshow(biggest_blob)

Output

enter image description here

Divakar
  • 218,885
  • 19
  • 262
  • 358