Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix: resolve broadcasting error in affine transform for multi-channel masks (#3388)

Nilay Srivastava8f4561cb8bb7
diff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.py
index 56dae28c1..19d774871 100644
--- a/kornia/geometry/transform/affwarp.py
+++ b/kornia/geometry/transform/affwarp.py
@@ -166,12 +166,15 @@ def affine(
"""
# warping needs data in the shape of BCHW
- is_unbatched: bool = tensor.ndimension() == 3
+ is_unbatched: bool = tensor.dim() == 3
if is_unbatched:
tensor = torch.unsqueeze(tensor, dim=0)
# we enforce broadcasting since by default grid_sample it does not
# give support for that
+ if tensor.shape[0] == 1 and matrix.shape[0] != 1:
+ tensor = tensor.expand(matrix.shape[0], tensor.shape[1], tensor.shape[2], tensor.shape[3])
+
matrix = matrix.expand(tensor.shape[0], -1, -1)
# warp the input tensor
@@ -217,7 +220,7 @@ def affine3d(
"""
# warping needs data in the shape of BCDHW
- is_unbatched: bool = tensor.ndimension() == 4
+ is_unbatched: bool = tensor.dim() == 4
if is_unbatched:
tensor = torch.unsqueeze(tensor, dim=0)
diff --git a/tests/geometry/transform/test_affine.py b/tests/geometry/transform/test_affine.py
index a4891a869..9623801aa 100644
--- a/tests/geometry/transform/test_affine.py
+++ b/tests/geometry/transform/test_affine.py
@@ -715,6 +715,21 @@ class TestAffine2d(BaseTester):
matrix_kornia = matrix_kornia.inverse()[0, :2].detach().cpu()
self.assert_close(matrix_kornia, matrix_expected, atol=1e-4, rtol=1e-4)
+ def test_broadcasting_issue_3176(self, device, dtype):
+ # Issue 3176: RandomRotation with multi-channel masks caused crash
+ # Scenario: Tensor is (B=1, C, H, W) but Matrix is (B=8, 2, 3)
+ # This implies applying N different transformations to a single image
+ B_mat, B_ten = 8, 1
+ C, H, W = 3, 64, 64
+
+ input_tensor = torch.rand(B_ten, C, H, W, device=device, dtype=dtype)
+
+ matrix = torch.rand(B_mat, 2, 3, device=device, dtype=dtype)
+
+ output = kornia.geometry.transform.affine(input_tensor, matrix, mode="bilinear")
+
+ assert output.shape == (B_mat, C, H, W)
+
class TestGetAffineMatrix(BaseTester):
def test_smoke(self, device, dtype):