diff --git a/monai/transforms/spatial/array.py b/monai/transforms/spatial/array.py index d37e69650c..6d95acb3d1 100644 --- a/monai/transforms/spatial/array.py +++ b/monai/transforms/spatial/array.py @@ -2523,6 +2523,8 @@ def __call__( img = convert_to_tensor(img, track_meta=get_track_meta()) if lazy_: if self._do_transform: + if grid is None: + self.rand_affine_grid(sp_size, randomize=randomize, lazy=True) affine = self.rand_affine_grid.get_transformation_matrix() else: affine = convert_to_dst_type(torch.eye(len(sp_size) + 1), img, dtype=self.rand_affine_grid.dtype)[0] diff --git a/monai/transforms/spatial/dictionary.py b/monai/transforms/spatial/dictionary.py index 79742f0582..6f53b10fc2 100644 --- a/monai/transforms/spatial/dictionary.py +++ b/monai/transforms/spatial/dictionary.py @@ -1141,6 +1141,7 @@ def __call__( grid = self.rand_affine.get_identity_grid(sp_size, lazy=lazy_) if self._do_transform: # add some random factors grid = self.rand_affine.rand_affine_grid(sp_size, grid=grid, lazy=lazy_) + grid = 0 if grid is None else grid # always provide a grid to self.rand_affine for key, mode, padding_mode in self.key_iterator(d, self.mode, self.padding_mode): # do the transform diff --git a/tests/test_rand_affine.py b/tests/test_rand_affine.py index 83aafe9773..915b14bf51 100644 --- a/tests/test_rand_affine.py +++ b/tests/test_rand_affine.py @@ -145,6 +145,7 @@ def test_rand_affine(self, input_param, input_data, expected_val): g = RandAffine(**input_param) g.set_random_state(123) result = g(**input_data) + g.rand_affine_grid.affine = torch.eye(4, dtype=torch.float64) # reset affine test_resampler_lazy(g, result, input_param, input_data, seed=123) if input_param.get("cache_grid", False): self.assertTrue(g._cached_grid is not None)