Image Processing Toolbox | ![]() ![]() |
Flood Fill
The bwfill
function performs a flood-fill operation on a binary image. You specify a background pixel as a starting point, and bwfill
changes connected background pixels (0's) to foreground pixels (1's), stopping when it reaches object boundaries. The boundaries are determined based on the type of neighborhood you specify.
This operation can be useful in removing irrelevant artifacts from images. For example, suppose you have a binary image, derived from a photograph, in which the foreground objects represent spheres. In the binary image, these objects should appear as circles, but instead are donut shaped because of reflections in the original photograph. Before doing any further processing of the image, you may want to first fill in the "donut holes" using bwfill
.
bwfill
differs from the other object-based operations in that it operates on background pixels, rather than the foreground. If the foreground is 8-connected, the background is 4-connected, and vice versa. Note, however, that as with the other object-based functions, you specify the connectedness of the foreground when you call bwfill
.
The implications of 4- vs. 8-connected foreground can be illustrated with flood-fill operation matrix.
BW1 = 0 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Regardless of whether the foreground is 4-connected or 8-connected, this image contains a single object. However, the topology of the object differs depending on the type of neighborhood. If the foreground is 8-connected, the object is a closed contour, and there are two separate background elements (the part inside the loop and the part outside). If the foreground is 4-connected, the contour is open, and there is only one background element.
Suppose you call bwfill
, specifying the pixel BW1(4,3)
as the starting point.
bwfill(BW1,4,3) ans = 0 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 1 1 1 1 1 0 0 0 1 1 1 1 1 0 0 0 1 1 1 1 1 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
bwfill
fills in just the inside of the loop, because bwfill
uses an 8-connected foreground by default. If you specify a 4-connected foreground instead, bwfill
fills in the entire image, because the entire background is a single 8-connected element.
bwfill(BW1,4,3,4) ans = 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Note that unlike other binary image operations, bwfill
pads with 1's rather than 0's along the image border. This prevents the fill operation from wrapping around the border.
You can also use bwfill
interactively, selecting starting pixels with a mouse. See the reference page for bwfill
for more information.
![]() | Perimeter Determination | Connected-Components Labeling | ![]() |