Loading...
Implement connected components labeling for binary image segmentation.
Given a binary image, identify and label distinct connected regions. Two pixels are connected if they share an edge (4-connectivity) or corner (8-connectivity).
Union-Find Algorithm (efficient approach):
4-connectivity: Only horizontal/vertical neighbors 8-connectivity: Includes diagonal neighbors
Return a label map where each connected region has a unique integer label (background = 0).
image = [[1, 0, 1],
[1, 0, 1],
[0, 0, 0]]
connectivity = 4[[1, 0, 2], [1, 0, 2], [0, 0, 0]]
4-connectivity analysis: Top-left and bottom-left 1s are connected vertically → Component 1 Top-right and bottom-right 1s are connected vertically → Component 2
Scan row by row:
Result: Two separate components labeled 1 and 2.