What is the imfill function in MATLAB, and how can I use it to fill holes in binary and grayscale images?
John Williams answered .
2025-11-20
The imfill function in MATLAB is used to fill holes in binary and grayscale images. A "hole" is defined as a set of background pixels that cannot be reached by filling in the background from the edge of the image. This function is particularly useful for image preprocessing and segmentation tasks where you need to fill gaps or voids in objects within an image.
Here's a basic example of how to use the imfill function:
For binary images:
% Read a binary image
bw = imread('binary_image.webp');
% Display the original image
imshow(bw);
title('Original Binary Image');
% Fill holes in the binary image
bw_filled = imfill(bw, 'holes');
% Display the filled image
figure;
imshow(bw_filled);
title('Filled Binary Image');
For grayscale images:
% Read a grayscale image
grayImage = imread('grayscale_image.webp');
% Display the original image
imshow(grayImage);
title('Original Grayscale Image');
% Define a seed point for filling (e.g., a pixel inside a hole)
seedPoint = [row, column]; % Replace with actual coordinates
% Fill regions starting from the seed point
filledImage = imfill(grayImage, seedPoint);
% Display the filled image
figure;
imshow(filledImage);
title('Filled Grayscale Image');
In these examples:
For binary images, imfill(bw, 'holes') fills all the holes in the binary image bw.
For grayscale images, you provide a seed point [row, column] to specify the starting location for the filling operation.
The imfill function helps in improving the quality of image segmentation and object recognition by ensuring that objects are completely filled. It is an essential tool in image processing workflows where accurate object representation is crucial.