Skip to content

Instantly share code, notes, and snippets.

@bdsaglam
Last active August 11, 2020 06:42
Show Gist options
  • Select an option

  • Save bdsaglam/15e9c9f705966afe966cb5260a2f863a to your computer and use it in GitHub Desktop.

Select an option

Save bdsaglam/15e9c9f705966afe966cb5260a2f863a to your computer and use it in GitHub Desktop.
Connected component labelling in Python
import numpy as np
# Time complexity: O(n), where n is the number of pixels in image
# Space complexity: O(n)
def label_connected_components(image: np.uint8) -> np.int:
nrow = image.shape[0]
ncol = image.shape[1]
component_map = np.full((nrow, ncol), -1, dtype=np.int)
current_comp_id = 1
for r in range(nrow):
for c in range(ncol):
labeled_any_pixel = False
queue.append((r, c))
while len(queue) > 0:
i, j = queue.popleft()
if component_map[i, j] != -1: # already visited
continue
if image[i, j] == 0: # zero pixels stay 0
component_map[i, j] = 0
continue
labeled_any_pixel = True
component_map[i, j] = current_comp_id
# add neigbors
if j > 0:
queue.append((i, j-1)) # left
if j < ncol - 1:
queue.append((i, j+1)) # right
if i > 0:
queue.append((i-1, j)) # top
if i < nrow - 1:
queue.append((i+1, j)) # bottom
if labeled_any_pixel:
current_comp_id += 1
return component_map, current_comp_id - 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment