Connected Components 3D

3.26.1 · active · verified Thu Apr 16

Connected Components 3D (cc3d) is a Python library for performing connected component labeling on discrete and continuous multilabel 3D and 2D images. It efficiently handles 26, 18, and 6 connected variants for 3D images, and 4 or 8 connected variants for 2D images, including support for periodic boundaries. The library is currently at version 3.26.1 and is actively maintained, offering significant performance improvements over general-purpose libraries for multi-label and large volumetric datasets.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to apply connected component labeling to a 3D NumPy array. It initializes a binary image, then uses `cc3d.connected_components` to label distinct regions. The `return_N=True` argument also provides the total count of components found. Different `connectivity` options (e.g., 6, 18, 26 for 3D; 4, 8 for 2D) can be specified, with 26 being the default for 3D.

import cc3d
import numpy as np

# Create a sample 3D binary image
labels_in = np.zeros((10, 10, 10), dtype=np.int32)
labels_in[2:5, 2:5, 2:5] = 1
labels_in[6:8, 6:8, 6:8] = 1
labels_in[4,4,4] = 0 # Introduce a gap for demonstration

print(f"Input shape: {labels_in.shape}, dtype: {labels_in.dtype}")

# Perform connected component labeling with 26-connectivity (default)
# Also return the number of connected components (N)
labels_out, N = cc3d.connected_components(labels_in, return_N=True, connectivity=26)

print(f"\nOutput labeled image (slice 5):\n{labels_out[:,:,5]}")
print(f"Number of connected components found: {N}")

# Example of extracting a single component
# for segid in range(1, N + 1):
#     extracted_component = (labels_out == segid).astype(labels_in.dtype)
#     print(f"Component {segid} volume: {np.sum(extracted_component)}")

view raw JSON →