v9.1.1
Menu

Connected Components Labeling

hardFREEWhat is Computer Vision?Image ProcessingCV: Introduction to Computer Vision

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):

  1. First pass: Scan image, assign temporary labels
    • If pixel is foreground and has labeled neighbors, use minimum label
    • Track equivalences between labels using union-find
  2. Second pass: Resolve equivalences and relabel

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). Labels are consecutive integers 1,2,3,…1, 2, 3, \ldots assigned in raster-scan order: the region whose first pixel appears earliest (top-to-bottom, then left-to-right) gets label 1, the next gets 2, and so on.

Example

Input
image = [[1, 0, 1],
         [1, 0, 1],
         [0, 0, 0]]
connectivity = 4
Output
[[1, 0, 2], [1, 0, 2], [0, 0, 0]]
Reasoning
  • Input: image is a 3×33 \times 3 binary grid (1 = foreground, 0 = background); connectivity =4= 4 means two foreground pixels belong together only if they share an edge.
  • Foreground pixels: four, at (row 0, col 0), (row 1, col 0), (row 0, col 2) and (row 1, col 2).
  • Grouping: (0,0) and (1,0) are vertically adjacent, so they form one region; (0,2) and (1,2) form another. The all-zero column 1 keeps them apart.
  • Numbering: reading the grid top-to-bottom, left-to-right, the left region appears first, at (0,0), so it is label 1; the right region, first seen at (0,2), is label 2. Each pixel takes its region's label: [[1, 0, 2], [1, 0, 2], [0, 0, 0]].
  • Notice: the output has the same shape as the input, background stays 0, and the largest label equals the number of regions. With connectivity =8= 8 the answer here is identical, since no diagonal pair bridges the gap; a diagonal line of 1s, though, is one region under 8-connectivity but one label per pixel under 4.

Constraints

  • image: Binary 2D array (0 = background, 1 = foreground)
  • connectivity: 4 or 8 (default 4)
  • Return: Label map with same shape, unique label per component
  • Background stays 0, components labeled 1, 2, 3, ...

More from CV: Introduction to Computer Vision

solution.py

Test results

Sign in to run your code against the test cases.