Connected-component labeling
Segmenting binary images into separate objects.
SciPy · Function
Labels connected nonzero features in an array and counts them. Connectivity is controlled by an optional structuring element.
The function treats nonzero elements as foreground and groups them into connected features according to a structuring element. It returns an integer label array and the number of features, unless an output array is supplied, in which case that array is filled in and only the count is returned.
scipy.ndimage.label(input, structure=None, output=None)| Name | Type | Description |
|---|---|---|
input | array_like | Array-like object to label; nonzero values are features and zeros are background. |
structure | array_like, optional | Optional structuring element defining feature connections; it must be centrosymmetric. |
output | None, data-type, or array_like, optional | Optional output dtype or array-like destination for the labels. |
If output is None, returns (labeled_array, num_features). If output is an ndarray, updates it with labels and returns only num_features.
import numpy as np
from scipy import ndimage
image = np.array([[1, 1, 0, 0],
[0, 1, 0, 1],
[0, 0, 0, 1]])
labels, count = ndimage.label(image)
print(labels)
print(count)This labels the two nonzero connected components and prints the label array plus their count.
Segmenting binary images into separate objects.
Counting isolated nonzero regions in masks or grids.
Writing labels into preallocated memory for downstream processing.
Nonzero input elements are treated as features and zeros as background. Connected nonzero regions receive distinct integer labels, and the function also reports how many regions it found.
Follow-up: How would connectivity be customized? Pass a structuring element through structure, ensuring that it is centrosymmetric.
Without structure, SciPy creates a default structuring element with squared connectivity equal to one. In two dimensions this gives four-neighbor connectivity rather than diagonal connectivity.
Follow-up: What must a custom structure satisfy? It must be centrosymmetric so connections are reciprocal.
With output omitted or set to None, the result is a tuple containing the labeled array and the number of features. If output is an array, that array receives the labels and only the count is returned.
Follow-up: What can output specify besides an array? It can specify a data type for the resulting labeled feature array.
scipy.ndimage.find_objectsscipy.ndimage.generate_binary_structurescipy.ndimage.sum