Main Content

labelmatrix

Create label matrix from objects in connected components

Description

A label matrix assigns unique integer values to objects or connected components in a binary image. 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.

example

Examples

collapse all

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

BW = imread('text.png');
imshow(BW)

Figure contains an axes object. The hidden axes object 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

88

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.

imshow(L,[])

Figure contains an axes object. The hidden axes object 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.

imshow(label2rgb(L,'jet','k','shuffle'));

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

Input Arguments

collapse all

Connected components, specified as a structure with four fields. You can get a connected components structure by using the bwconncomp or bwpropfilt function.

FieldDescription
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 data type that can represent the number of objects, CC.NumObjects, as shown in the table.

Data TypeRange
uint8

CC.NumObjects ≤ 255

uint16

256 ≤ CC.NumObjects ≤ 65535

uint32

65536 ≤ CC.NumObjects ≤ 232 – 1

double

CC.NumObjects ≥ 232

Data Types: double | uint8 | uint16 | uint32

Version History

Introduced in R2009a