π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): preserve batched line and plane projections (#5046)
A Aswanth Raj91bd35497e8a
diff --git a/changelog.d/5046.fixed.md b/changelog.d/5046.fixed.mdnew file mode 100644index 000000000..621bae456--- /dev/null+++ b/changelog.d/5046.fixed.md@@ -0,0 +1,5 @@+Batched `ParametrizedLine.point_at`, `ParametrizedLine.projection`, `ParametrizedLine.intersect` and+`Hyperplane.projection` now work row by row. Previously they broadcast a per-row step or distance against the+coordinate axis: a batch of `B` lines in `D` dimensions returned rows mixed with each other when `B == D` and raised+for most other batch sizes, and a `(2, 1)` plane batch returned a `(2, 2, 3)` projection. `point_at` also reads a+`Scalar` step as its tensor and returns a `torch.Tensor`, as annotated (#5013).diff --git a/kornia/geometry/line.py b/kornia/geometry/line.pyindex 1dcfe8c23..12855a185 100644--- a/kornia/geometry/line.py+++ b/kornia/geometry/line.py@@ -27,6 +27,7 @@ from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECKfrom kornia.core.utils import _torch_svd_cast, register_module_statefrom kornia.geometry.linalg import batched_dot_productfrom kornia.geometry.plane import Hyperplane+from kornia.geometry.vector import Scalar__all__ = ["ParametrizedLine", "fit_line"]@@ -101,11 +102,12 @@ class ParametrizedLine(nn.Module):"""return ParametrizedLine(p0, F.normalize((p1 - p0), p=2, dim=-1))- def point_at(self, t: Union[float, torch.Tensor]) -> torch.Tensor:+ def point_at(self, t: Union[float, torch.Tensor, Scalar]) -> torch.Tensor:"""Get the point at :math:`t` along this line.Args:- t: step along the line.+ t: step along the line: a number or a 0-d tensor for every row, or one step per row of shape+ :math:`(B,)` or :math:`(B, 1)` for a line of shape :math:`(B, D)`.Return:tensor with the point.@@ -117,6 +119,10 @@ class ParametrizedLine(nn.Module):>>> p2 = l.point_at(0.1)"""+ if isinstance(t, Scalar):+ t = t.data+ if isinstance(t, torch.Tensor) and t.ndim > 0 and t.ndim == self.direction.ndim - 1:+ t = t[..., None]return self.origin + self.direction * tdef projection(self, point: torch.Tensor) -> torch.Tensor:@@ -126,7 +132,7 @@ class ParametrizedLine(nn.Module):point: the point to be projected."""- return self.origin + (self.direction @ (point - self.origin)) * self.direction+ return self.origin + batched_dot_product(self.direction, point - self.origin)[..., None] * self.directiondef squared_distance(self, point: torch.Tensor) -> torch.Tensor:"""Return the squared distance of a point to its projection onto the line.diff --git a/kornia/geometry/plane.py b/kornia/geometry/plane.pyindex 2cb07e5f8..2cbb0b3a7 100644--- a/kornia/geometry/plane.py+++ b/kornia/geometry/plane.py@@ -130,11 +130,7 @@ class Hyperplane(nn.Module):batch dimensions."""dist = self.signed_distance(p)- if len(dist.shape) != len(self.normal):- # non batched plane project a batch of points- dist = dist[..., None] # Nx1- # TODO: TypeError: bad operand type for unary -: 'Scalar'- return p - dist.data * self.normal+ return p - dist.data[..., None] * self.normal# TODO: make that Vector can subtract Scalar# return p - self.signed_distance(p) * self.normaldiff --git a/tests/geometry/test_line.py b/tests/geometry/test_line.pyindex 5a0903779..1614d0f7c 100644--- a/tests/geometry/test_line.py+++ b/tests/geometry/test_line.py@@ -17,10 +17,10 @@import pytestimport torch-from torch.autograd import gradcheckfrom kornia.geometry.line import ParametrizedLine, fit_linefrom kornia.geometry.plane import Hyperplane+from kornia.geometry.vector import Scalar, Vector3from testing.base import BaseTester, assert_close@@ -50,6 +50,27 @@ class TestParametrizedLine(BaseTester):self.assert_close(l1.point_at(0.5), torch.tensor([0.5, 0.0], device=device, dtype=dtype))self.assert_close(l1.point_at(1.0), torch.tensor([1.0, 0.0], device=device, dtype=dtype))+ def test_batched_point_at(self, device, dtype):+ origin = torch.tensor([[1.0, 2.0], [3.0, 4.0]], device=device, dtype=dtype)+ direction = torch.tensor([[1.0, 0.0], [1.0, 0.0]], device=device, dtype=dtype)+ steps = torch.tensor([2.0, 3.0], device=device, dtype=dtype)+ line = ParametrizedLine(origin, direction)+ expected = torch.stack([ParametrizedLine(origin[i], direction[i]).point_at(steps[i]) for i in range(2)])+ self.assert_close(line.point_at(steps), expected)+ # A (B, 1) step already carries the coordinate axis, and a Scalar is unwrapped to its tensor.+ self.assert_close(line.point_at(steps[:, None]), expected)+ from_scalar = line.point_at(Scalar(steps))+ assert type(from_scalar) is torch.Tensor+ self.assert_close(from_scalar, expected)++ def test_scalar_point_at_preserves_line_dtype(self, device, dtype):+ line = ParametrizedLine(+ torch.tensor([1.0, 2.0], device=device, dtype=dtype),+ torch.tensor([1.0, 0.0], device=device, dtype=dtype),+ )+ point = line.point_at(torch.tensor(2.0, device=device, dtype=torch.float32))+ self.assert_close(point, torch.tensor([3.0, 2.0], device=device, dtype=dtype))+def test_projection1(self, device, dtype):p0 = torch.tensor([0.0, 0.0], device=device, dtype=dtype)p1 = torch.tensor([1.0, 0.0], device=device, dtype=dtype)@@ -76,6 +97,16 @@ class TestParametrizedLine(BaseTester):point_projection = torch.tensor([1.0, 0.0], device=device, dtype=dtype)self.assert_close(l1.projection(point), point_projection)+ @pytest.mark.parametrize("batch_size", (2, 3))+ def test_batched_projection(self, device, dtype, batch_size):+ origin = torch.tensor([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], device=device, dtype=dtype)[:batch_size]+ direction = torch.tensor([[1.0, 0.0], [1.0, 0.0], [1.0, 0.0]], device=device, dtype=dtype)[:batch_size]+ point = torch.tensor([[2.0, 4.0], [6.0, 7.0], [8.0, 9.0]], device=device, dtype=dtype)[:batch_size]+ expected = torch.stack(+ [ParametrizedLine(origin[i], direction[i]).projection(point[i]) for i in range(batch_size)]+ )+ self.assert_close(ParametrizedLine(origin, direction).projection(point), expected)+def test_distance(self, device, dtype):p0 = torch.tensor([0.0, 0.0], device=device, dtype=dtype)p1 = torch.tensor([1.0, 0.0], device=device, dtype=dtype)@@ -131,6 +162,18 @@ class TestParametrizedLine(BaseTester):self.assert_close(lmbda, expected_lambda)self.assert_close(point, expected_point)+ def test_batched_intersect_plane(self, device, dtype):+ origin = torch.tensor([[0.0, 1.0, 2.0], [1.0, 2.0, 3.0]], device=device, dtype=dtype)+ direction = torch.tensor([[1.0, 0.0, 0.0], [1.0, 0.0, 0.0]], device=device, dtype=dtype)+ normal = Vector3(torch.tensor([1.0, 0.0, 0.0], device=device, dtype=dtype))+ plane = Hyperplane.from_vector(normal, Vector3(torch.tensor([3.0, 0.0, 0.0], device=device, dtype=dtype)))+ steps, points = ParametrizedLine(origin, direction).intersect(plane)+ expected_steps, expected_points = zip(+ *(ParametrizedLine(origin[i], direction[i]).intersect(plane) for i in range(2))+ )+ self.assert_close(steps, torch.stack(expected_steps))+ self.assert_close(points, torch.stack(expected_points))+def test_intersect_plane_returns_tensors(self, device, dtype):plane = Hyperplane.through(torch.tensor([0.0, 0.0, 2.0], device=device, dtype=dtype),@@ -362,15 +405,15 @@ class TestFitLine(BaseTester):assert line.direction.dtype == dtypeself.assert_close(line.direction, torch.tensor([[0.0, 1.0]], device=device, dtype=dtype))- @pytest.mark.skip(reason="numerical do not match with analytical")- def test_gradcheck(self, device):+ @pytest.mark.parametrize("dim", (2, 3))+ def test_gradcheck(self, device, dim):+ # Two point sets whose rows differ, each projected onto its own fitted line (#5013).def proxy_func(pts, weights):- line = fit_line(pts, weights)- return line.projection(pts[:, 0].T)+ return fit_line(pts, weights).projection(pts[:, 0])- pts = torch.rand(1, 3, 2, device=device, dtype=torch.float64, requires_grad=True)- weights = torch.rand(1, 3, device=device, dtype=torch.float64, requires_grad=False)- assert gradcheck(proxy_func, (pts, weights), raise_exception=True)+ pts = torch.rand(2, 5, dim, device=device)+ weights = torch.rand(2, 5, device=device)+ self.gradcheck(proxy_func, (pts, weights), requires_grad=(True, False))@pytest.mark.skip(reason="not implemented yet")def test_cardinality(self, device, dtype):diff --git a/tests/geometry/test_plane.py b/tests/geometry/test_plane.pyindex c22ec18de..0933b1164 100644--- a/tests/geometry/test_plane.py+++ b/tests/geometry/test_plane.py@@ -116,7 +116,9 @@ class TestHyperplane(BaseTester):expected = torch.ones(shape or (), device=device, dtype=dtype)self.assert_close(pl1.signed_distance(p1 + n1 * s0[..., None]), s0)assert (pl0.abs_distance(p0) < expected).all()- assert (pl1.signed_distance(pl1.projection(p0)) < expected).all()+ projected_distance = pl1.signed_distance(pl1.projection(p0)).data+ assert projected_distance.shape == (shape or ())+ self.assert_close(projected_distance, torch.zeros_like(projected_distance))assert (pl1.abs_distance(p1 + pl1.normal * s1) < expected).all()def test_projection(self, device, dtype):@@ -129,6 +131,24 @@ class TestHyperplane(BaseTester):p_in_plane_expected = torch.tensor([0.0, 0.0, 1.0], device=device, dtype=dtype)self.assert_close(p_in_plane, p_in_plane_expected)+ def test_batched_projection_preserves_shape_and_values(self, device, dtype):+ normal = Vector3(torch.tensor([[[1.0, 0.0, 0.0]], [[0.0, 1.0, 0.0]]], device=device, dtype=dtype))+ anchor = Vector3(torch.tensor([[[2.0, 0.0, 0.0]], [[0.0, 3.0, 0.0]]], device=device, dtype=dtype))+ point = Vector3(torch.tensor([[[5.0, 4.0, 1.0]], [[6.0, 7.0, 2.0]]], device=device, dtype=dtype))+ plane = Hyperplane.from_vector(normal, anchor)+ projected = plane.projection(point)+ expected = torch.stack(+ [+ Hyperplane.from_vector(Vector3(normal.data[i, 0]), Vector3(anchor.data[i, 0]))+ .projection(Vector3(point.data[i, 0]))+ .data+ for i in range(2)+ ]+ )[:, None, :]+ assert projected.data.shape == point.data.shape+ self.assert_close(projected.data, expected)+ self.assert_close(plane.signed_distance(projected).data, torch.zeros(2, 1, device=device, dtype=dtype))+@pytest.mark.skip(reason="not implemented yet")def test_cardinality(self, device, dtype):pass