Skip to content

Commit e28a2c0

Browse files
fix(transforms): resolve TypeError when spatial_size is None (#9068) (#9080)
### Description Fixes #9068. This PR resolves a `TypeError` in `spatial_resample` when `spatial_size=None` (or contains `None` entries). The predicate now safely guards against `NoneType` comparisons when evaluating target spatial dimensions. ### Key Changes - Updated `spatial_size` evaluation in `monai/transforms/spatial/functional.py` to be `None`-safe. - Added dedicated CPU unit test cases in `tests/transforms/test_spatial_resample.py` testing explicit `spatial_size=None` and partial `None` dimensions. - Aliased the imported lazy-resampler helper so pytest does not collect it as a standalone fixture-based test. ### Types of changes - [x] Bug fix (non-breaking change which fixes an issue) - [x] Unit tests added/updated --------- Signed-off-by: Luchang Jiang <auroral.sunflower@gmail.com> Co-authored-by: Eric Kerfoot <17726042+ericspod@users.noreply.github.com>
1 parent 868041a commit e28a2c0

3 files changed

Lines changed: 36 additions & 8 deletions

File tree

‎monai/data/image_writer.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -266,12 +266,13 @@ def resample_if_needed(
266266
The output data type of this method is always ``np.float32``.
267267
"""
268268
orig_type = type(data_array)
269-
data_array = convert_to_tensor(data_array, track_meta=True)
269+
# Add the channel dimension before setting the affine so spatial_ndim is inferred correctly.
270+
data_array = convert_to_tensor(data_array, track_meta=True)[None]
270271
if affine is not None:
271272
data_array.affine = convert_to_tensor(affine, track_meta=False) # type: ignore
272273
resampler = SpatialResample(mode=mode, padding_mode=padding_mode, align_corners=align_corners, dtype=dtype)
273274
output_array = resampler(
274-
data_array[None], dst_affine=target_affine, spatial_size=output_spatial_shape # type: ignore
275+
data_array, dst_affine=target_affine, spatial_size=output_spatial_shape # type: ignore
275276
)
276277
# convert back at the end
277278
if isinstance(output_array, MetaTensor):

‎monai/transforms/spatial/functional.py‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,9 @@ def spatial_resample(
117117
Args:
118118
img: data to be resampled, assuming `img` is channel-first.
119119
dst_affine: target affine matrix, if None, use the input affine matrix, effectively no resampling.
120-
spatial_size: output spatial size, if the component is ``-1``, use the corresponding input spatial size.
120+
spatial_size: output spatial size. Components set to ``-1`` or ``None`` use the corresponding input
121+
spatial dimension. If the entire value is ``None``, the output size is computed automatically when
122+
possible, otherwise the input spatial shape is used.
121123
mode: {``"bilinear"``, ``"nearest"``} or spline interpolation order 0-5 (integers).
122124
Interpolation mode to calculate output values.
123125
See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html
@@ -135,6 +137,13 @@ def spatial_resample(
135137
dtype_pt: data `dtype` for resampling computation.
136138
lazy: a flag that indicates whether the operation should be performed lazily or not
137139
transform_info: a dictionary with the relevant information pertaining to an applied transform.
140+
141+
Returns:
142+
torch.Tensor: The resampled output tensor, with metadata preserved when metadata tracking is enabled.
143+
144+
Raises:
145+
ValueError: If the affine or spatial dimensions are invalid, or if the output spatial size cannot be
146+
computed.
138147
"""
139148
original_spatial_shape = img.peek_pending_shape() if isinstance(img, MetaTensor) else img.shape[1:]
140149
src_affine: torch.Tensor = img.peek_pending_affine() if isinstance(img, MetaTensor) else torch.eye(4)
@@ -156,7 +165,7 @@ def spatial_resample(
156165
elif spatial_size is None and spatial_rank > 1: # auto spatial size
157166
spatial_size, _ = compute_shape_offset(in_spatial_size, src_affine, dst_affine) # type: ignore
158167
spatial_size = torch.tensor(
159-
fall_back_tuple(ensure_tuple(spatial_size)[:spatial_rank], in_spatial_size, lambda x: x >= 0)
168+
fall_back_tuple(ensure_tuple(spatial_size)[:spatial_rank], in_spatial_size, lambda x: x is not None and x >= 0)
160169
)
161170
extra_info = {
162171
"dtype": str(dtype_pt)[6:], # remove "torch": torch.float32 -> float32

‎tests/transforms/test_spatial_resample.py‎

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
from monai.data.utils import to_affine_nd
2424
from monai.transforms import SpatialResample
2525
from monai.utils import optional_import
26-
from tests.lazy_transforms_utils import test_resampler_lazy
26+
from tests.lazy_transforms_utils import test_resampler_lazy as check_resampler_lazy
2727
from tests.test_utils import TEST_DEVICES, TEST_NDARRAYS_ALL, assert_allclose, dict_product
2828

2929
TESTS = []
@@ -148,7 +148,7 @@ def test_flips(self, img, device, data_param, expected_output):
148148
assert_allclose(out, expected_output, rtol=1e-2, atol=1e-2)
149149
assert_allclose(to_affine_nd(len(out.shape) - 1, out.affine), call_param["dst_affine"])
150150

151-
test_resampler_lazy(resampler, out, init_param=None, call_param=call_param)
151+
check_resampler_lazy(resampler, out, init_param=None, call_param=call_param)
152152

153153
@parameterized.expand(TEST_4_5_D)
154154
def test_4d_5d(self, new_shape, tile, device, dtype, expected_data):
@@ -165,7 +165,7 @@ def test_4d_5d(self, new_shape, tile, device, dtype, expected_data):
165165
assert_allclose(out, expected_data[None], rtol=1e-2, atol=1e-2)
166166
assert_allclose(out.affine, dst.to(torch.float32), rtol=1e-2, atol=1e-2)
167167

168-
test_resampler_lazy(resampler, out, init_param, call_param)
168+
check_resampler_lazy(resampler, out, init_param, call_param)
169169

170170
@parameterized.expand(TEST_DEVICES)
171171
def test_ill_affine(self, device):
@@ -199,7 +199,7 @@ def test_input_torch(self, new_shape, tile, device, dtype, expected_data, track_
199199
out = resampler(**call_param)
200200
assert_allclose(out, expected_data[None], rtol=1e-2, atol=1e-2)
201201

202-
test_resampler_lazy(resampler, out, init_param, call_param)
202+
check_resampler_lazy(resampler, out, init_param, call_param)
203203

204204
if track_meta:
205205
self.assertIsInstance(out, MetaTensor)
@@ -230,6 +230,24 @@ def test_unchange(self):
230230
assert_allclose(result, img, type_test=False)
231231
set_track_meta(True)
232232

233+
def test_none_spatial_size_rank_one(self):
234+
"""Verify that an unspecified rank-one size preserves the input shape and returns finite values."""
235+
img = MetaTensor(torch.randn(1, 8))
236+
result = SpatialResample()(img, spatial_size=None)
237+
238+
self.assertEqual(result.shape, img.shape)
239+
self.assertIsInstance(result, MetaTensor)
240+
self.assertTrue(torch.isfinite(result).all())
241+
242+
def test_partial_none_spatial_size(self):
243+
"""Verify that ``None`` dimensions fall back while specified dimensions produce the requested shape."""
244+
img = MetaTensor(torch.randn(1, 3, 6, 7))
245+
result = SpatialResample()(img, spatial_size=(None, 4, 5))
246+
247+
self.assertEqual(result.shape, (1, 3, 4, 5))
248+
self.assertIsInstance(result, MetaTensor)
249+
self.assertTrue(torch.isfinite(result).all())
250+
233251

234252
if __name__ == "__main__":
235253
unittest.main()

0 commit comments

Comments
 (0)