PIXELBANKv9.1.0
Menu

Connected Components Labeling

Implement a Connected Components Labeling algorithm to identify and label distinct regions in a binary image. The task involves processing a 2D array of pixels, where each pixel has a value of either 0 or 1, and assigning a unique integer label to each connected component.

The concept of connected components is crucial in Image Segmentation, as it enables the separation of objects or regions of interest within an image. In this context, two pixels are considered connected if they are adjacent to each other, either horizontally or vertically, and have the same intensity value. The 4-connectivity criterion is used, which means that two pixels are connected if they share an edge.

To solve this problem, the following steps can be taken:

  1. Initialize an empty label matrix with the same dimensions as the input image.
  2. Iterate over each pixel in the image, and for each unlabeled pixel with a value of 1, assign a new unique label and propagate this label to all connected pixels. The key formula for this process can be represented as:
L(x,y)={kif pixel at (x, y) is connected to the k-th component0if pixel at (x, y) is background\begin{aligned} L(x, y) = \begin{cases} k & \text{if pixel at (x, y) is connected to the k-th component} \\ 0 & \text{if pixel at (x, y) is background} \end{cases} \end{aligned}

This technique is widely used in medical imaging for tumor segmentation.

Example:

Input:
image = [[1, 0, 1], [0, 0, 0], [1, 0, 1]]
Output:
([[1, 0, 2], [0, 0, 0], [3, 0, 4]], 4)
Reasoning:
  • The algorithm starts by scanning the input image and identifying the first connected component, which is the top-left 1. This component is labeled as 1.
  • It then continues scanning and finds two more isolated 1s in the first row, labeling the second one as 2.
  • In the third row, it finds two more isolated 1s, labeling them as 3 and 4 respectively, since they are not connected to any previously labeled components.
  • The resulting labeled image is [[1, 0, 2], [0, 0, 0], [3, 0, 4]], and since there are 44 unique labels, num_components is 44.

Constraints:

  • image is a 2D binary list (0 or 1)
  • Use 4-connectivity (up, down, left, right)
  • Labels start at 1 and increment
  • Return tuple (labeled_image, count)
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.