π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): reject integer transform points inputs (#6152)
Devulapalli Naga Sri Vaishnavid233ddb12bfa
diff --git a/changelog.d/6152.fixed.md b/changelog.d/6152.fixed.mdnew file mode 100644index 000000000..b59acfcc1--- /dev/null+++ b/changelog.d/6152.fixed.md@@ -0,0 +1 @@+`transform_points` no longer truncates integer operands. Integer points, such as pixel indices from `torch.nonzero`, used to come back in their integer dtype, truncated whenever the transformed coordinate was fractional; they now return in the floating dtype of the transform, or in the default floating dtype when the transform is integer too. An integer transform used to truncate floating points before the product; it is now applied in the points' dtype. `transform_bbox` and `Keypoints.transform_keypoints` change with it.diff --git a/kornia/geometry/linalg.py b/kornia/geometry/linalg.pyindex 84b348e12..193de84f2 100644--- a/kornia/geometry/linalg.py+++ b/kornia/geometry/linalg.py@@ -223,6 +223,12 @@ def relative_transformation(trans_01: torch.Tensor, trans_02: torch.Tensor) -> tdef transform_points(trans_01: torch.Tensor, points_1: torch.Tensor) -> torch.Tensor:r"""Apply transformations to a set of points.+ Convention:+ Integer and boolean operands are promoted, not rejected, because a transform moves integer coordinates+ (pixel indices from ``torch.nonzero`` or ``argmax``) to fractional ones. Integer points return in the+ floating dtype of ``trans_01``, or in the default floating dtype when both operands are integer, and an integer+ ``trans_01`` is applied in the dtype of the result. Floating points keep their dtype.+Args:trans_01: tensor for transformations of shape:math:`(D+1, D+1)` or :math:`(B, D+1, D+1)`.@@ -242,6 +248,15 @@ def transform_points(trans_01: torch.Tensor, points_1: torch.Tensor) -> torch.Te"""KORNIA_CHECK_IS_TENSOR(trans_01)KORNIA_CHECK_IS_TENSOR(points_1)+ # Integer or boolean operands cannot hold the fractional coordinates a transform produces, so the result takes+ # the points' floating dtype, else the transform's, else the default one (read off an empty tensor: TorchScript+ # has no ``torch.get_default_dtype()``).+ out_dtype = points_1.dtype+ if not (points_1.is_floating_point() or points_1.is_complex()):+ floating_trans = trans_01.is_floating_point() or trans_01.is_complex()+ out_dtype = trans_01.dtype if floating_trans else torch.empty(0, device=points_1.device).dtype+ if not (trans_01.is_floating_point() or trans_01.is_complex()):+ trans_01 = trans_01.to(out_dtype)if trans_01.ndim == 2:trans_01 = trans_01.unsqueeze(0)# A 2-D ``points_1`` is (N, D) with no batch axis, so N equal to a transform batch B > 1 is a@@ -258,7 +273,7 @@ def transform_points(trans_01: torch.Tensor, points_1: torch.Tensor) -> torch.Te# yields the same empty set. Return early β the reshape below cannot infer ``-1`` from a# 0-element tensor, so this also avoids a spurious crash on valid empty inputs.if points_1.shape[-2] == 0:- return points_1+ return points_1.to(out_dtype)# We reshape to BxNxD in case we get more dimensions, e.g., MxBxNxDshape_inp = list(points_1.shape)@@ -274,8 +289,7 @@ def transform_points(trans_01: torch.Tensor, points_1: torch.Tensor) -> torch.Tepoints_1_h = convert_points_to_homogeneous(points_1) # BxNxD+1# `torch.bmm` requires both operands to share a scalar type. Callers may pass coordinate# tensors in a different dtype than the transform matrix (e.g. fp32 bbox + fp16 image), so- # harmonise at the bmm site and restore the caller's coordinate dtype on return.- points_dtype = points_1_h.dtype+ # harmonise at the bmm site and return in ``out_dtype``.# transform coordinatespoints_0_h = torch.bmm(points_1_h.to(trans_01.dtype), trans_01.permute(0, 2, 1))# to euclidean@@ -284,7 +298,7 @@ def transform_points(trans_01: torch.Tensor, points_1: torch.Tensor) -> torch.Teshape_inp[-2] = points_0.shape[-2]shape_inp[-1] = points_0.shape[-1]points_0 = points_0.reshape(shape_inp)- return points_0.to(points_dtype)+ return points_0.to(out_dtype)def _nonzero(x: torch.Tensor) -> torch.Tensor:diff --git a/tests/geometry/test_linalg.py b/tests/geometry/test_linalg.pyindex d8d134f31..227a11ec0 100644--- a/tests/geometry/test_linalg.py+++ b/tests/geometry/test_linalg.py@@ -59,6 +59,48 @@ class TestTransformPoints(BaseTester):with pytest.raises(ValueError, match=r"differ by one unit\. Got torch\.Size\(.*\) and torch\.Size\(\[5, 2\]\)"):kgl.transform_points(transform, points)+ @pytest.mark.parametrize("index_dtype", [torch.int64, torch.int32, torch.uint8, torch.bool])+ def test_integer_points_take_the_transform_dtype(self, index_dtype, device, dtype):+ # Integer pixel indices (``torch.nonzero``, ``argmax``) move to fractional coordinates: the result takes the+ # transform's floating dtype instead of being truncated back to the indices' dtype, also when it is empty.+ shift = torch.tensor([[1.0, 0.0, 0.5], [0.0, 1.0, 1.5], [0.0, 0.0, 1.0]], device=device, dtype=dtype)+ pixels = torch.tensor([[[0, 0], [1, 1], [0, 1]]], device=device).to(index_dtype)+ expected = torch.tensor([[[0.5, 1.5], [1.5, 2.5], [0.5, 2.5]]], device=device, dtype=dtype)++ result = kgl.transform_points(shift, pixels)++ assert result.dtype == dtype+ self.assert_close(result, expected)+ assert kgl.transform_points(shift, pixels[:, :0]).dtype == dtype++ def test_integer_transform_does_not_truncate_the_points(self, device, dtype):+ # Python integer literals build an int64 matrix; it is applied in the points' dtype.+ translate = torch.tensor([[1, 0, 2], [0, 1, 1], [0, 0, 1]], device=device)+ points = torch.tensor([[[0.5, 1.5], [2.25, 2.75]]], device=device, dtype=dtype)+ expected = torch.tensor([[[2.5, 2.5], [4.25, 3.75]]], device=device, dtype=dtype)++ result = kgl.transform_points(translate, points)++ assert result.dtype == dtype+ self.assert_close(result, expected)++ @pytest.mark.parametrize("default_dtype", [torch.float32, torch.float64])+ def test_integer_operands_take_the_default_dtype(self, default_dtype, device):+ if device.type == "mps" and default_dtype == torch.float64:+ pytest.skip("MPS has no float64")+ # w = 2 halves the coordinates, which an integer result would truncate.+ halve = torch.tensor([[1, 0, 0], [0, 1, 0], [0, 0, 2]], device=device)+ pixels = torch.tensor([[[3, 4], [1, 7]]], device=device)+ old_default = torch.get_default_dtype()+ try:+ torch.set_default_dtype(default_dtype)+ result = kgl.transform_points(halve, pixels)+ finally:+ torch.set_default_dtype(old_default)++ assert result.dtype == default_dtype+ self.assert_close(result, pixels.to(default_dtype) / 2)+@pytest.mark.parametrize("num_points", [2, 3])def test_unbatched_points_with_transform_batch_raise(self, num_points, device, dtype):# (N, D) points have no batch axis, so N == B must hit the batch check like N != B does