Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Ananyamukh6/total variation (#250)

Ananya Mukherjee176b727087cd
diff --git a/docs/source/losses.rst b/docs/source/losses.rst
index e469aaf4b..919a5af1f 100644
--- a/docs/source/losses.rst
+++ b/docs/source/losses.rst
@@ -4,6 +4,7 @@ kornia.losses
.. currentmodule:: kornia.losses
.. autofunction:: dice_loss
+.. autofunction:: total_variation
.. autofunction:: tversky_loss
.. autofunction:: focal_loss
.. autofunction:: ssim
@@ -14,3 +15,4 @@ kornia.losses
.. autoclass:: FocalLoss
.. autoclass:: SSIM
.. autoclass:: InverseDepthSmoothnessLoss
+.. autoclass:: TotalVariation
diff --git a/kornia/__init__.py b/kornia/__init__.py
index 5874614d2..64ee00633 100644
--- a/kornia/__init__.py
+++ b/kornia/__init__.py
@@ -56,6 +56,7 @@ from kornia.losses import (
dice_loss,
tversky_loss,
inverse_depth_smoothness_loss,
+ total_variation
)
from kornia.utils import (
one_hot,
diff --git a/kornia/filters/filter.py b/kornia/filters/filter.py
index c1392bb4e..f757c353f 100644
--- a/kornia/filters/filter.py
+++ b/kornia/filters/filter.py
@@ -21,9 +21,9 @@ def filter2D(input: torch.Tensor, kernel: torch.Tensor,
r"""Function that convolves a tensor with a kernel.
The function applies a given kernel to a tensor. The kernel is applied
- indepentdently at each depth channel of the tensor. Before applying the
+ independently at each depth channel of the tensor. Before applying the
kernel, the function applies padding according to the specified mode so
- that the output reaims in the same shape.
+ that the output remains in the same shape.
Args:
input (torch.Tensor): the input tensor with shape of
diff --git a/kornia/losses/__init__.py b/kornia/losses/__init__.py
index 07421a3f4..4ed157d70 100644
--- a/kornia/losses/__init__.py
+++ b/kornia/losses/__init__.py
@@ -6,3 +6,4 @@ from .depth_smooth import (
InverseDepthSmoothnessLoss, inverse_depth_smoothness_loss
)
from .divergence import kl_div_loss_2d, js_div_loss_2d
+from .total_variation import TotalVariation, total_variation
diff --git a/kornia/losses/total_variation.py b/kornia/losses/total_variation.py
new file mode 100644
index 000000000..ebc8ffeab
--- /dev/null
+++ b/kornia/losses/total_variation.py
@@ -0,0 +1,40 @@
+import torch
+import torch.nn as nn
+
+
+class TotalVariation(nn.Module):
+ r"""Computes the Total Variation according to
+ [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:`()`
+ Examples:
+ >>> kornia.losses.total_variation(torch.ones(3,4,4)) # tensor(0.)
+ >>> tv = kornia.losses.TotalVariation()
+ >>> output = tv(torch.ones(2,3,4,4)) # tensor([0., 0.])
+ >>> output.backward()
+ """
+ def __init__(self) -> None:
+ super(TotalVariation, self).__init__()
+
+ def forward( # type: ignore
+ self, img) -> torch.Tensor:
+ return total_variation(img)
+
+
+def total_variation(img: torch.Tensor) -> torch.Tensor:
+ r"""Function that computes Total Variation.
+
+ See :class:`~kornia.losses.TotalVariation` for details.
+ """
+ if not torch.is_tensor(img):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(img)}")
+ img_shape = img.shape
+ if len(img_shape) == 3 or len(img_shape) == 4:
+ pixel_dif1 = img[..., 1:, :] - img[..., :-1, :]
+ pixel_dif2 = img[..., :, 1:] - img[..., :, :-1]
+ reduce_axes = (-3, -2, -1)
+ else:
+ raise ValueError("Expected input tensor to be of ndim 3 or 4, but got " + str(len(img_shape)))
+
+ return pixel_dif1.abs().sum(dim=reduce_axes) + pixel_dif2.abs().sum(dim=reduce_axes)
diff --git a/test/test_losses.py b/test/test_losses.py
index cce4325e0..36ba11dbd 100644
--- a/test/test_losses.py
+++ b/test/test_losses.py
@@ -265,3 +265,78 @@ class TestDivergenceLoss:
def test_kl_div_loss_2d_without_reduction(self, input, target, expected):
actual = kornia.losses.kl_div_loss_2d(input, target, reduction='none')
assert_allclose(actual, expected)
+
+
+class TestTotalVariation:
+ # Total variation of constant vectors is 0
+ @pytest.mark.parametrize('input,expected', [
+ (torch.ones(3, 4, 5), torch.zeros(())),
+ (2 * torch.ones(2, 3, 4, 5), torch.zeros(2)),
+ ])
+ def test_tv_on_constant(self, input, expected):
+ actual = kornia.losses.total_variation(input)
+ assert_allclose(actual, expected)
+
+ # Total variation for 3D tensors
+ @pytest.mark.parametrize('input,expected', [
+ (torch.tensor([[[0.11747694, 0.5717714, 0.89223915, 0.2929412, 0.63556224],
+ [0.5371079, 0.13416398, 0.7782737, 0.21392655, 0.1757018],
+ [0.62360305, 0.8563448, 0.25304103, 0.68539226, 0.6956515],
+ [0.9350611, 0.01694632, 0.78724295, 0.4760313, 0.73099905]],
+
+ [[0.4788819, 0.45253807, 0.932798, 0.5721999, 0.7612051],
+ [0.5455887, 0.8836531, 0.79551977, 0.6677338, 0.74293613],
+ [0.4830376, 0.16420758, 0.15784949, 0.21445751, 0.34168917],
+ [0.8675162, 0.5468113, 0.6117004, 0.01305223, 0.17554593]],
+
+ [[0.6423703, 0.5561105, 0.54304767, 0.20339686, 0.8553698],
+ [0.98024786, 0.31562763, 0.10122144, 0.17686582, 0.26260805],
+ [0.20522952, 0.14523649, 0.8601968, 0.02593213, 0.7382898],
+ [0.71935296, 0.9625162, 0.42287344, 0.07979459, 0.9149871]]]), torch.tensor(33.001236)),
+ (torch.tensor([[[0.09094203, 0.32630223, 0.8066123],
+ [0.10921168, 0.09534764, 0.48588026]]]), torch.tensor(1.6900232)),
+ ])
+ def test_tv_on_3d(self, input, expected):
+ assert_allclose(kornia.losses.total_variation(input), expected)
+
+ # Total variation for 4D tensors
+ @pytest.mark.parametrize('input,expected', [
+ (torch.tensor([[[[0.8756, 0.0920],
+ [0.8034, 0.3107]],
+ [[0.3069, 0.2981],
+ [0.9399, 0.7944]],
+ [[0.6269, 0.1494],
+ [0.2493, 0.8490]]],
+ [[[0.3256, 0.9923],
+ [0.2856, 0.9104]],
+ [[0.4107, 0.4387],
+ [0.2742, 0.0095]],
+ [[0.7064, 0.3674],
+ [0.6139, 0.2487]]]]), torch.tensor([5.0054283, 3.1870906])),
+ (torch.tensor([[[[0.1104, 0.2284, 0.4371],
+ [0.4569, 0.1906, 0.8035]]],
+ [[[0.0552, 0.6831, 0.8310],
+ [0.3589, 0.5044, 0.0802]]],
+ [[[0.5078, 0.5703, 0.9110],
+ [0.4765, 0.8401, 0.2754]]]]), torch.tensor([1.9565653, 2.5786452, 2.2681699])),
+ ])
+ def test_tv_on_4d(self, input, expected):
+ assert_allclose(kornia.losses.total_variation(input), expected)
+
+ # Expect ValueError to be raised when tensors of ndim != 3 or 4 are passed
+ @pytest.mark.parametrize('input', [
+ torch.rand(2, 3, 4, 5, 3),
+ torch.rand(3, 1),
+ ])
+ def test_tv_on_invalid_dims(self, input):
+ with pytest.raises(ValueError) as ex_info:
+ kornia.losses.total_variation(input)
+
+ # Expect TypeError to be raised when non-torch tensors are passed
+ @pytest.mark.parametrize('input', [
+ 1,
+ [1, 2],
+ ])
+ def test_tv_on_invalid_types(self, input):
+ with pytest.raises(TypeError) as ex_info:
+ kornia.losses.total_variation(input)