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 Otsu Threshold

From Leeroopedia


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

Overview

Implements Otsu's automatic thresholding algorithm for PyTorch tensors, computing the optimal threshold that maximizes inter-class variance between foreground and background.

Description

This module is part of the Kornia library's filters subpackage. It provides the otsu_threshold function and OtsuThreshold nn.Module class for automatic image thresholding. The implementation computes a histogram of the input tensor, then uses vectorized operations to find the threshold that maximizes the between-class (inter-class) variance, following Otsu's method. The module supports inputs of various dimensionalities (1D through 5D) by flattening them appropriately via transform_input. It supports both a fast non-differentiable histogram (using torch.histc) and a slower differentiable histogram mode. The function can return either the thresholded image or a binary mask.

Usage

Import this function or class when you need automatic binarization of grayscale images without manually specifying a threshold, such as for document image binarization, foreground/background separation, or preprocessing for contour detection.

Code Reference

Source Location

Signature

class OtsuThreshold(torch.nn.Module):
    def __init__(self) -> None: ...
    def transform_input(self, x: torch.Tensor,
                        original_shape: Optional[torch.Size] = None
                        ) -> Tuple[torch.Tensor, torch.Size]: ...
    def forward(self, x: torch.Tensor, nbins: int = 256,
                slow_and_differentiable: bool = False
                ) -> Tuple[torch.Tensor, torch.Tensor]: ...

def otsu_threshold(
    x: torch.Tensor,
    nbins: int = 256,
    slow_and_differentiable: bool = False,
    return_mask: bool = False,
) -> Tuple[torch.Tensor, torch.Tensor]: ...

Import

from kornia.filters import otsu_threshold
from kornia.filters.otsu_thresholding import OtsuThreshold

I/O Contract

Inputs

Name Type Required Description
x torch.Tensor Yes Input tensor (image or batch). Supports 1D through 5D tensors. Supported dtypes: uint8, int8, int16, int32, int64, float16, bfloat16, float32, float64.
nbins int No (default 256) Number of bins for histogram computation.
slow_and_differentiable bool No (default False) If True, uses a differentiable histogram computation (slower but gradient-compatible).
return_mask bool No (default False) If True, returns a binary mask instead of the thresholded image (functional API only).

Outputs

Name Type Description
thresholded torch.Tensor The thresholded tensor (values below threshold set to 0), or a binary mask if return_mask=True. Same shape as input.
threshold torch.Tensor The computed Otsu threshold values. Shape depends on flattened channel count.

Usage Examples

import torch
from kornia.filters import otsu_threshold

# Basic usage with an integer tensor
x = torch.tensor([[10, 20, 30], [40, 50, 60], [70, 80, 90]])
thresholded, threshold = otsu_threshold(x)
print(thresholded)
# tensor([[ 0,  0,  0],
#         [ 0, 50, 60],
#         [70, 80, 90]])
print(threshold)  # tensor([40])

# Batch of images
x_batch = torch.rand(2, 1, 64, 64)
thresholded, thresholds = otsu_threshold(x_batch)
print(thresholded.shape)  # torch.Size([2, 1, 64, 64])

# Get binary mask instead
mask, thresholds = otsu_threshold(x_batch, return_mask=True)

# Differentiable mode for gradient-based optimization
thresholded, thresholds = otsu_threshold(x_batch, slow_and_differentiable=True)

Related Pages

Page Connections

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