π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): build the default center of rotate, scale and Affine in the parameters' dtype (#6546)
Saksham Sharma23e2a61d5dcc
diff --git a/changelog.d/6546.fixed.md b/changelog.d/6546.fixed.mdnew file mode 100644index 000000000..55dd95315--- /dev/null+++ b/changelog.d/6546.fixed.md@@ -0,0 +1 @@+`kornia.geometry.transform.rotate` and `scale`, and the `Affine`, `Rotate` and `Scale` modules, build their default center in the dtype of the angle or scale factor, so leaving `center` out gives the same result as passing the image center in that dtype. With parameters in a narrower floating dtype than the image, such as float32 parameters and a float64 image, they used to raise `ValueError` ("Inputs must have same dtype") unless `center` was passed; they now warp in the image dtype, as `warp_affine` does. Parameters that `warp_affine` rejects for the image, such as float64 parameters with a float32 image, still raise, now with its `RuntimeError`, as with an explicit center.diff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.pyindex 3a8070a57..15ff6606a 100644--- a/kornia/geometry/transform/affwarp.py+++ b/kornia/geometry/transform/affwarp.py@@ -86,18 +86,23 @@ def _register_transform_tensor(module: nn.Module, name: str, value: Optional[tor# utilities to compute affine matrices-def _compute_tensor_center(tensor: torch.Tensor) -> torch.Tensor:- """Compute the center of tensor plane for (H, W), (C, H, W) and (B, C, H, W)."""+def _compute_tensor_center(tensor: torch.Tensor, like: Optional[torch.Tensor] = None) -> torch.Tensor:+ """Compute the center of tensor plane for (H, W), (C, H, W) and (B, C, H, W).++ The center is in the dtype of ``like`` when it is a floating-point tensor, the parameter it is combined with, so+ that the default center gives the same matrix as one passed explicitly (#6545); otherwise in ``tensor``'s.+ """if not 2 <= len(tensor.shape) <= 4:raise AssertionError(f"Must be a 3D tensor as HW, CHW and BCHW. Got {tensor.shape}.")height, width = tensor.shape[-2:]center_x: float = float(width - 1) / 2center_y: float = float(height - 1) / 2+ dtype = like.dtype if like is not None and like.is_floating_point() else tensor.dtype# Filled on the device in eager mode: ``torch.tensor(..., device=cuda)`` copies from the host and waits for queued# kernels. TorchScript, which cannot compile ``_device_literal``, keeps the host literal.if torch.jit.is_scripting():- return torch.tensor([center_x, center_y], device=tensor.device, dtype=tensor.dtype)- return _device_literal([center_x, center_y], device=tensor.device, dtype=tensor.dtype)+ return torch.tensor([center_x, center_y], device=tensor.device, dtype=dtype)+ return _device_literal([center_x, center_y], device=tensor.device, dtype=dtype)def _compute_tensor_center3d(tensor: torch.Tensor) -> torch.Tensor:@@ -403,7 +408,7 @@ def rotate(# compute the rotation centerif center is None:- center = _compute_tensor_center(tensor)+ center = _compute_tensor_center(tensor, angle)# compute the rotation matrix# TODO: add broadcasting to get_rotation_matrix2d for center@@ -661,7 +666,7 @@ def scale(# compute the tensor centerif center is None:- center = _compute_tensor_center(tensor)+ center = _compute_tensor_center(tensor, scale_factor)# compute the rotation matrix# TODO: add broadcasting to get_rotation_matrix2d for center@@ -1276,7 +1281,9 @@ class Affine(nn.Module):params_batch = self.angle.shape[0]# The default center is the same for every image, so it takes the parameters' batch: a batch-1 parameter set# then warps every image, and B parameter sets warp one image, as with an explicit center.- center = _compute_tensor_center(input).expand(params_batch, -1) if self.center is None else self.center+ center = (+ _compute_tensor_center(input, self.angle).expand(params_batch, -1) if self.center is None else self.center+ )matrix = get_affine_matrix2d(self.translation, center, self.scale_factor, -self.angle, sx=sx, sy=sy)if params_batch not in (batch, 1) and batch != 1:diff --git a/tests/geometry/transform/test_affine.py b/tests/geometry/transform/test_affine.pyindex b828b009b..b57a69ebb 100644--- a/tests/geometry/transform/test_affine.py+++ b/tests/geometry/transform/test_affine.py@@ -1430,6 +1430,28 @@ class TestAffine2d(BaseTester):assert out[0, 0, 0, 9] == 0.0+ @pytest.mark.parametrize("op", ["rotate", "scale", "Affine"])+ def test_default_center_takes_parameter_dtype_6545(self, device, op):+ # float32 parameters with a float64 image sample in float64, as warp_affine documents. The default center was+ # built in the image dtype and failed the matrix's same-dtype check, while an explicit center worked.+ if device.type == "mps":+ pytest.skip("MPS has no float64")+ image = torch.rand(2, 3, 6, 7, device=device, dtype=torch.float64)+ angle = torch.tensor([30.0, -15.0], device=device, dtype=torch.float32)+ factor = torch.tensor([[1.5, 0.75], [0.5, 2.0]], device=device, dtype=torch.float32)+ center = torch.tensor([[3.0, 2.5]], device=device, dtype=torch.float32).expand(2, -1)+ if op == "rotate":+ out = kornia.geometry.transform.rotate(image, angle)+ expected = kornia.geometry.transform.rotate(image, angle, center)+ elif op == "scale":+ out = kornia.geometry.transform.scale(image, factor)+ expected = kornia.geometry.transform.scale(image, factor, center)+ else:+ out = kornia.geometry.transform.Affine(angle)(image)+ expected = kornia.geometry.transform.Affine(angle, center=center)(image)+ assert out.dtype == torch.float64+ self.assert_close(out, expected, atol=0, rtol=0)+class TestGetAffineMatrix(BaseTester):def test_smoke(self, device, dtype):