Skip to content

Commit b947a1c

Browse files
committed
NF: allow scalar voxel sizes in output resampling
Allow user to specify a scalar meaning that voxel sizes for each dimension of the image should be the same.
1 parent a9e1900 commit b947a1c

File tree

2 files changed

+16
-3
lines changed

2 files changed

+16
-3
lines changed

nibabel/processing.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,8 @@ def resample_to_output(in_img,
194194
Gives the diagonal entries of ``out_img.affine` (except the trailing 1
195195
for the homogenous coordinates) (``out_img.affine ==
196196
np.diag(voxel_sizes + [1])``). If None, return identity
197-
`out_img.affine`.
197+
`out_img.affine`. If scalar, interpret as vector ``[voxel_sizes] *
198+
len(in_img.shape)``.
198199
order : int, optional
199200
The order of the spline interpolation, default is 3. The order has to
200201
be in the range 0-5 (see ``scipy.ndimage.affine_transform``).
@@ -218,10 +219,14 @@ def resample_to_output(in_img,
218219
"""
219220
if out_class is None:
220221
out_class = in_img.__class__
221-
# Allow 2D images by promoting to 3D. We might want to see what a slice
222-
# looks like when resampled into world coordinates
223222
in_shape = in_img.shape
224223
n_dim = len(in_shape)
224+
if voxel_sizes is not None:
225+
voxel_sizes = np.asarray(voxel_sizes)
226+
if voxel_sizes.ndim == 0: # Scalar
227+
voxel_sizes = np.repeat(voxel_sizes, n_dim)
228+
# Allow 2D images by promoting to 3D. We might want to see what a slice
229+
# looks like when resampled into world coordinates
225230
if n_dim < 3: # Expand image to 3D, make voxel sizes match
226231
new_shape = in_shape + (1,) * (3 - n_dim)
227232
data = in_img.get_data().reshape(new_shape) # 2D data should be small

nibabel/tests/test_processing.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,10 +185,18 @@ def test_resample_to_output():
185185
# Image aligned to output axes - no-op
186186
data = np.arange(24).reshape((2, 3, 4))
187187
img = Nifti1Image(data, np.eye(4))
188+
# Check default resampling
188189
img2 = resample_to_output(img)
189190
assert_array_equal(img2.shape, (2, 3, 4))
190191
assert_array_equal(img2.affine, np.eye(4))
191192
assert_array_equal(img2.dataobj, data)
193+
# Check resampling with different voxel size specifications
194+
for vox_sizes in (None, 1, [1, 1, 1]):
195+
img2 = resample_to_output(img, vox_sizes)
196+
assert_array_equal(img2.shape, (2, 3, 4))
197+
assert_array_equal(img2.affine, np.eye(4))
198+
assert_array_equal(img2.dataobj, data)
199+
img2 = resample_to_output(img, vox_sizes)
192200
# Check 2D works
193201
img_2d = Nifti1Image(data[0], np.eye(4))
194202
img3 = resample_to_output(img_2d)

0 commit comments

Comments
 (0)