Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Initial commit. Adding psnr.py

ananyamukh61449a9099527
diff --git a/kornia/__init__.py b/kornia/__init__.py
index c0d7cfee4..8ee6afa70 100644
--- a/kornia/__init__.py
+++ b/kornia/__init__.py
@@ -58,7 +58,8 @@ from kornia.losses import (
dice_loss,
tversky_loss,
inverse_depth_smoothness_loss,
- total_variation
+ total_variation,
+ psnr
)
from kornia.utils import (
one_hot,
diff --git a/kornia/losses/__init__.py b/kornia/losses/__init__.py
index 4ed157d70..24212d0ff 100644
--- a/kornia/losses/__init__.py
+++ b/kornia/losses/__init__.py
@@ -7,3 +7,4 @@ from .depth_smooth import (
)
from .divergence import kl_div_loss_2d, js_div_loss_2d
from .total_variation import TotalVariation, total_variation
+from .psnr import PSNR, psnr
diff --git a/kornia/losses/psnr.py b/kornia/losses/psnr.py
new file mode 100644
index 000000000..d48904018
--- /dev/null
+++ b/kornia/losses/psnr.py
@@ -0,0 +1,36 @@
+import torch
+import torch.nn as nn
+from torch.nn.functional import mse_loss
+
+
+class PSNR(nn.Module):
+ r"""Creates a criterion that calculates the PSNR between 2 images.
+
+ Arguments:
+ max_val (float): Maximum value os signal
+
+ Shape:
+ - signal: :math:`(*)`
+ - approximation: :math:`(*)` same shape as signal
+ - output: :math:`()` a scalar
+
+ Examples:
+ >>> kornia.losses.psnr(torch.ones(1), 1.2*torch.ones(1), 2)
+ tensor(20.0000) # 10 * log(4/((1.2-1)**2)) / log(10)
+ """
+
+ def __init__(self, max_val):
+ self.max_val = max_val
+
+
+ def forward(self, signal: torch.tensor, approximation: torch.tensor):
+ return psnr(signal, approximation, self.max_val)
+
+
+def psnr (signal: torch.tensor, approximation: torch.tensor, max_val):
+ if not torch.is_tensor(signal) or not torch.is_tensor(approximation):
+ raise TypeError(f"Expected 2 torch tensors but got {type(signal)} and {type(approximation)}")
+ if signal.shape != approximation.shape:
+ raise TypeError(f"Expected tensors of equal shapes, but got {signal.shape} and {approximation.shape}")
+ mse_val = mse_loss(signal, approximation, reduction = 'mean')
+ return 10 * torch.log(max_val*max_val/mse_val)/torch.log(10)
diff --git a/kornia/losses/total_variation.py b/kornia/losses/total_variation.py
index ebc8ffeab..35ed8433e 100644
--- a/kornia/losses/total_variation.py
+++ b/kornia/losses/total_variation.py
@@ -7,7 +7,7 @@ class TotalVariation(nn.Module):
[1] https://en.wikipedia.org/wiki/Total_variation
Shape:
- Input: :math:`(N, C, H, W)` or :math:`(C, H, W)` where C = number of classes.
- - Target: :math:`(N,)` or :math:`()`
+ - Output: :math:`(N,)` or :math:`()`
Examples:
>>> kornia.losses.total_variation(torch.ones(3,4,4)) # tensor(0.)
>>> tv = kornia.losses.TotalVariation()