L = bwlabel(BW, n) returns
a matrix L, of the same size as BW,
containing labels for the connected objects in BW.
The variable n can have a value of either 4 or
8, where 4 specifies 4-connected objects and 8 specifies 8-connected
objects. If the argument is omitted, it defaults to 8.

The elements of L are integer values greater
than or equal to 0. The pixels labeled 0 are the
background. The pixels labeled 1 make up one object;
the pixels labeled 2 make up a second object; and
so on.

[L, num] = bwlabel(BW, n) returns
in num the number of connected objects found in BW.

[gpuarrayL, num] = bwlabel(gpuarrayBW,
n) performs the labeling operation on a GPU. The input
image and output image are gpuArrays. n can
be a numeric array or a gpuArray.

Class Support

BW can be logical or numeric, and it must
be real, two-dimensional, and nonsparse. L is of
class double. gpuarrayBW and gpuarrayL are gpuArrays.

The functions bwlabel, bwlabeln,
and bwconncomp all compute connected components
for binary images. bwconncomp replaces the use
of bwlabel and bwlabeln. It
uses significantly less memory and is sometimes faster than the other
functions.

Input
Dimension

Output Form

Memory Use

Connectivity

bwlabel

2-D

Double-precision label matrix

High

4 or 8

bwlabeln

N-D

Double-precision label matrix

High

Any

bwconncomp

N-D

CC struct

Low

Any

Using find with bwlabel

You can use the MATLAB^{®}find function
in conjunction with bwlabel to return vectors of
indices for the pixels that make up a specific object. For example,
to return the coordinates for the pixels in object 2, enter the following:

[r, c] = find(bwlabel(BW)==2)

You can display the output matrix as a pseudocolor indexed image.
Each object appears in a different color, so the objects are easier
to distinguish than in the original image. For more information, see label2rgb.

Using labelmatrix and regionprops

To compute a label matrix having a more memory-efficient data
type (e.g., uint8 versus double),
use the labelmatrix function on the output of bwconncomp.
For more information, see the reference page for each function.

To extract features from a binary image using regionprops with
default connectivity, just pass BW directly into regionprops,
i.e., regionprops(BW).