This can be implemented using various Image Processing Toolbox functions. The attached example code implements the following algorithm to achive the desired result:
1. Label components using the BWLABEL function. The BWLABEL function returns a matrix 'L' of the same size as the image. Note each component is labeled with a different value and the label throughout one component is the same.
2. Now get a histogram of 'L' to get a count of the number of pixels in each component using the HIST function.
3. Get the label values for which the count is less than 5, that is, the number of pixels in that component is less than 5.
4. Iterate though all of the small components to save their row and column values in cell arrays 'M' and 'N'.
5. Modify the original image to set the small component intensity values to be 0 (black).
6. Perform a dilation operation on this image using the IMDILATE function using a rectangular structural element by STREL function.
7. Iterate through the small components to set their pixel values in this new image to be 1 (white).
Another way to implement this functionality is using the BWAREAOPEN function which morphologically open binary image (remove small objects):
I = imread('rice.png');
level = graythresh(I);
BW = im2bw(I,level);
figure(1)
imshow(BW);
title('Original Image');
im1 = bwareaopen(BW,5);
im2 = imdilate(im1, strel('square',3));
outputIm = im2 | BW;
figure(2)
imshow(outputIm);
title('Final Image')
Best Answer