Implementation:Kornia Kornia SSIM Loss
| Knowledge Sources | |
|---|---|
| Domains | Vision, Loss_Functions |
| Last Updated | 2026-02-09 15:00 GMT |
Overview
SSIM Loss computes the Structural Dissimilarity (DSSIM) loss based on the Structural Similarity Index Measure (SSIM) for 2D images.
Description
The SSIM Loss computes the Structural Dissimilarity (DSSIM), which is derived from the Structural Similarity Index Measure (SSIM). SSIM is a perceptual metric that quantifies image quality degradation based on luminance, contrast, and structural information.
The DSSIM loss is defined as:
The SSIM computation uses a Gaussian kernel of configurable window size to smooth the images before computing the similarity. The loss is clamped to [0, 1].
The implementation supports two padding modes:
- same: Pads the input to produce output of the same spatial size.
- valid: Uses only the valid convolution area, matching the MATLAB reference implementation.
Usage
Import this loss for image generation, super-resolution, and reconstruction tasks where perceptual quality is important. SSIM-based losses capture structural differences that pixel-level losses (L1, L2) may miss, leading to perceptually better results.
Code Reference
Source Location
- Repository: Kornia
- File: kornia/losses/ssim.py
- Lines: 1-129
Signature
def ssim_loss(
img1: torch.Tensor,
img2: torch.Tensor,
window_size: int,
max_val: float = 1.0,
eps: float = 1e-12,
reduction: str = "mean",
padding: str = "same",
) -> torch.Tensor: ...
class SSIMLoss(nn.Module):
def __init__(
self,
window_size: int,
max_val: float = 1.0,
eps: float = 1e-12,
reduction: str = "mean",
padding: str = "same",
) -> None: ...
def forward(self, img1: torch.Tensor, img2: torch.Tensor) -> torch.Tensor: ...
Import
from kornia.losses import SSIMLoss
from kornia.losses import ssim_loss
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| window_size | int | Yes | Size of the Gaussian kernel for smoothing |
| max_val | float | No | Dynamic range of the images (default: 1.0) |
| eps | float | No | Small value for numerical stability (default: 1e-12) |
| reduction | str | No | Reduction mode: 'none', 'mean' (default), or 'sum' |
| padding | str | No | Padding mode: 'same' (default) or 'valid' |
| img1 | torch.Tensor | Yes | First input image with shape (B, C, H, W) |
| img2 | torch.Tensor | Yes | Second input image with shape (B, C, H, W) |
Outputs
| Name | Type | Description |
|---|---|---|
| loss | torch.Tensor | DSSIM loss value in [0, 1]; scalar for 'mean'/'sum', per-pixel for 'none' |
Usage Examples
import torch
from kornia.losses import SSIMLoss
# Create sample image tensors
input1 = torch.rand(1, 4, 5, 5)
input2 = torch.rand(1, 4, 5, 5)
# Using the module API
criterion = SSIMLoss(window_size=5)
loss = criterion(input1, input2)
# With custom parameters
criterion_custom = SSIMLoss(
window_size=11,
max_val=1.0,
eps=1e-12,
reduction="mean",
padding="valid",
)
loss = criterion_custom(input1, input2)