Select second largest area in image

264 Views Asked by At

I use bwareaopen to remove small objects. Is there a function to remove the big objects? I'm trying to adapt bwareaopen however haven't been successful so far. Thanks

For ref: Here's a link to the help of bwareaopen.

2

There are 2 best solutions below

2
On BEST ANSWER

Another way if you don't want to use bwareaopen is to use regionprops, specifically with the Area and PixelIdxList attributes, filter out the elements that don't conform to the area range you want, then use the remaining elements and create a new mask. Area captures the total area of each shape while PixelIdxList captures the column major linear indices of the locations inside the image that belong to each shape. You would use the Area attribute to perform your filtering while you would use the PixelIdxList attribute to create a new output image and set these locations to true that are within the desired area range:

% Specify lower and upper bounds
LB = 30;
UB = 50;

% Run regionprops
s = regionprops(I, 'Area', 'PixelIdxList');

% Get all of the areas for each shape
areas = [s.Area];

% Remove elements from output of regionprops
% that are not within the range
s = s(areas >= LB & areas <= UB);

% Get the column-major locations of the shapes
% that have passed the check
idx = {s.PixelIdxList};
idx = cat(1, idx{:});

% Create an output image with the passed shapes
Iout = false(size(I));
Iout(idx) = true;
0
On

I found an easy way to tackle this problem described here:

"To keep only objects between, say, 30 pixels and 50 pixels in area, you can use the BWAREAOPEN command, like this:"

LB = 30;
UB = 50;
Iout = xor(bwareaopen(I,LB),  bwareaopen(I,UB));