Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/).
### Fixed
* `Quicknat` no longer depends on the unpublished `squeeze_and_excitation` package for `se_block="SSE"` and `"CSSE"`. Checkpoints saved with that package for these two options use different `state_dict` keys and will not load strictly. (#9276)
* `ChannelSELayer` raises `ValueError` instead of `ZeroDivisionError` when `r=0`.
* `Spacing` and `Spacingd` with `recompute_affine=True` compose the recomputed scaling with the input affine again, so the output keeps the input spacing, orientation and origin. Since 1.2.0 the output affine was replaced by the bare scaling matrix.

## [1.6.2] - 2026-11-18
### Addressed Security Advisories
Expand Down
2 changes: 1 addition & 1 deletion monai/transforms/spatial/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -543,7 +543,7 @@ def __call__(
raise NotImplementedError("recompute_affine is not supported with lazy evaluation.")
ac = align_corners if align_corners is not None else self.sp_resample.align_corners
a = scale_affine(original_spatial_shape, actual_shape, align_corners=ac)
data_array.affine = convert_to_dst_type(a, affine_)[0] # type: ignore
data_array.affine = convert_to_dst_type(affine_ @ a, affine_)[0] # type: ignore
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
return data_array

def inverse(self, data: torch.Tensor) -> torch.Tensor:
Expand Down
37 changes: 37 additions & 0 deletions tests/transforms/test_spacing.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,8 @@ def _template_5_expected_output(device: torch.device) -> torch.Tensor:
for params in dict_product(d=TEST_DEVICES, recompute=[False, True], align=[False, True], scale_extent=[False, True])
]

TEST_RECOMPUTE = [[*params["d"], params["align"]] for params in dict_product(d=TEST_DEVICES, align=[False, True])]


@skip_if_quick
class TestSpacingCase(unittest.TestCase):
Expand Down Expand Up @@ -326,6 +328,41 @@ def test_inverse_mn_mx(self, device, recompute, align, scale_extent):
self.assertEqual(img_out.shape, img_t.shape)
self.assertLess(((affine - img_out.affine) ** 2).sum() ** 0.5, 5e-2)

@parameterized.expand(TEST_RECOMPUTE)
def test_recompute_affine_keeps_geometry(self, device, align):
# non-unit spacing, a flipped axis and a non-zero origin
affine = torch.tensor(
[[-1.2, 0, 0, 90], [0, 0.9, 0, -120], [0, 0, 1.5, 30], [0, 0, 0, 1]], dtype=torch.float64, device="cpu"
)
in_shape = (32, 36, 28)
# smooth, asymmetric image so that a misplaced or flipped grid shows up in the voxel values
grid = torch.meshgrid(*[torch.linspace(0, 1, s) for s in in_shape], indexing="ij")
img_t = (2 * grid[0] + torch.cos(2 * grid[1]) + grid[2] ** 2)[None].to(device)
img = MetaTensor(img_t, affine=affine, meta={"fname": "somewhere"})

expected = Spacing(pixdim=1.0, align_corners=align)(img)
tr = Spacing(pixdim=1.0, recompute_affine=True, align_corners=align)
res = tr(img)
out_shape = np.asarray(res.shape[1:])
self.assertEqual(tuple(out_shape), tuple(expected.shape[1:]))

# pixdim follows from the input spacing and the actual shape change
in_pixdim = np.array([1.2, 0.9, 1.5])
if align:
expected_pixdim = in_pixdim * (np.asarray(in_shape) - 1) / (out_shape - 1)
else:
expected_pixdim = in_pixdim * np.asarray(in_shape) / out_shape
assert_allclose(res.pixdim, expected_pixdim, type_test=False, rtol=1e-4)
# orientation and origin stay close to the analytic output affine (only quantization differs)
assert_allclose(res.affine, expected.affine, type_test=False, atol=0.3)
assert_allclose(np.sign(np.diag(res.affine.cpu().numpy())), [-1, 1, 1, 1], type_test=False)

# inverse brings the voxel values back onto the input grid
inv = tr.inverse(res)
self.assertEqual(inv.shape, img_t.shape)
assert_allclose(inv.affine, affine, type_test=False, atol=1e-4)
assert_allclose(inv[0, 3:-3, 3:-3, 3:-3], img_t[0, 3:-3, 3:-3, 3:-3], type_test=False, atol=0.1)

def test_property_no_change(self):
affine = torch.tensor(
[[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], dtype=torch.float32, device="cpu"
Expand Down