Create label matrix from
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.
Find and Display Connected Components
Read a binary image into the workspace. Display the image.
BW = imread('text.png'); imshow(BW)
Calculate the connected components using
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.
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.
CC — Connected components
Connected components, specified as a structure with four fields.
|Connectivity of the connected components (objects)|
|Size of the binary image|
|Number of connected components (objects) in the binary image.|
L — Label matrix
matrix of nonnegative integers
Label matrix of contiguous regions, returned as matrix of nonnegative
integers. The pixels labeled
0 are the background. The
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.
Introduced in R2009a