Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): stop ParametrizedLine.squared_distance cancelling near the line (#5028)

RitiGrover2ef5acadb61e
diff --git a/changelog.d/5028.fixed.md b/changelog.d/5028.fixed.md
new file mode 100644
index 000000000..b8bac632b
--- /dev/null
+++ b/changelog.d/5028.fixed.md
@@ -0,0 +1,2 @@
+`ParametrizedLine.squared_distance` and `distance` no longer go negative or return NaN for points on or near the line.
+They use the sum of squares of the perpendicular component again, row by row, instead of a cancelling identity. (#5028)
diff --git a/kornia/geometry/line.py b/kornia/geometry/line.py
index 56ce53a1b..fe183fb6a 100644
--- a/kornia/geometry/line.py
+++ b/kornia/geometry/line.py
@@ -129,23 +129,27 @@ class ParametrizedLine(nn.Module):
return self.origin + (self.direction @ (point - self.origin)) * self.direction
def squared_distance(self, point: torch.Tensor) -> torch.Tensor:
- """Return the squared distance of a point to its projection onte the line.
+ """Return the squared distance of a point to its projection onto the line.
Args:
point: the point to calculate the distance onto the line.
"""
- d = point - self.origin
- proj = torch.sum(d * self.direction, dim=-1)
- sq_norm_d = torch.sum(d * d, dim=-1)
- return sq_norm_d - proj * proj
+ perp = self._perpendicular(point)
+ return torch.sum(perp * perp, dim=-1)
def distance(self, point: torch.Tensor) -> torch.Tensor:
"""Return the distance of a point to its projections onto the line.
Args:
- point: the point to calculate the distance into the line.
+ point: the point to calculate the distance onto the line.
"""
- return self.squared_distance(point).sqrt()
+ return torch.linalg.vector_norm(self._perpendicular(point), dim=-1)
+
+ def _perpendicular(self, point: torch.Tensor) -> torch.Tensor:
+ # The component of ``point - origin`` orthogonal to the line, row by row. Its squared norm is a sum of
+ # squares, so it cannot go negative. ``||d||^2 - (d . u)^2`` cancels for points near the line.
+ d = point - self.origin
+ return d - torch.sum(d * self.direction, dim=-1, keepdim=True) * self.direction
# TODO(edgar) implement the following:
# - intersection
diff --git a/tests/geometry/test_line.py b/tests/geometry/test_line.py
index 521230b90..4f63038f8 100644
--- a/tests/geometry/test_line.py
+++ b/tests/geometry/test_line.py
@@ -92,6 +92,27 @@ class TestParametrizedLine(BaseTester):
distance_expected = torch.tensor(16.0, device=device, dtype=dtype)
self.assert_close(l1.squared_distance(point), distance_expected)
+ def test_distance_near_the_line_does_not_cancel_5016(self, device):
+ # #5016: ||d||^2 - (d . u)^2 cancelled for points near a tilted line, so squared_distance went negative
+ # and distance returned NaN, with a NaN gradient.
+ o = torch.tensor([0.3, 0.7], device=device)
+ line = ParametrizedLine(o, torch.tensor([0.28, 0.96], device=device))
+ u = line.direction.detach()
+ on_line = o + torch.linspace(-50.0, 50.0, 200, device=device)[:, None] * u
+ # One value per row: a reduction over every element also passes the checks below.
+ assert line.squared_distance(on_line).shape == (200,)
+ assert line.distance(on_line).shape == (200,)
+ assert (line.squared_distance(on_line) >= 0).all()
+ assert torch.isfinite(line.distance(on_line)).all()
+ assert line.distance(on_line).max() < 1e-4
+
+ off_line = o + 40.0 * u + 1e-3 * torch.stack([-u[1], u[0]])
+ self.assert_close(line.distance(off_line), torch.tensor(1e-3, device=device), rtol=1e-2, atol=0.0)
+
+ p = on_line[7].clone().requires_grad_(True)
+ line.distance(p).backward()
+ assert torch.isfinite(p.grad).all()
+
def test_instersect_plane(self, device, dtype):
p0 = torch.tensor([0.0, 0.0, 0.0], device=device, dtype=dtype)
p1 = torch.tensor([1.0, 0.0, 0.0], device=device, dtype=dtype)