Read a binary image into the workspace. Display the image.
BW = imread('text.png');
imshow(BW)
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,[])
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'));