Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

implement `kornia.geometry.linalg.euclidean_distance` (#2000)

Edgar Riba47ea7666e28a
diff --git a/docs/source/geometry.linalg.rst b/docs/source/geometry.linalg.rst
index 47aee4850..ce03ef946 100644
--- a/docs/source/geometry.linalg.rst
+++ b/docs/source/geometry.linalg.rst
@@ -11,3 +11,4 @@ kornia.geometry.linalg
.. autofunction:: point_line_distance
.. autofunction:: squared_norm
.. autofunction:: batched_dot_product
+.. autofunction:: euclidean_distance
diff --git a/kornia/geometry/linalg.py b/kornia/geometry/linalg.py
index 7133d734f..52606389b 100644
--- a/kornia/geometry/linalg.py
+++ b/kornia/geometry/linalg.py
@@ -1,7 +1,7 @@
import torch
from torch import Tensor
-from kornia.testing import KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE, check_is_tensor
+from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE, check_is_tensor
from .conversions import convert_points_from_homogeneous, convert_points_to_homogeneous
@@ -13,6 +13,7 @@ __all__ = [
"point_line_distance",
"squared_norm",
"batched_dot_product",
+ "euclidean_distance",
]
@@ -226,11 +227,6 @@ def point_line_distance(point: Tensor, line: Tensor, eps: float = 1e-9) -> Tenso
return numerator / (denominator + eps)
-def squared_norm(x: Tensor, keepdim: bool = False) -> Tensor:
- """Return the squared norm of a vector."""
- return (x * x).sum(-1, keepdim)
-
-
def batched_dot_product(x: Tensor, y: Tensor, keepdim: bool = False) -> Tensor:
"""Return a batched version of .dot()"""
KORNIA_CHECK_SHAPE(x, ["B", "N"])
@@ -238,6 +234,29 @@ def batched_dot_product(x: Tensor, y: Tensor, keepdim: bool = False) -> Tensor:
return (x * y).sum(-1, keepdim)
+def squared_norm(x: Tensor, keepdim: bool = False) -> Tensor:
+ """Return the squared norm of a vector."""
+ return batched_dot_product(x, x, keepdim)
+
+
+def euclidean_distance(x: Tensor, y: Tensor, keepdim: bool = False, eps: float = 1e-6) -> Tensor:
+ """Compute the Euclidean distance between two set of n-dimensional points.
+
+ More: https://en.wikipedia.org/wiki/Euclidean_distance
+
+ Args:
+ x: first set of points of shape :math:`(*, N)`.
+ y: second set of points of shape :math:`(*, N)`.
+ keepdim: whether to keep the dimension after reduction.
+ eps: small value to have numerical stability.
+ """
+ KORNIA_CHECK_SHAPE(x, ["*", "N"])
+ KORNIA_CHECK_SHAPE(y, ["*", "N"])
+ KORNIA_CHECK(x.shape == y.shape)
+
+ return (x - y + eps).pow(2).sum(-1, keepdim).sqrt()
+
+
# aliases
batched_squared_norm = squared_norm
diff --git a/test/geometry/test_linalg.py b/test/geometry/test_linalg.py
index c98e650d0..7d0dd18bd 100644
--- a/test/geometry/test_linalg.py
+++ b/test/geometry/test_linalg.py
@@ -5,7 +5,7 @@ from torch.autograd import gradcheck
import kornia
import kornia.geometry.linalg as kgl
import kornia.testing as utils # test utils
-from kornia.testing import assert_close
+from kornia.testing import BaseTester, assert_close
def identity_matrix(batch_size, device, dtype):
@@ -390,3 +390,39 @@ class TestPointsLinesDistances:
pts = torch.rand(2, 3, 2, device=device, requires_grad=True, dtype=torch.float64)
lines = torch.rand(2, 3, 3, device=device, requires_grad=True, dtype=torch.float64)
assert gradcheck(kgl.point_line_distance, (pts, lines), raise_exception=True)
+
+
+class TestEuclideanDistance(BaseTester):
+ def test_smoke(self, device, dtype):
+ pt1 = torch.tensor([0, 0, 0], device=device, dtype=dtype)
+ pt2 = torch.tensor([1, 0, 0], device=device, dtype=dtype)
+ dst = kgl.euclidean_distance(pt1, pt2)
+ self.assert_close(dst, torch.tensor(1.0, device=device, dtype=dtype))
+
+ @pytest.mark.parametrize("shape", [(2,), (3,), (1, 2), (2, 3)])
+ def test_cardinality(self, device, dtype, shape):
+ pt1 = torch.rand(shape, device=device, dtype=dtype)
+ pt2 = torch.rand(shape, device=device, dtype=dtype)
+ dst = kgl.euclidean_distance(pt1, pt2)
+ assert len(dst.shape) == len(shape) - 1
+
+ def test_exception(self, device, dtype):
+ pt1 = torch.tensor([0, 0, 0], device=device, dtype=dtype)
+ pt2 = torch.rand(1, 2, device=device, dtype=dtype)
+ with pytest.raises(Exception):
+ kgl.euclidean_distance(pt1, pt2)
+
+ def test_gradcheck(self, device):
+ pt1 = torch.rand(2, 3, device=device, dtype=torch.float64, requires_grad=True)
+ pt2 = torch.rand(2, 3, device=device, dtype=torch.float64, requires_grad=True)
+ assert gradcheck(kgl.euclidean_distance, (pt1, pt2), raise_exception=True)
+
+ def test_jit(self, device, dtype):
+ pt1 = torch.rand(2, 3, device=device, dtype=dtype)
+ pt2 = torch.rand(2, 3, device=device, dtype=dtype)
+ op = kgl.euclidean_distance
+ op_jit = torch.jit.script(op)
+ self.assert_close(op(pt1, pt2), op_jit(pt1, pt2))
+
+ def test_module(self, device, dtype):
+ pass