Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Reject non-floating input to convert_affinematrix_to_homography and ARKitQTVecs_to_ColmapQTVecs (#6411)

Tejas Malhotraa5c567df09e2
diff --git a/changelog.d/6411.fixed.md b/changelog.d/6411.fixed.md
new file mode 100644
index 000000000..a8d35a44d
--- /dev/null
+++ b/changelog.d/6411.fixed.md
@@ -0,0 +1 @@
+`convert_affinematrix_to_homography` and `convert_affinematrix_to_homography3d` now reject integer and bool input up front with a `ValueError` naming the dtype, as `Rt_to_matrix4x4` does; before, it failed with a bare `RuntimeError` from the in-place `+= 1.0` on the padded homography. `ARKitQTVecs_to_ColmapQTVecs` now rejects an integer, bool or complex `qvec` and a complex `tvec` with a `TypeCheckError` naming the argument, as `ColmapQTVecs_to_ARKitQTVecs` does; before, they failed inside `linalg.vector_norm` or a comparison. An integer `tvec` with a floating `qvec` still promotes and returns the floating result.
diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.py
index c36943382..10befcd4e 100644
--- a/kornia/geometry/conversions.py
+++ b/kornia/geometry/conversions.py
@@ -403,6 +403,8 @@ def convert_points_to_homogeneous(points: torch.Tensor) -> torch.Tensor:
def _convert_affinematrix_to_homography_impl(A: torch.Tensor) -> torch.Tensor:
+ if not A.is_floating_point() and not A.is_complex():
+ raise ValueError(f"Input A must be a floating point or complex tensor. Got {A.dtype}.")
H: torch.Tensor = F.pad(A, [0, 0, 0, 1], "constant", value=0.0)
H[..., -1, -1] += 1.0
return H
@@ -420,6 +422,10 @@ def convert_affinematrix_to_homography(A: torch.Tensor) -> torch.Tensor:
- the rank is enforced to be exactly 3, so batching is **mandatory**: an
unbatched ``(2, 3)`` matrix raises ``ValueError``
+ Note:
+ ``A`` must be a floating point or complex tensor; an integer or
+ boolean one raises ``ValueError`` naming its dtype.
+
Args:
A: the affine matrix with shape ``(B,2,3)``.
@@ -461,6 +467,10 @@ def convert_affinematrix_to_homography3d(A: torch.Tensor) -> torch.Tensor:
- the rank is enforced to be exactly 3, as in the 2D function: an
unbatched ``(3, 4)`` matrix raises ``ValueError``
+ Note:
+ ``A`` must be a floating point or complex tensor; an integer or
+ boolean one raises ``ValueError`` naming its dtype.
+
Args:
A: the affine matrix with shape ``(B,3,4)``.
@@ -3574,6 +3584,10 @@ def ARKitQTVecs_to_ColmapQTVecs(qvec: torch.Tensor, tvec: torch.Tensor) -> tuple
``torch.zeros(1, 4)`` with ``t = (1, 1, 1)`` returns
``q = [0., 1., 0., 0.]``, ``t = (-1, 1, 1)``, the same answer as the
identity input
+ - ``qvec`` must be real floating point: an integer, bool or complex
+ ``qvec`` raises ``TypeCheckError`` (also a ``TypeError``) naming it,
+ so cast it first. An integer or bool ``tvec`` promotes to ``qvec``'s
+ dtype; a complex ``tvec`` raises ``TypeCheckError``
Args:
qvec: ARKit rotation quaternion ``(B, 4)``, [w, x, y, z] format.
@@ -3598,6 +3612,13 @@ def ARKitQTVecs_to_ColmapQTVecs(qvec: torch.Tensor, tvec: torch.Tensor) -> tuple
"""
# ToDo: integrate QuaterniaonAPI
+ if isinstance(qvec, torch.Tensor) and not qvec.is_floating_point(): # complex is not floating point
+ raise TypeCheckError(
+ f"Input qvec must be a real floating point tensor. Got dtype {qvec.dtype}.", actual_type=qvec.dtype
+ )
+ # An integer tvec promotes against the floating rotation and gives the float result; only complex is rejected.
+ if isinstance(tvec, torch.Tensor) and tvec.is_complex():
+ raise TypeCheckError(f"Input tvec must be a real tensor. Got dtype {tvec.dtype}.", actual_type=tvec.dtype)
Rcg = quaternion_to_rotation_matrix(qvec)
Rcv, Tcv = camtoworld_graphics_to_vision_Rt(Rcg, tvec)
R_colmap, t_colmap = camtoworld_to_worldtocam_Rt(Rcv, Tcv)
diff --git a/tests/geometry/test_conversions.py b/tests/geometry/test_conversions.py
index 93525362e..61db4c1a0 100644
--- a/tests/geometry/test_conversions.py
+++ b/tests/geometry/test_conversions.py
@@ -2806,6 +2806,25 @@ class TestConvertAtoH(BaseTester):
)
self.assert_close(out, expected)
+ @pytest.mark.parametrize(
+ "op,shape",
+ [
+ (kornia.geometry.conversions.convert_affinematrix_to_homography, (1, 2, 3)),
+ (kornia.geometry.conversions.convert_affinematrix_to_homography3d, (1, 3, 4)),
+ ],
+ )
+ @pytest.mark.parametrize("int_dtype", [torch.int64, torch.int32, torch.bool])
+ def test_exception_rejects_non_floating_input(self, op, shape, int_dtype, device):
+ # Integer or bool input used to surface as a bare torch RuntimeError from the in-place
+ # "+= 1.0" on the padded homography ("result type Float can't be cast to the desired
+ # output type Long"), naming no kornia argument. Now rejected up front by name.
+ # Snippet used to generate the old behaviour (torch only):
+ # convert_affinematrix_to_homography(torch.ones(1, 2, 3, dtype=torch.int64))
+ # -> RuntimeError: result type Float can't be cast to the desired output type Long
+ A = torch.ones(shape, device=device, dtype=int_dtype)
+ with pytest.raises(ValueError, match=rf"floating point or complex.*{int_dtype}"):
+ op(A)
+
class TestConvertPointsFromHomogeneous(BaseTester):
@pytest.mark.parametrize("batch_shape", [(2, 3), (1, 2, 3), (2, 3, 3), (5, 5, 3)])
@@ -5557,6 +5576,43 @@ class TestCARKitToColmap(BaseTester):
with pytest.raises(TypeCheckError, match=rf"{which}.*real floating point.*{complex_dtype}"):
ColmapQTVecs_to_ARKitQTVecs(qvec, tvec)
+ @pytest.mark.parametrize("int_dtype", [torch.int64, torch.int32, torch.bool])
+ def test_exception_arkit_to_colmap_rejects_non_floating_qvec(self, device, int_dtype):
+ # The forward conversion had no dtype guard and an integer qvec surfaced a bare torch
+ # RuntimeError from linalg.vector_norm instead of naming the argument.
+ # Snippet used to generate the old behaviour (torch only):
+ # ARKitQTVecs_to_ColmapQTVecs(torch.tensor([[0, 1, 0, 1]]), torch.ones(1, 3, 1, dtype=torch.int64))
+ # -> RuntimeError: linalg.vector_norm: Expected a floating point or complex tensor as input. Got Long
+ qvec = torch.tensor([[1, 0, 0, 0]], device=device, dtype=int_dtype)
+ tvec = torch.ones(1, 3, 1, device=device, dtype=torch.float32)
+ with pytest.raises(TypeCheckError, match=rf"qvec.*floating point.*{int_dtype}"):
+ ARKitQTVecs_to_ColmapQTVecs(qvec, tvec)
+
+ @pytest.mark.parametrize("int_dtype", [torch.int64, torch.int32, torch.bool])
+ def test_arkit_to_colmap_integer_tvec_promotes(self, device, dtype, int_dtype):
+ # An integer tvec with a floating qvec has always promoted to qvec's dtype and given the
+ # float result; the qvec guard must not reject it.
+ qvec = torch.tensor([[0.5, 0.5, 0.5, 0.5], [0.0, 1.0, 0.0, 1.0]], device=device, dtype=dtype)
+ tvec = torch.tensor([[[1], [0], [3]], [[0], [1], [1]]], device=device, dtype=int_dtype)
+ q_int, t_int = ARKitQTVecs_to_ColmapQTVecs(qvec, tvec)
+ q_ref, t_ref = ARKitQTVecs_to_ColmapQTVecs(qvec, tvec.to(dtype))
+ assert t_int.dtype == dtype
+ self.assert_close(q_int, q_ref, atol=0.0, rtol=0.0)
+ self.assert_close(t_int, t_ref, atol=0.0, rtol=0.0)
+
+ @pytest.mark.parametrize("complex_dtype", [torch.complex64, torch.complex128])
+ @pytest.mark.parametrize("which", ["qvec", "tvec"])
+ def test_exception_arkit_to_colmap_rejects_complex_inputs(self, complex_dtype, which):
+ # CPU tensors: the guard runs before any arithmetic and MPS has no complex128.
+ qvec = torch.tensor([[1.0, 0.0, 0.0, 0.0]])
+ tvec = torch.ones(1, 3, 1)
+ if which == "qvec":
+ qvec = qvec.to(complex_dtype)
+ else:
+ tvec = tvec.to(complex_dtype)
+ with pytest.raises(TypeCheckError, match=rf"{which}.*real.*{complex_dtype}"):
+ ARKitQTVecs_to_ColmapQTVecs(qvec, tvec)
+
def test_dynamo_colmap_to_arkit(self, device, dtype, torch_optimizer):
qvec = torch.tensor([[0.7071, 0.0, 0.7071, 0.0], [1.0, 0.0, 0.0, 0.0]], device=device, dtype=dtype)
tvec = torch.tensor([[[1.0], [2.0], [3.0]], [[-1.0], [0.5], [2.0]]], device=device, dtype=dtype)