Main Content


Create label matrix from bwconncomp structure


A label matrix labels objects or connected components in a binary image with unique integer values. Use a label matrix to visualize distinct objects or connected components.


L = labelmatrix(CC) creates a label matrix, L, from the connected components structure CC returned by bwconncomp.


collapse all

Read a binary image into the workspace. Display the image.

BW = imread('text.png');

Figure contains an axes. The axes contains an object of type image.

Calculate the connected components using bwconncomp.

CC = bwconncomp(BW);

Create a label matrix using labelmatrix. Each label has a unique numeric index.

L = labelmatrix(CC);

Find the maximum value of the label matrix. This value indicates the number of detected objects, in this case, 88.

numObjects = max(L(:))
numObjects = uint8

Display the label matrix as an image. Because the maximum label value is much smaller than the maximum value of the uint8 data type, increase the display range of the image to make the labels more distinct.


Figure contains an axes. The axes contains an object of type image.

It is challenging to see the objects labeled with small label values. Further, it is challenging to differentiate objects with comparable label values. To make it easier to differentiate the different connected components, display the label matrix as an RGB image using label2rgb and shuffle the color order of the labels.


Figure contains an axes. The axes contains an object of type image.

Input Arguments

collapse all

Connected components, specified as a structure with four fields.

ConnectivityConnectivity of the connected components (objects)
ImageSizeSize of the binary image
NumObjectsNumber of connected components (objects) in the binary image.
PixelIdxList1-by-NumObjects cell array where the k-th element in the cell array is a vector containing the linear indices of the pixels in the k-th object.

Output Arguments

collapse all

Label matrix of contiguous regions, returned as matrix of nonnegative integers. 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.

The size of L is determined by the value of the CC.ImageSize field. The class of L depends upon the number of contiguous regions. labelmatrix uses the smallest class that can represent the number of objects, CC.NumObjects, as shown in the table.


CC.NumObjects 255


256 CC.NumObjects 65535


65536 CC.NumObjects 2321


CC.NumObjects 232

Data Types: double | uint8 | uint16 | uint32

Introduced in R2009a