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 Median Filter

From Leeroopedia


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

Overview

Applies median filtering to blur images by replacing each pixel with the median value of its local neighborhood, providing robust noise removal while preserving edges.

Description

This module is part of the Kornia library's filters subpackage. It provides the median_blur function and MedianBlur nn.Module class for non-linear image smoothing. Unlike mean or Gaussian filters, the median filter is particularly effective at removing salt-and-pepper noise while preserving edge sharpness. The implementation uses a binary kernel via get_binary_kernel2d to unfold local windows through convolution, reshapes the features to expose the kernel dimension, and then takes the median along that dimension. The file also exports the utility function _compute_zero_padding which is used by other filter modules.

Usage

Import this function or class when you need to remove impulse noise (salt-and-pepper) from images or when you want a non-linear smoothing filter that preserves edges better than linear filters.

Code Reference

Source Location

Signature

def _compute_zero_padding(kernel_size: tuple[int, int] | int) -> tuple[int, int]: ...

def median_blur(
    input: torch.Tensor,
    kernel_size: tuple[int, int] | int,
) -> torch.Tensor: ...

class MedianBlur(nn.Module):
    def __init__(self, kernel_size: tuple[int, int] | int) -> None: ...
    def forward(self, input: torch.Tensor) -> torch.Tensor: ...

Import

from kornia.filters import median_blur, MedianBlur

I/O Contract

Inputs

Name Type Required Description
input torch.Tensor (B, C, H, W) Yes The input image tensor.
kernel_size tuple[int, int] or int Yes The size of the median filter kernel.

Outputs

Name Type Description
output torch.Tensor (B, C, H, W) The median-filtered image, same shape as input.

Usage Examples

import torch
from kornia.filters import median_blur, MedianBlur

# Functional median blur
input = torch.rand(2, 4, 5, 7)
output = median_blur(input, (3, 3))
print(output.shape)  # torch.Size([2, 4, 5, 7])

# Module-based median blur
blur = MedianBlur((3, 3))
output = blur(input)
print(output.shape)  # torch.Size([2, 4, 5, 7])

# Larger kernel for stronger denoising
output_large = median_blur(input, (5, 5))

Related Pages

Page Connections

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