Implementation:Kornia Kornia SSIM3D Loss
| Knowledge Sources | |
|---|---|
| Domains | Vision, Loss_Functions |
| Last Updated | 2026-02-09 15:00 GMT |
Overview
SSIM3D Loss computes a loss based on the 3D Structural Similarity Index Measure (SSIM) for volumetric data.
Description
The SSIM3D Loss extends the Structural Similarity Index Measure to 3D volumetric data. It computes the Structural Dissimilarity as:
Note that unlike the 2D SSIM loss which divides by 2, the 3D variant directly uses the complement of the SSIM value.
The SSIM3D computation uses a 3D Gaussian kernel for smoothing the volume data before computing similarity. It delegates to `kornia.metrics.ssim3d` for the actual SSIM computation.
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.
Usage
Import this loss for 3D medical image analysis tasks, video processing, and volumetric data reconstruction where you need a perceptual quality metric that operates on 3D data (e.g., CT scans, MRI volumes, video sequences).
Code Reference
Source Location
- Repository: Kornia
- File: kornia/losses/ssim3d.py
- Lines: 1-129
Signature
def ssim3d_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 SSIM3DLoss(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 SSIM3DLoss
from kornia.losses import ssim3d_loss
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| window_size | int | Yes | Size of the 3D 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 volume with shape (B, C, D, H, W) |
| img2 | torch.Tensor | Yes | Second input volume with shape (B, C, D, H, W) |
Outputs
| Name | Type | Description |
|---|---|---|
| loss | torch.Tensor | 3D SSIM loss value (1 - SSIM); scalar for 'mean'/'sum', per-voxel for 'none' |
Usage Examples
import torch
from kornia.losses import SSIM3DLoss
# Create sample 3D volume tensors
input1 = torch.rand(1, 4, 5, 5, 5)
input2 = torch.rand(1, 4, 5, 5, 5)
# Using the module API
criterion = SSIM3DLoss(window_size=5)
loss = criterion(input1, input2)
# With custom parameters
criterion_custom = SSIM3DLoss(
window_size=7,
max_val=1.0,
reduction="mean",
padding="valid",
)
loss = criterion_custom(input1, input2)