Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): use L2 norm in Hyperplane.through normal normalization (#5012) (#5055)

Prakhar Saini0fdfcf20a603
diff --git a/changelog.d/5055.breaking.md b/changelog.d/5055.breaking.md
new file mode 100644
index 000000000..eb8e06d80
--- /dev/null
+++ b/changelog.d/5055.breaking.md
@@ -0,0 +1 @@
+`Hyperplane.through` now divides the cross product by its Euclidean norm, so the returned normal has unit length and `signed_distance`, `abs_distance` and `projection` are right for tilted planes. It used to divide by the p = -1 "norm", so the normal of a plane through three generic points was not unit: for the plane through (1, 0, 0), (0, 2, 0) and (0, 0, 3) it was (-6, -3, -2), and distances came out 7 times too large. Axis-aligned planes, whose cross product has a zero component, used to take the SVD fallback, whose sign is arbitrary; they now take the cross-product branch, so their normal is `(p2 - p0) x (p1 - p0)` normalised and can be the negation of the previous one, which flips the sign of `signed_distance`: the plane through (0, 0, 1), (1, 0, 1) and (0, 1, 1) now has the normal (0, 0, -1) instead of (0, 0, 1). The collinearity threshold is now evaluated per batch row, relative to the dtype's machine epsilon, instead of once over the whole batch.
diff --git a/kornia/geometry/plane.py b/kornia/geometry/plane.py
index 2cbb0b3a7..d3c72af0c 100644
--- a/kornia/geometry/plane.py
+++ b/kornia/geometry/plane.py
@@ -177,23 +177,33 @@ class Hyperplane(nn.Module):
"Hyperplane.through requires three points p0, p1 and p2 of shape (..., 3); "
"the two-point (2D line) form is not supported."
)
- KORNIA_CHECK_SHAPE(p0, ["*", "3"])
- KORNIA_CHECK(p0.shape == p1.shape)
- KORNIA_CHECK(p1.shape == p2.shape)
- v0, v1 = (p2 - p0), (p1 - p0)
+
+ p0_data = _unwrap(p0)
+ p1_data = _unwrap(p1)
+ p2_data = _unwrap(p2)
+
+ KORNIA_CHECK_SHAPE(p0_data, ["*", "3"])
+ KORNIA_CHECK(p0_data.shape == p1_data.shape)
+ KORNIA_CHECK(p1_data.shape == p2_data.shape)
+
+ v0, v1 = (p2_data - p0_data), (p1_data - p0_data)
normal = torch.linalg.cross(v0, v1, dim=-1)
- norm = normal.norm(-1)
+
+ norm = torch.linalg.vector_norm(normal, dim=-1, keepdim=True)
+ v0_norm = torch.linalg.vector_norm(v0, dim=-1, keepdim=True)
+ v1_norm = torch.linalg.vector_norm(v1, dim=-1, keepdim=True)
# https://gitlab.com/libeigen/eigen/-/blob/master/Eigen/src/Geometry/Hyperplane.h#L108
- def compute_normal_svd(v0: torch.Tensor, v1: torch.Tensor) -> "Vector3":
- # NOTE: for reason torch.TensorWrapper does not stack well
- m = torch.stack((_unwrap(v0), _unwrap(v1)), -2) # Bx2x3
+ def compute_normal_svd(v0: torch.Tensor, v1: torch.Tensor) -> torch.Tensor:
+ m = torch.stack((v0, v1), -2) # Bx2x3
_, _, V = _torch_svd_cast(m) # kornia solution lies in the last row
- return _wrap(V[..., :, -1], Vector3) # Bx3
+ return V[..., :, -1] # Bx3
- normal_mask = norm <= v0.norm(-1) * v1.norm(-1) * 1e-6
- normal = torch.where(normal_mask, compute_normal_svd(v0, v1).data, normal / (norm + 1e-6))
- offset = -batched_dot_product(p0, normal)
+ eps = torch.finfo(p0_data.dtype).eps if p0_data.is_floating_point() else 1e-6
+ normal_mask = norm <= v0_norm * v1_norm * eps
+ norm_safe = torch.where(normal_mask, torch.ones_like(norm), norm)
+ normal = torch.where(normal_mask, compute_normal_svd(v0, v1), normal / norm_safe)
+ offset = -batched_dot_product(p0_data, normal)
return Hyperplane(_wrap(normal, Vector3), _wrap(offset, Scalar))
@@ -204,7 +214,7 @@ def fit_plane(points: Vector3) -> Hyperplane:
"""Fit a plane from a set of points using SVD.
Args:
- points: tensor containing a batch of sets of n-dimensional points. The expected
+ points: tensor containing a batch of sets of n-dimensional points. The expected
shape of the tensor is :math:`(N, D)`.
Return:
diff --git a/tests/geometry/test_plane.py b/tests/geometry/test_plane.py
index 0933b1164..021c6349d 100644
--- a/tests/geometry/test_plane.py
+++ b/tests/geometry/test_plane.py
@@ -18,6 +18,7 @@
import pytest
import torch
+from kornia.core.check import are_checks_enabled, disable_checks, enable_checks
from kornia.core.exceptions import BaseError
from kornia.geometry.plane import Hyperplane, fit_plane
from kornia.geometry.vector import Vector3
@@ -165,6 +166,104 @@ class TestHyperplane(BaseTester):
def test_module(self, device, dtype):
pass
- @pytest.mark.skip(reason="not implemented yet")
def test_gradcheck(self, device):
- pass
+ # A tilted triangle whose edges are neither orthogonal nor of equal length, so the SVD fallback
+ # (which torch.where differentiates as well) has distinct singular values.
+ p0 = torch.tensor([1.0, 0.0, 0.0], device=device, dtype=torch.float64)
+ p1 = torch.tensor([0.0, 2.0, 0.0], device=device, dtype=torch.float64)
+ p2 = torch.tensor([0.0, 0.0, 3.0], device=device, dtype=torch.float64)
+
+ def proxy(a, b, c):
+ plane = Hyperplane.through(a, b, c)
+ return plane.normal.data, plane.offset.data
+
+ self.gradcheck(proxy, (p0, p1, p2))
+
+ def test_through_tilted_plane_unit_normal(self, device, dtype):
+ # #5012: a tilted plane (no zero component in its normal) used to get the cross product divided by
+ # its p=-1 "norm", here (-6, -3, -2) with length 7, so distances came out 7x too large.
+ p0 = torch.tensor([1.0, 0.0, 0.0], device=device, dtype=dtype)
+ p1 = torch.tensor([0.0, 2.0, 0.0], device=device, dtype=dtype)
+ p2 = torch.tensor([0.0, 0.0, 3.0], device=device, dtype=dtype)
+
+ plane = Hyperplane.through(p0, p1, p2)
+
+ # The unit normal (p2 - p0) x (p1 - p0) / 7 and the offset -p0 . n = 6 / 7.
+ expected_normal = torch.tensor([-6.0, -3.0, -2.0], device=device, dtype=dtype) / 7.0
+ self.assert_close(plane.normal.data, expected_normal)
+ self.assert_close(plane.offset.data, torch.tensor(6.0 / 7.0, device=device, dtype=dtype))
+
+ # The point x = (1, 2, 3) has signed distance -12 / 7 and projects to x + (12 / 7) n.
+ x = torch.tensor([1.0, 2.0, 3.0], device=device, dtype=dtype)
+ self.assert_close(plane.signed_distance(x).data, torch.tensor(-12.0 / 7.0, device=device, dtype=dtype))
+ expected_projection = torch.tensor([-23.0, 62.0, 123.0], device=device, dtype=dtype) / 49.0
+ # low_tolerance: the first coordinate is 1 - 72 / 49, which cancels in float16 and bfloat16.
+ self.assert_close(plane.projection(x).data, expected_projection, low_tolerance=True)
+
+ def test_through_axis_aligned_follows_cross_product_orientation(self, device, dtype):
+ # An axis-aligned plane has a zero component in its cross product, so its p=-1 "norm" was 0 and it took
+ # the SVD fallback, whose sign is arbitrary: for this plane z = 1 it returned (0, 0, 1). It now takes the
+ # cross-product branch like every other plane, and the normal is (p2 - p0) x (p1 - p0) = (0, 0, -1).
+ p0 = torch.tensor([0.0, 0.0, 1.0], device=device, dtype=dtype)
+ p1 = torch.tensor([1.0, 0.0, 1.0], device=device, dtype=dtype)
+ p2 = torch.tensor([0.0, 1.0, 1.0], device=device, dtype=dtype)
+ plane = Hyperplane.through(p0, p1, p2)
+ self.assert_close(plane.normal.data, torch.tensor([0.0, 0.0, -1.0], device=device, dtype=dtype))
+ origin = torch.zeros(3, device=device, dtype=dtype)
+ self.assert_close(plane.signed_distance(origin).data, torch.tensor(1.0, device=device, dtype=dtype))
+
+ def test_through_batched_rows_are_independent(self, device, dtype):
+ # The collinearity threshold is per row. The p=-1 "norm" reduced over the whole batch, so an axis-aligned
+ # row sent a tilted row to the SVD fallback too, where it got a different sign than on its own.
+ p0 = torch.tensor([[1.0, 0.0, 0.0], [0.0, 0.0, 1.0]], device=device, dtype=dtype)
+ p1 = torch.tensor([[0.0, 2.0, 0.0], [1.0, 0.0, 1.0]], device=device, dtype=dtype)
+ p2 = torch.tensor([[0.0, 0.0, 3.0], [0.0, 1.0, 1.0]], device=device, dtype=dtype)
+ batched = Hyperplane.through(p0, p1, p2)
+ expected = torch.tensor([[-6.0 / 7.0, -3.0 / 7.0, -2.0 / 7.0], [0.0, 0.0, -1.0]], device=device, dtype=dtype)
+ self.assert_close(batched.normal.data, expected)
+ for i in range(2):
+ self.assert_close(batched.normal.data[i], Hyperplane.through(p0[i], p1[i], p2[i]).normal.data)
+
+ def test_through_batched_threshold_is_per_row(self, device, dtype):
+ # The fallback threshold compares each row's cross product with that row's own edge lengths. Measured
+ # against the whole batch, the 1e-4 triangle would fall below it next to the 1e4 one and take the SVD
+ # fallback, whose sign differs from the cross product's for this triangle.
+ if dtype in (torch.float16, torch.bfloat16):
+ pytest.skip("the 1e4 triangle's cross product overflows float16")
+ base = [
+ torch.tensor([1.0, 0.0, 0.0], device=device, dtype=dtype),
+ torch.tensor([0.0, 2.0, 0.0], device=device, dtype=dtype),
+ torch.tensor([0.0, 0.0, 3.0], device=device, dtype=dtype),
+ ]
+ batched = Hyperplane.through(*(torch.stack([1e-4 * p, 1e4 * p]) for p in base))
+ expected = torch.tensor([-6.0, -3.0, -2.0], device=device, dtype=dtype) / 7.0
+ self.assert_close(batched.normal.data, expected.expand(2, 3))
+
+ def test_through_degenerate_takes_svd_fallback(self, device, dtype):
+ # Collinear or coincident points leave a zero cross product, and the SVD fallback returns a finite unit normal.
+ # The gradient is not pinned: the plane through collinear points is not unique, so the fallback normal is
+ # not differentiable there. Checks are disabled so this also covers the fallback where eager calls reject
+ # these inputs.
+ checks_were_enabled = are_checks_enabled()
+ disable_checks()
+ try:
+ a = torch.tensor([1.0, 1.0, 1.0], device=device, dtype=dtype)
+ b = torch.tensor([2.0, 3.0, 4.0], device=device, dtype=dtype)
+ collinear = [a, b, 2 * b - a]
+ coincident = [a, a.clone(), a.clone()]
+ for points in (collinear, coincident):
+ plane = Hyperplane.through(*points)
+ norm = torch.linalg.vector_norm(plane.normal.data, dim=-1)
+ self.assert_close(norm, torch.tensor(1.0, device=device, dtype=dtype))
+
+ # A degenerate row does not send the other rows of its batch to the fallback.
+ tilted = [
+ torch.tensor([1.0, 0.0, 0.0], device=device, dtype=dtype),
+ torch.tensor([0.0, 2.0, 0.0], device=device, dtype=dtype),
+ torch.tensor([0.0, 0.0, 3.0], device=device, dtype=dtype),
+ ]
+ batched = Hyperplane.through(*(torch.stack([c, t]) for c, t in zip(collinear, tilted)))
+ self.assert_close(batched.normal.data[1], Hyperplane.through(*tilted).normal.data)
+ finally:
+ if checks_were_enabled:
+ enable_checks()