Steve on Image Processing

Concepts, algorithms & MATLAB

Binary image area filtering

Posted by Steve Eddins,

In my August 8 post about Pokemon Go (and I still can't quite believe that I did that), one of the processing steps was finding the centroid of the largest object in a binary image.

That reminded me of something that's been on my blog topic ideas list for a long time: filtering a binary image based on object size. Typically this operation is used as a kind of cleanup or preprocessing operation to remove small "noise-like" blobs.

Among the mathematical morphology folk, removing connected components that have an area smaller than some threshold is called area opening, and there's an Image Processing Toolbox function called bwareaopen that does it.

bw = imread('blobs.png');
imshow(bw)
title('Original')

Keep objects containing at least 10 pixels.

bw2 = bwareaopen(bw,10);
imshow(bw2)
title('Area opening')

Long-time blog readers might remember a post from five years ago in which I invited feedback on the area opening terminology and the name of the function bwareaopen. I wondered in that post whether area opening was a little too jargony. Several people posted insightful comments.

Well, that discussion had an impact. A few release cycles later, in R2014b, the toolbox development team added a new function: bwareafilt. This function "keeps" a subset of objects in the binary image based on size. There are several ways to define the subset. Here are some examples:

Keep the 10 largest objects.

bw3 = bwareafilt(bw,10);
imshow(bw3)
title('10 largest objects')

Keep the 10 smallest objects.

bw4 = bwareafilt(bw,10,'smallest');
imshow(bw4)
title('10 smallest objects')

Keep objects within a range of sizes.

bw5 = bwareafilt(bw,[20 50]);
imshow(bw5)
title('Size range: 20-50 pixels')

Keep objects with a minimum size by using Inf as the upper bound.

bw6 = bwareafilt(bw,[100 Inf]);
imshow(bw6)
title('Objects with at least 100 pixels')

Finally, let me show you a quick way to get a histogram of object sizes in an image.

bw_text = imread('text.png');
imshow(bw_text)
t = regionprops('table',bw_text,'Area');
figure
histogram(t.Area)
title('Object sizes in text image')


Get the MATLAB code

Published with MATLAB® R2016a

Add A Comment

What is 7 + 9?

Preview: hide