Connected-component labeling assigns unique IDs to contiguous foreground regions in a binary image using a classical two-pass algorithm:
- First pass — Scan rows top to bottom, left to right. At each foreground pixel, examine already-visited neighbors (left, above, upper-left, upper-right for 8-connectivity). If no foreground neighbors exist, assign a new label. If one neighbor has a label, copy it. If multiple neighbors have different labels, assign one and record the equivalence.
- Second pass — Resolve all recorded equivalences using a union-find data structure, replacing temporary labels with their canonical representatives. The output has contiguous label numbers with no duplicates.
An alternative morphological approach (Solomon & Breckon): iteratively dilate from a seed pixel within one component, constrained to the original binary foreground, until convergence identifies the entire connected component. Clear from the working image, increment label, repeat until all components are labeled.