π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): raise ShapeError for unbatched epipolar and solver inputs; drop runs of spaces from RANSAC and NamedPose messages (#6434)
Caner Demir077c70f33b85
diff --git a/changelog.d/6434.fixed.md b/changelog.d/6434.fixed.mdnew file mode 100644index 000000000..803cf083d--- /dev/null+++ b/changelog.d/6434.fixed.md@@ -0,0 +1 @@+`KRt_from_projection`, `projections_from_fundamental`, `get_perpendicular`, `get_closest_point_on_epipolar_line` and `multiply_deg_one_poly` raise `ShapeError`, naming the argument and its expected shape, when `P`, `F_mat`, `points`, `pts2`, `a` or `b` lacks the batch dimension or has an extra one. Previously they raised an `IndexError`, a `RuntimeError` or an `AssertionError` from a later step, or, for some inputs with an extra dimension, returned wrong values: `multiply_deg_one_poly` with `(A, 4, 4)` inputs, and the two epipolar functions when `lines` and `points`, or `pts1` and `pts2`, both had shape `(A, B, 3, 3)`. The two epipolar functions also raise `ShapeError` instead of a bare `AssertionError` when `points` or `pts2` has a last dimension other than 2 or 3. The too-few-correspondences message of `RANSAC` and the matrix-shape message of `NamedPose.from_rt` and `NamedPose.from_matrix` no longer contain runs of spaces, and the latter prints each expected shape once, as `[2, 2]` instead of `[2, 2]x[2, 2]`.diff --git a/kornia/geometry/epipolar/fundamental.py b/kornia/geometry/epipolar/fundamental.pyindex 514ca034c..997308f48 100644--- a/kornia/geometry/epipolar/fundamental.py+++ b/kornia/geometry/epipolar/fundamental.py@@ -23,6 +23,7 @@ from typing import Literal, Optional, Tuple, Unionimport torchfrom kornia.core.check import KORNIA_CHECK_SAME_SHAPE, KORNIA_CHECK_SHAPE+from kornia.core.exceptions import ShapeErrorfrom kornia.core.utils import _autocast_disabled, _torch_svd_cast, safe_inverse_with_maskfrom kornia.geometry.conversions import convert_points_from_homogeneous, convert_points_to_homogeneousfrom kornia.geometry.solvers.homogeneous import _det3, _null_space_lu@@ -739,13 +740,18 @@ def get_perpendicular(lines: torch.Tensor, points: torch.Tensor) -> torch.Tensor"""KORNIA_CHECK_SHAPE(lines, ["*", "N", "3"])- KORNIA_CHECK_SHAPE(points, ["*", "N", "two"])+ # points are read on dimension 2 below; an unbatched lines tensor broadcasts against them.+ KORNIA_CHECK_SHAPE(points, ["B", "N", "D"], "points must have shape (B, N, 2) or (B, N, 3).")if points.shape[2] == 2:points_h: torch.Tensor = convert_points_to_homogeneous(points)elif points.shape[2] == 3:points_h = pointselse:- raise AssertionError(points.shape)+ raise ShapeError(+ f"points must have shape (B, N, 2) or (B, N, 3), got {list(points.shape)}.",+ actual_shape=list(points.shape),+ expected_shape=["B", "N", "2 or 3"],+ )infinity_point = lines * torch.tensor([1, 1, 0], dtype=lines.dtype, device=lines.device).view(1, 1, 3)perp: torch.Tensor = torch.linalg.cross(points_h, infinity_point, dim=2)return perp@@ -784,6 +790,14 @@ def get_closest_point_on_epipolar_line(pts1: torch.Tensor, pts2: torch.Tensor, Fraise TypeError(f"Fm type is not a torch.Tensor. Got {type(Fm)}")if (len(Fm.shape) < 3) or not Fm.shape[-2:] == (3, 3):raise ValueError(f"Fm must be a (*, 3, 3) tensor. Got {Fm.shape}")+ # pts2 goes to get_perpendicular, which reads dimension 2; an unbatched pts1 broadcasts against Fm.+ KORNIA_CHECK_SHAPE(pts2, ["B", "N", "D"], "pts2 must have shape (B, N, 2) or (B, N, 3).")+ if pts2.shape[2] not in (2, 3):+ raise ShapeError(+ f"pts2 must have shape (B, N, 2) or (B, N, 3), got {list(pts2.shape)}.",+ actual_shape=list(pts2.shape),+ expected_shape=["B", "N", "2 or 3"],+ )# A caller's autocast region would compute the epipolar lines in half precision and hand them, with the caller's# float32 points, to torch.linalg.cross, which raised on the dtype mismatch. TorchScript has no context managers;# a scripted call keeps the caller's precision.diff --git a/kornia/geometry/epipolar/projection.py b/kornia/geometry/epipolar/projection.pyindex 5b037f167..3f0381fb1 100644--- a/kornia/geometry/epipolar/projection.py+++ b/kornia/geometry/epipolar/projection.py@@ -226,7 +226,7 @@ def KRt_from_projection(P: torch.Tensor, eps: float = 1e-6) -> Tuple[torch.Tensoleft ``3 x 3`` block of its second camera has rank 2, so this decomposition gives no metric camera for it."""- KORNIA_CHECK_SHAPE(P, ["*", "3", "4"])+ KORNIA_CHECK_SHAPE(P, ["B", "3", "4"], "P must have shape (B, 3, 4).")# A caller's autocast region would run the products below in half precision, which torch.linalg.det (CPU) and# qr (MPS) have no kernel for. TorchScript has no context managers; a scripted call keeps the caller's precision.if torch.jit.is_scripting():@@ -334,7 +334,7 @@ def projections_from_fundamental(F_mat: torch.Tensor) -> torch.Tensor:- :func:`KRt_from_projection`: the decomposition of a metric projection matrix."""- KORNIA_CHECK_SHAPE(F_mat, ["*", "3", "3"])+ KORNIA_CHECK_SHAPE(F_mat, ["B", "3", "3"], "F_mat must have shape (B, 3, 3).")R1 = eye_like(3, F_mat) # Bx3x3t1 = vec_like(3, F_mat) # Bx3diff --git a/kornia/geometry/pose.py b/kornia/geometry/pose.pyindex 5a599bbaf..172ec5f2a 100644--- a/kornia/geometry/pose.py+++ b/kornia/geometry/pose.py@@ -48,10 +48,7 @@ def _check_matrix_shape(matrix: torch.Tensor, matrix_type: str = "R") -> None:elif matrix_type == "RT":target_shapes = [[3, 3], [4, 4]]if len(matrix.shape) > 3 or len(matrix.shape) < 2 or list(matrix.shape[-2:]) not in target_shapes:- raise ValueError(- f"{matrix_type} must be either {target_shapes[0]}x{target_shapes[0]} or \- {target_shapes[1]}x{target_shapes[1]}, got {matrix.shape}"- )+ raise ValueError(f"{matrix_type} must be either {target_shapes[0]} or {target_shapes[1]}, got {matrix.shape}")class NamedPose:diff --git a/kornia/geometry/ransac.py b/kornia/geometry/ransac.pyindex 6098ff423..eadf8fc4d 100644--- a/kornia/geometry/ransac.py+++ b/kornia/geometry/ransac.py@@ -956,17 +956,16 @@ class RANSAC(nn.Module):KORNIA_CHECK_SHAPE(kp2, ["N", "2"])if not (kp1.shape[0] == kp2.shape[0]) or (kp1.shape[0] < self.minimal_sample_size):raise ValueError(- "kp1 and kp2 should be equal shape at least"- f" [{self.minimal_sample_size}, 2], got {kp1.shape}, {kp2.shape}"+ f"kp1 and kp2 should be equal shape at least [{self.minimal_sample_size}, 2],"+ f" got {kp1.shape}, {kp2.shape}")if self.model_type == "homography_from_linesegments":KORNIA_CHECK_SHAPE(kp1, ["N", "2", "2"])KORNIA_CHECK_SHAPE(kp2, ["N", "2", "2"])if not (kp1.shape[0] == kp2.shape[0]) or (kp1.shape[0] < self.minimal_sample_size):raise ValueError(- "kp1 and kp2 should be equal shape at least"- f" [{self.minimal_sample_size}, 2, 2], got {kp1.shape},"- f" {kp2.shape}"+ f"kp1 and kp2 should be equal shape at least [{self.minimal_sample_size}, 2, 2],"+ f" got {kp1.shape}, {kp2.shape}")def forward(diff --git a/kornia/geometry/solvers/polynomial_solver.py b/kornia/geometry/solvers/polynomial_solver.pyindex 8100568eb..7c3fab1aa 100644--- a/kornia/geometry/solvers/polynomial_solver.py+++ b/kornia/geometry/solvers/polynomial_solver.py@@ -1387,6 +1387,8 @@ def multiply_deg_one_poly(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:- :func:`multiply_deg_two_one_poly`: the next step, a degree-two polynomial times a degree-one one."""+ KORNIA_CHECK_SHAPE(a, ["B", "4"], "a must have shape (B, 4).")+ KORNIA_CHECK_SHAPE(b, ["B", "4"], "b must have shape (B, 4).")global T_deg1 # noqa: PLW0603if T_deg1.device != a.device or T_deg1.dtype != a.dtype:T_deg1 = T_deg1.to(device=a.device, dtype=a.dtype)diff --git a/tests/geometry/epipolar/test_fundamental.py b/tests/geometry/epipolar/test_fundamental.pyindex 45ff99517..d091ee788 100644--- a/tests/geometry/epipolar/test_fundamental.py+++ b/tests/geometry/epipolar/test_fundamental.py@@ -22,6 +22,7 @@ import torchimport kornia.geometry.epipolar as epiimport kornia.geometry.epipolar.fundamental as fundamental_module+from kornia.core.exceptions import ShapeErrorfrom kornia.core.utils import _torch_svd_castfrom kornia.geometry.conversions import axis_angle_to_rotation_matrix, convert_points_to_homogeneousfrom kornia.geometry.epipolar.fundamental import (@@ -681,6 +682,20 @@ class TestPerpendicular(BaseTester):line = torch.rand(1, 3, 3, device=device, dtype=torch.float64)self.gradcheck(epi.get_perpendicular, (pt, line), requires_grad=(True, False))+ @pytest.mark.parametrize("lines_shape, points_shape", [((5, 3), (5, 2)), ((1, 5, 3), (1, 5, 4))])+ def test_wrong_points_shape_raises_6422(self, lines_shape, points_shape, device, dtype):+ # Unbatched points reached points.shape[2], an IndexError; four coordinates reached a bare AssertionError.+ lines = torch.rand(*lines_shape, device=device, dtype=dtype)+ points = torch.rand(*points_shape, device=device, dtype=dtype)+ with pytest.raises(ShapeError, match=r"points must have shape \(B, N, 2\) or \(B, N, 3\)"):+ epi.get_perpendicular(lines, points)++ def test_unbatched_lines_still_broadcast_6422(self, device, dtype):+ # Only points are read on dimension 2: unbatched lines broadcast against batched points, as before.+ lines = torch.rand(4, 3, device=device, dtype=dtype)+ points = torch.rand(2, 4, 2, device=device, dtype=dtype)+ self.assert_close(epi.get_perpendicular(lines, points), epi.get_perpendicular(lines.expand(2, 4, 3), points))+class TestGetClosestPointOnEpipolarLine(BaseTester):def test_shape(self, device, dtype):@@ -704,6 +719,24 @@ class TestGetClosestPointOnEpipolarLine(BaseTester):Fm = create_random_fundamental_matrix(1, dtype=torch.float64, device=device)self.gradcheck(epi.get_closest_point_on_epipolar_line, (pts1, pts2, Fm), requires_grad=(True, False, False))+ @pytest.mark.parametrize("pts_shape", [(5, 2), (1, 5, 4)])+ def test_wrong_pts2_shape_raises_6422(self, pts_shape, device, dtype):+ # pts2 reached get_perpendicular, where an unbatched one raised an IndexError and one with four+ # coordinates a bare AssertionError.+ pts1 = torch.rand(pts_shape[:-1] + (2,), device=device, dtype=dtype)+ pts2 = torch.rand(pts_shape, device=device, dtype=dtype)+ Fm = create_random_fundamental_matrix(1, device=device, dtype=dtype)+ with pytest.raises(ShapeError, match=r"pts2 must have shape \(B, N, 2\) or \(B, N, 3\)"):+ epi.get_closest_point_on_epipolar_line(pts1, pts2, Fm)++ def test_unbatched_pts1_still_broadcasts_6422(self, device, dtype):+ # An unbatched pts1 broadcasts against Fm in compute_correspond_epilines, as before.+ pts1 = torch.rand(4, 2, device=device, dtype=dtype)+ pts2 = torch.rand(1, 4, 2, device=device, dtype=dtype)+ Fm = create_random_fundamental_matrix(1, device=device, dtype=dtype)+ expected = epi.get_closest_point_on_epipolar_line(pts1[None], pts2, Fm)+ self.assert_close(epi.get_closest_point_on_epipolar_line(pts1, pts2, Fm), expected)+_NO_HALF_EIGH = "find_fundamental calls torch.linalg.eigh, which has no float16/bfloat16 kernel"_HALF_PIXEL_F = (diff --git a/tests/geometry/epipolar/test_projection.py b/tests/geometry/epipolar/test_projection.pyindex b393f83ca..fc3acb4aa 100644--- a/tests/geometry/epipolar/test_projection.py+++ b/tests/geometry/epipolar/test_projection.py@@ -20,6 +20,7 @@ import torchfrom torch.autograd import gradcheckimport kornia.geometry.epipolar as epi+from kornia.core.exceptions import ShapeErrorfrom kornia.geometry.camera import PinholeCamerafrom testing.base import BaseTester@@ -155,6 +156,12 @@ class TestProjectionsFromFundamental(BaseTester):F_mat = torch.rand(1, 3, 3, device=device, dtype=torch.float64, requires_grad=True)assert self.gradcheck(epi.projections_from_fundamental, (F_mat,), raise_exception=True, fast_mode=True)+ def test_unbatched_input_raises_6422(self, device, dtype):+ # An unbatched F_mat passed the shape check and failed later in torch.stack with a RuntimeError.+ F_mat = torch.rand(3, 3, device=device, dtype=dtype)+ with pytest.raises(ShapeError, match=r"F_mat must have shape \(B, 3, 3\)"):+ epi.projections_from_fundamental(F_mat)+class TestKRtFromProjection(BaseTester):def test_smoke(self, device, dtype):@@ -174,6 +181,12 @@ class TestKRtFromProjection(BaseTester):assert R.shape == (B, 3, 3)assert t.shape == (B, 3, 1)+ def test_unbatched_input_raises_6422(self, device, dtype):+ # An unbatched P passed the shape check and failed later with an IndexError.+ P = torch.eye(3, 4, device=device, dtype=dtype)+ with pytest.raises(ShapeError, match=r"P must have shape \(B, 3, 4\)"):+ epi.KRt_from_projection(P)+def test_simple(self, device, dtype):P = torch.tensor([[[308.0, 139.0, 231.0, 84.0], [481.0, 161.0, 358.0, 341.0], [384.0, 387.0, 459.0, 102.0]]],@@ -317,7 +330,7 @@ class TestConventionProjection(BaseTester):two_view = two_view_scene(device, dtype)# P must have exactly one batch dimension.for P_bad in (two_view["P2"][0], two_view["P2"][None]):- with pytest.raises(IndexError):+ with pytest.raises(ShapeError):epi.KRt_from_projection(P_bad)if dtype in (torch.float16, torch.bfloat16):# float16 and bfloat16 raise: the input is not upcast (projections_from_fundamental upcasts).@@ -372,7 +385,7 @@ class TestConventionProjection(BaseTester):assert (_unit(F_reversed) * torch.sign((F_reversed * F).sum()) - _unit(F)).abs().max() > 0.1# F_mat must have exactly one batch dimension.for F_bad in (F[0], F[None]):- with pytest.raises(RuntimeError):+ with pytest.raises(ShapeError):epi.projections_from_fundamental(F_bad)def test_convention_depth_from_point_is_camera_z(self, device, dtype):diff --git a/tests/geometry/solvers/test_polynomial_solver.py b/tests/geometry/solvers/test_polynomial_solver.pyindex 6c6acf627..c7c7a6156 100644--- a/tests/geometry/solvers/test_polynomial_solver.py+++ b/tests/geometry/solvers/test_polynomial_solver.py@@ -592,6 +592,18 @@ class TestMultiplyDegOnePoly(BaseTester):out_poly = solver.multiply_deg_one_poly(a, b)assert out_poly.shape == (B, 10)+ def test_unbatched_input_raises_6422(self, device, dtype):+ # An unbatched polynomial failed in unsqueeze(2) with an IndexError.+ a = torch.rand(4, device=device, dtype=dtype)+ b = torch.rand(4, device=device, dtype=dtype)+ with pytest.raises(ShapeError, match=r"a must have shape \(B, 4\)"):+ solver.multiply_deg_one_poly(a, b)+ with pytest.raises(ShapeError, match=r"b must have shape \(B, 4\)"):+ solver.multiply_deg_one_poly(a[None], b)+ # An extra batch dimension returned products of the wrong coefficients instead of raising.+ with pytest.raises(ShapeError, match=r"a must have shape \(B, 4\)"):+ solver.multiply_deg_one_poly(a.expand(1, 4, 4), b.expand(1, 4, 4))+@pytest.mark.parametrize("a_coeffs, b_coeffs, expected_coeffs",[diff --git a/tests/geometry/test_pose.py b/tests/geometry/test_pose.pyindex 425ad22e3..6dd205782 100644--- a/tests/geometry/test_pose.py+++ b/tests/geometry/test_pose.py@@ -187,6 +187,15 @@ class TestNamedPose(BaseTester):assert b_from_a.translation.dtype == bf16assert isinstance((b_from_a.inverse() * b_from_a).pose, Se2)+ def test_wrong_matrix_shape_message_6422(self, device, dtype):+ # The message used to print [2, 2]x[2, 2] and carry a run of spaces from a backslash continuation.+ with pytest.raises(ValueError) as excinfo:+ NamedPose.from_rt(torch.eye(4, device=device, dtype=dtype), torch.zeros(4, device=device, dtype=dtype))+ assert str(excinfo.value) == "R must be either [2, 2] or [3, 3], got torch.Size([4, 4])"+ with pytest.raises(ValueError) as excinfo:+ NamedPose.from_matrix(torch.eye(5, device=device, dtype=dtype))+ assert str(excinfo.value) == "RT must be either [3, 3] or [4, 4], got torch.Size([5, 5])"+def test_inverse(self, device, dtype):b_from_a = NamedPose(Se3.trans_x(torch.tensor([1.0], device=device, dtype=dtype)), frame_src="frame_a", frame_dst="frame_b"diff --git a/tests/geometry/test_ransac.py b/tests/geometry/test_ransac.pyindex 52c067eef..0fb54d0c0 100644--- a/tests/geometry/test_ransac.py+++ b/tests/geometry/test_ransac.py@@ -1577,6 +1577,16 @@ class TestRANSACValidation(BaseTester):with pytest.raises(ValueError):RANSAC(model).validate_inputs(points, points[:8])+ @pytest.mark.parametrize(("model", "shape"), [("homography", (3, 2)), ("homography_from_linesegments", (3, 2, 2))])+ def test_too_few_correspondences_message_6422(self, device, dtype, model, shape):+ # The message used to contain runs of spaces.+ points = torch.zeros(shape, device=device, dtype=dtype)+ with pytest.raises(ValueError) as excinfo:+ RANSAC(model).validate_inputs(points, points)+ minimal = [4, *shape[1:]]+ size = torch.Size(shape)+ assert str(excinfo.value) == f"kp1 and kp2 should be equal shape at least {minimal}, got {size}, {size}"+@staticmethoddef _projection_case(device, dtype, extra_exact_points):# Every correspondence fits this rank-two F exactly. Its projection onto the essential manifold