Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Kornia Kornia Connected Components

From Leeroopedia


Knowledge Sources
Domains Vision, Image_Segmentation, Morphological_Operations
Last Updated 2026-02-09 15:00 GMT

Overview

Computes connected-component labelling (CCL) on binarized image tensors using iterative max-pooling.

Description

The connected_components function in the Kornia contrib package implements a Connected-Component Labelling (CCL) algorithm for binary image tensors. It works by initializing each foreground pixel with a unique label and then iteratively applying 3x3 max-pooling to propagate the largest label within connected regions. After a configurable number of iterations, all pixels in the same connected component share the same label. This approach is differentiable-friendly and runs entirely on GPU using standard PyTorch operations.

Usage

Import this function when you need to identify and label distinct connected regions in a binary image, for example after thresholding, for tasks such as cell counting, blob detection, or instance-level separation of binary masks.

Code Reference

Source Location

Signature

def connected_components(image: torch.Tensor, num_iterations: int = 100) -> torch.Tensor:

Import

from kornia.contrib import connected_components

I/O Contract

Inputs

Name Type Required Description
image torch.Tensor Yes Binarized input image with shape (*, 1, H, W), floating point in range [0, 1]
num_iterations int No Number of iterations for the algorithm to converge (default: 100)

Outputs

Name Type Description
labels torch.Tensor Label image with the same shape as input; each connected component has a unique integer label, background pixels are 0

Usage Examples

import torch
from kornia.contrib import connected_components

# Create a binary image with two separate blobs
image = torch.zeros(1, 1, 8, 8)
image[0, 0, 1:3, 1:3] = 1.0  # blob 1
image[0, 0, 5:7, 5:7] = 1.0  # blob 2

# Compute connected components
labels = connected_components(image, num_iterations=100)
print(labels.unique())  # Unique labels: 0 (background) plus one per blob

# Batch processing
batch = torch.rand(4, 1, 32, 32).round()  # random binary batch
batch_labels = connected_components(batch, num_iterations=100)

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment