Jump to content

Connect Leeroopedia MCP: Equip your AI agents to search best practices, build plans, verify code, diagnose failures, and look up hyperparameter defaults.

Implementation:Kornia Kornia Canny Edge Detector

From Leeroopedia


Knowledge Sources
Domains Vision Filters Edge_Detection
Last Updated 2026-02-09 15:00 GMT

Overview

Concrete tool for differentiable multi-stage Canny edge detection provided by Kornia's filters module.

Description

The Canny class implements the full Canny edge detection pipeline as a differentiable nn.Module. It performs Gaussian smoothing, Sobel gradient computation, non-maximum suppression, double thresholding, and optional hysteresis. The module returns both the gradient magnitude map and the thresholded binary edge map. Thresholds operate in the [0, 1] range on normalized images. The implementation is fully differentiable for use in training loops.

Usage

Import when you need classical edge detection with configurable sensitivity. Wrap in AugmentationSequential or use standalone.

Code Reference

Source Location

  • Repository: kornia
  • File: kornia/filters/canny.py
  • Lines: L164-242

Signature

class Canny(nn.Module):
    def __init__(
        self,
        low_threshold: float = 0.1,
        high_threshold: float = 0.2,
        kernel_size: tuple[int, int] | int = (5, 5),
        sigma: tuple[float, float] | torch.Tensor = (1, 1),
        hysteresis: bool = True,
        eps: float = 1e-6,
    ) -> None

    def forward(self, input: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]

Import

from kornia.filters import Canny

I/O Contract

Inputs

Constructor parameters:

Name Type Required Description
low_threshold float No Lower hysteresis threshold (default 0.1)
high_threshold float No Upper hysteresis threshold (default 0.2)
kernel_size int No Gaussian kernel size (default (5, 5))
sigma torch.Tensor No Gaussian sigma (default (1, 1))
hysteresis bool No Enable hysteresis edge tracking (default True)
eps float No Regularization constant (default 1e-6)

Forward parameters:

Name Type Required Description
input torch.Tensor Yes Input image tensor of shape (B, C, H, W)

Outputs

Name Type Description
magnitude torch.Tensor Gradient magnitude map of shape (B, 1, H, W)
edges torch.Tensor Binary edge map of shape (B, 1, H, W)

Usage Examples

Basic Example

import torch
from kornia.filters import Canny
from kornia.io import load_image
from kornia.utils import tensor_to_image

# Load image
img = load_image("photo.jpg", device="cuda")[None]  # (1, 3, H, W)

# Create Canny detector with custom thresholds
canny = Canny(low_threshold=0.1, high_threshold=0.3, kernel_size=5)

# Detect edges
magnitude, edges = canny(img)

# Visualize
import matplotlib.pyplot as plt
plt.imshow(tensor_to_image(edges[0]), cmap="gray")
plt.show()

Related Pages

Implements Principle

Page Connections

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