Connected Component Labeling - Equivalence Table
As I've said in my comment to question, you can use function pixConnComp from leptonica library. Another variant is to use one of a common known algorithm for connected components labeling. For example you can use my realisation (from line 385) of conncomp labeling algorithm.

Most algorithms use two or three passes over image. My version have three passes:


Mark neighbours in each line: you just assign labels to each connected set of pixels line by line (labels are saving in matrix with image size).
Fill associative array with remarking: we assign a new labels to labels that we've get at step 1. For this operation we check neighbours of non-zero labels on image and assign to it a smallest value.
Rename markers due to associative array. 


We can combine steps 2 and 3, but in that case algorithm would be more difficult.