Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): preserve unbatched channels in affine transforms (#6065)

A Aswanth Rajbdf184f4495a
diff --git a/changelog.d/6065.fixed.md b/changelog.d/6065.fixed.md
new file mode 100644
index 000000000..d8771cb58
--- /dev/null
+++ b/changelog.d/6065.fixed.md
@@ -0,0 +1 @@
+Fix `rotate`, `Rotate`, `scale`, `Scale`, `rotate3d` and `Affine` treating the channels of an unbatched input as a batch. Multichannel inputs now retain their shape instead of gaining an extra dimension or raising an error.
diff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.py
index d5b31931b..04dde9dae 100644
--- a/kornia/geometry/transform/affwarp.py
+++ b/kornia/geometry/transform/affwarp.py
@@ -285,7 +285,7 @@ def rotate(
- positive ``angle`` rotates counter-clockwise as displayed (y-down image axes)
Args:
- tensor: The image tensor to be warped in shapes of :math:`(B, C, H, W)`.
+ tensor: The image tensor to be warped in shapes of :math:`(C, H, W)` or :math:`(B, C, H, W)`.
angle: The angle through which to rotate. The tensor
must have a shape of (B), where B is batch size.
center: The center through which to rotate. The tensor
@@ -332,7 +332,7 @@ def rotate(
# A singleton angle and center describe one transform shared by all images. Keep
# it singleton through affine so warp_affine can reuse its sampling grid. Trainable
# parameters keep the original reduction order, which matters for half-precision gradients.
- batch = tensor.shape[0]
+ batch = tensor.shape[0] if tensor.dim() == 4 else 1
if (
tensor.dim() == 4
and batch > 0
@@ -378,7 +378,7 @@ def rotate3d(
- align_corners: ``False`` by default (the 2D :func:`rotate` defaults to ``True``)
Args:
- tensor: The image tensor to be warped in shapes of :math:`(B, C, D, H, W)`.
+ tensor: The image tensor to be warped in shapes of :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`.
yaw: The ``rx`` component of the axis-angle vector. The tensor
must have a shape of (B), where B is batch size.
pitch: The ``ry`` component of the axis-angle vector. The tensor
@@ -422,10 +422,11 @@ def rotate3d(
# compute the rotation matrix
# TODO: add broadcasting to get_rotation_matrix2d for center
- yaw = yaw.expand(tensor.shape[0])
- pitch = pitch.expand(tensor.shape[0])
- roll = roll.expand(tensor.shape[0])
- center = center.expand(tensor.shape[0], -1)
+ batch = tensor.shape[0] if tensor.dim() == 5 else 1
+ yaw = yaw.expand(batch)
+ pitch = pitch.expand(batch)
+ roll = roll.expand(batch)
+ center = center.expand(batch, -1)
rotation_matrix: torch.Tensor = _compute_rotation_matrix3d(yaw, pitch, roll, center)
# warp using the affine transform
@@ -500,7 +501,7 @@ def scale(
- ``center`` is ``(x, y)`` in pixels, origin at top-left; defaults to the tensor center
Args:
- tensor: The image tensor to be warped in shapes of :math:`(B, C, H, W)`.
+ tensor: The image tensor to be warped in shapes of :math:`(C, H, W)` or :math:`(B, C, H, W)`.
scale_factor: The scale factor apply. The tensor
must have a shape of (B) or (B, 2), where B is batch size.
If (B), isotropic scaling will perform.
@@ -541,8 +542,9 @@ def scale(
# compute the rotation matrix
# TODO: add broadcasting to get_rotation_matrix2d for center
- center = center.expand(tensor.shape[0], -1)
- scale_factor = scale_factor.expand(tensor.shape[0], 2)
+ batch = tensor.shape[0] if tensor.dim() == 4 else 1
+ center = center.expand(batch, -1)
+ scale_factor = scale_factor.expand(batch, 2)
scaling_matrix: torch.Tensor = _compute_scaling_matrix(scale_factor, center)
# warp using the affine transform
@@ -1051,7 +1053,8 @@ class Affine(nn.Module):
else:
sx, sy = self.shear[..., 0], self.shear[..., 1]
- center = _compute_tensor_center(input).expand(input.size()[0], -1) if self.center is None else self.center
+ batch = input.shape[0] if input.dim() == 4 else 1
+ center = _compute_tensor_center(input).expand(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)
return affine(input, matrix[..., :2, :3], self.mode, self.padding_mode, self.align_corners)
diff --git a/tests/geometry/transform/test_affine.py b/tests/geometry/transform/test_affine.py
index 1d25587b2..36daa85ce 100644
--- a/tests/geometry/transform/test_affine.py
+++ b/tests/geometry/transform/test_affine.py
@@ -566,6 +566,54 @@ class TestRescale(BaseTester):
self.assert_close(out, expected, rtol=0.0, atol=0.0)
+class TestUnbatchedTransforms(BaseTester):
+ @pytest.mark.parametrize("operation", ["rotate", "Rotate", "scale", "Scale", "rotate3d", "Affine"])
+ @pytest.mark.parametrize("channels", [1, 3])
+ @pytest.mark.parametrize("custom_center", [False, True])
+ def test_matches_singleton_batch(self, device, dtype, operation, channels, custom_center):
+ shape = (channels, 4, 5, 7) if operation == "rotate3d" else (channels, 5, 7)
+ image = torch.arange(math.prod(shape), device=device, dtype=dtype).reshape(shape) / math.prod(shape)
+ image.requires_grad_()
+ value = 1.2 if operation in ("scale", "Scale") else 23.0
+ parameter = torch.tensor([value], device=device, dtype=dtype, requires_grad=True)
+ center = None
+ if custom_center:
+ dimensions = 3 if operation == "rotate3d" else 2
+ center = torch.full((1, dimensions), 1.3, device=device, dtype=dtype, requires_grad=True)
+ if operation == "rotate3d":
+
+ def fn(x: torch.Tensor) -> torch.Tensor:
+ return kornia.geometry.transform.rotate3d(x, parameter, parameter, parameter, center)
+
+ elif operation in ("scale", "Scale"):
+ fn = kornia.geometry.transform.Scale(parameter, center)
+ if operation == "scale":
+
+ def fn(x: torch.Tensor) -> torch.Tensor:
+ return kornia.geometry.transform.scale(x, parameter, center)
+
+ elif operation == "Affine":
+ fn = kornia.geometry.transform.Affine(angle=parameter, center=center)
+
+ else:
+ fn = kornia.geometry.transform.Rotate(parameter, center)
+ if operation == "rotate":
+
+ def fn(x: torch.Tensor) -> torch.Tensor:
+ return kornia.geometry.transform.rotate(x, parameter, center)
+
+ actual = fn(image)
+ expected = fn(image.unsqueeze(0)).squeeze(0)
+
+ assert actual.shape == image.shape
+ self.assert_close(actual, expected)
+ inputs = (image, parameter) if center is None else (image, parameter, center)
+ actual_grads = torch.autograd.grad(actual.sum(), inputs)
+ expected_grads = torch.autograd.grad(expected.sum(), inputs)
+ for actual_grad, expected_grad in zip(actual_grads, expected_grads):
+ self.assert_close(actual_grad, expected_grad)
+
+
class TestRotate(BaseTester):
@pytest.mark.parametrize("align_corners", [False, True])
@pytest.mark.parametrize("center_shape", [None, (2,), (1, 2), (3, 2)])