Connected component labeling helps find groups of connected pixels in images or data. It tells which parts belong together.
Connected component labeling in SciPy
from scipy.ndimage import label labeled_array, num_features = label(input_array, structure=None)
input_array is a binary or boolean array where connected regions are labeled.
structure defines connectivity (e.g., 4-connectivity or 8-connectivity in 2D). If None, uses 8-connectivity in 2D.
import numpy as np from scipy.ndimage import label input_array = np.array([[1, 0, 0], [1, 1, 0], [0, 0, 1]]) labeled_array, num_features = label(input_array) print(labeled_array) print(num_features)
import numpy as np from scipy.ndimage import label input_array = np.zeros((3,3), dtype=int) labeled_array, num_features = label(input_array) print(labeled_array) print(num_features)
import numpy as np from scipy.ndimage import label input_array = np.array([[1]]) labeled_array, num_features = label(input_array) print(labeled_array) print(num_features)
import numpy as np from scipy.ndimage import label input_array = np.array([[1, 1, 0], [0, 1, 1], [0, 0, 1]]) structure = np.array([[1,1,1], [1,1,1], [1,1,1]]) # 8-connectivity labeled_array, num_features = label(input_array, structure=structure) print(labeled_array) print(num_features)
This program creates a 5x5 grid with three groups of connected 1s. It labels each group with a unique number and prints the results.
import numpy as np from scipy.ndimage import label # Create a 5x5 binary array with three connected components input_array = np.array([ [1, 1, 0, 0, 0], [1, 1, 0, 1, 1], [0, 0, 0, 1, 1], [0, 1, 0, 0, 0], [0, 1, 1, 0, 0] ]) print("Input array:") print(input_array) # Label connected components with default connectivity labeled_array, num_features = label(input_array) print("\nLabeled array:") print(labeled_array) print(f"\nNumber of connected components: {num_features}")
Time complexity is roughly O(n), where n is the number of elements in the array.
Space complexity depends on the size of the input array and the labeled output array.
Common mistake: forgetting to use a binary array (only 0 and 1) as input.
Use connected component labeling when you want to identify and count distinct groups in data. For simple counting without location, other methods might be faster.
Connected component labeling finds groups of connected pixels in binary data.
It assigns a unique label to each connected group.
Useful for image analysis, clustering, and region detection.