Implementation:Kornia Kornia Unsharp Mask
| Knowledge Sources | |
|---|---|
| Domains | Vision, Image_Filtering |
| Last Updated | 2026-02-09 15:00 GMT |
Overview
Sharpens images using the unsharp masking technique, which enhances edges by computing the difference between the original image and its Gaussian-blurred version.
Description
This module is part of the Kornia library's filters subpackage. It provides the unsharp_mask function and UnsharpMask nn.Module class for image sharpening. The unsharp masking technique works by subtracting a blurred version of the image from the original and adding the result back, effectively amplifying high-frequency details (edges). The implementation uses the formula: out = 2 * image - gaussian_blur2d(image), which is efficiently computed via torch.lerp(data_blur, input, weight=2.0). The Gaussian blur is applied using gaussian_blur2d from the same filters subpackage.
Usage
Import this function or class when you need to enhance image sharpness, increase edge contrast, or counteract blurring in images, such as for display enhancement, preprocessing before feature detection, or post-processing after upsampling.
Code Reference
Source Location
- Repository: Kornia
- File: kornia/filters/unsharp.py
- Lines: 1-100
Signature
def unsharp_mask(
input: torch.Tensor,
kernel_size: tuple[int, int] | int,
sigma: tuple[float, float] | torch.Tensor,
border_type: str = "reflect",
) -> torch.Tensor: ...
class UnsharpMask(nn.Module):
def __init__(self, kernel_size: tuple[int, int] | int,
sigma: tuple[float, float] | torch.Tensor,
border_type: str = "reflect") -> None: ...
def forward(self, input: torch.Tensor) -> torch.Tensor: ...
Import
from kornia.filters import unsharp_mask, UnsharpMask
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| input | torch.Tensor (B, C, H, W) | Yes | The input image tensor to sharpen. |
| kernel_size | tuple[int, int] or int | Yes | Size of the Gaussian blur kernel used for the unsharp mask. |
| sigma | tuple[float, float] or torch.Tensor | Yes | Standard deviation of the Gaussian kernel. |
| border_type | str | No (default "reflect") | Padding mode: constant, reflect, replicate, or circular. |
Outputs
| Name | Type | Description |
|---|---|---|
| output | torch.Tensor (B, C, H, W) | The sharpened image, same shape as input. |
Usage Examples
import torch
from kornia.filters import unsharp_mask, UnsharpMask
# Functional unsharp mask
input = torch.rand(2, 4, 5, 5)
output = unsharp_mask(input, (3, 3), (1.5, 1.5))
print(output.shape) # torch.Size([2, 4, 5, 5])
# Module-based unsharp mask
sharpen = UnsharpMask((3, 3), (1.5, 1.5))
output = sharpen(input)
print(output.shape) # torch.Size([2, 4, 5, 5])
# Stronger sharpening with larger kernel and sigma
output_strong = unsharp_mask(input, (7, 7), (3.0, 3.0))