Skip to content

Commit e38c16a

Browse files
jmarabottooesteban
authored andcommitted
enh: outsource the apply function
1 parent e792cef commit e38c16a

File tree

2 files changed

+114
-95
lines changed

2 files changed

+114
-95
lines changed

nitransforms/base.py

Lines changed: 0 additions & 95 deletions
Original file line numberDiff line numberDiff line change
@@ -222,101 +222,6 @@ def ndim(self):
222222
"""Access the dimensions of the reference space."""
223223
raise TypeError("TransformBase has no dimensions")
224224

225-
def apply(
226-
self,
227-
spatialimage,
228-
reference=None,
229-
order=3,
230-
mode="constant",
231-
cval=0.0,
232-
prefilter=True,
233-
output_dtype=None,
234-
):
235-
"""
236-
Apply a transformation to an image, resampling on the reference spatial object.
237-
238-
Parameters
239-
----------
240-
spatialimage : `spatialimage`
241-
The image object containing the data to be resampled in reference
242-
space
243-
reference : spatial object, optional
244-
The image, surface, or combination thereof containing the coordinates
245-
of samples that will be sampled.
246-
order : int, optional
247-
The order of the spline interpolation, default is 3.
248-
The order has to be in the range 0-5.
249-
mode : {'constant', 'reflect', 'nearest', 'mirror', 'wrap'}, optional
250-
Determines how the input image is extended when the resamplings overflows
251-
a border. Default is 'constant'.
252-
cval : float, optional
253-
Constant value for ``mode='constant'``. Default is 0.0.
254-
prefilter: bool, optional
255-
Determines if the image's data array is prefiltered with
256-
a spline filter before interpolation. The default is ``True``,
257-
which will create a temporary *float64* array of filtered values
258-
if *order > 1*. If setting this to ``False``, the output will be
259-
slightly blurred if *order > 1*, unless the input is prefiltered,
260-
i.e. it is the result of calling the spline filter on the original
261-
input.
262-
output_dtype: dtype specifier, optional
263-
The dtype of the returned array or image, if specified.
264-
If ``None``, the default behavior is to use the effective dtype of
265-
the input image. If slope and/or intercept are defined, the effective
266-
dtype is float64, otherwise it is equivalent to the input image's
267-
``get_data_dtype()`` (on-disk type).
268-
If ``reference`` is defined, then the return value is an image, with
269-
a data array of the effective dtype but with the on-disk dtype set to
270-
the input image's on-disk dtype.
271-
272-
Returns
273-
-------
274-
resampled : `spatialimage` or ndarray
275-
The data imaged after resampling to reference space.
276-
277-
"""
278-
if reference is not None and isinstance(reference, (str, Path)):
279-
reference = _nbload(str(reference))
280-
281-
_ref = (
282-
self.reference if reference is None else SpatialReference.factory(reference)
283-
)
284-
285-
if _ref is None:
286-
raise TransformError("Cannot apply transform without reference")
287-
288-
if isinstance(spatialimage, (str, Path)):
289-
spatialimage = _nbload(str(spatialimage))
290-
291-
data = np.asanyarray(spatialimage.dataobj)
292-
targets = ImageGrid(spatialimage).index( # data should be an image
293-
_as_homogeneous(self.map(_ref.ndcoords.T), dim=_ref.ndim)
294-
)
295-
296-
resampled = ndi.map_coordinates(
297-
data,
298-
targets.T,
299-
output=output_dtype,
300-
order=order,
301-
mode=mode,
302-
cval=cval,
303-
prefilter=prefilter,
304-
)
305-
306-
if isinstance(_ref, ImageGrid): # If reference is grid, reshape
307-
hdr = None
308-
if _ref.header is not None:
309-
hdr = _ref.header.copy()
310-
hdr.set_data_dtype(output_dtype or spatialimage.get_data_dtype())
311-
moved = spatialimage.__class__(
312-
resampled.reshape(_ref.shape),
313-
_ref.affine,
314-
hdr,
315-
)
316-
return moved
317-
318-
return resampled
319-
320225
def map(self, x, inverse=False):
321226
r"""
322227
Apply :math:`y = f(x)`.

nitransforms/resampling.py

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
# emacs: -*- mode: python-mode; py-indent-offset: 4; indent-tabs-mode: nil -*-
2+
# vi: set ft=python sts=4 ts=4 sw=4 et:
3+
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
4+
#
5+
# See COPYING file distributed along with the NiBabel package for the
6+
# copyright and license terms.
7+
#
8+
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
9+
"""Resampling utilities."""
10+
from pathlib import Path
11+
import numpy as np
12+
import h5py
13+
import warnings
14+
from nibabel.loadsave import load as _nbload
15+
from nibabel import funcs as _nbfuncs
16+
from nibabel.nifti1 import intent_codes as INTENT_CODES
17+
from nibabel.cifti2 import Cifti2Image
18+
from scipy import ndimage as ndi
19+
20+
21+
def apply(
22+
transform,
23+
spatialimage,
24+
reference=None,
25+
order=3,
26+
mode="constant",
27+
cval=0.0,
28+
prefilter=True,
29+
output_dtype=None,
30+
):
31+
"""
32+
Apply a transformation to an image, resampling on the reference spatial object.
33+
34+
Parameters
35+
----------
36+
spatialimage : `spatialimage`
37+
The image object containing the data to be resampled in reference
38+
space
39+
reference : spatial object, optional
40+
The image, surface, or combination thereof containing the coordinates
41+
of samples that will be sampled.
42+
order : int, optional
43+
The order of the spline interpolation, default is 3.
44+
The order has to be in the range 0-5.
45+
mode : {'constant', 'reflect', 'nearest', 'mirror', 'wrap'}, optional
46+
Determines how the input image is extended when the resamplings overflows
47+
a border. Default is 'constant'.
48+
cval : float, optional
49+
Constant value for ``mode='constant'``. Default is 0.0.
50+
prefilter: bool, optional
51+
Determines if the image's data array is prefiltered with
52+
a spline filter before interpolation. The default is ``True``,
53+
which will create a temporary *float64* array of filtered values
54+
if *order > 1*. If setting this to ``False``, the output will be
55+
slightly blurred if *order > 1*, unless the input is prefiltered,
56+
i.e. it is the result of calling the spline filter on the original
57+
input.
58+
output_dtype: dtype specifier, optional
59+
The dtype of the returned array or image, if specified.
60+
If ``None``, the default behavior is to use the effective dtype of
61+
the input image. If slope and/or intercept are defined, the effective
62+
dtype is float64, otherwise it is equivalent to the input image's
63+
``get_data_dtype()`` (on-disk type).
64+
If ``reference`` is defined, then the return value is an image, with
65+
a data array of the effective dtype but with the on-disk dtype set to
66+
the input image's on-disk dtype.
67+
68+
Returns
69+
-------
70+
resampled : `spatialimage` or ndarray
71+
The data imaged after resampling to reference space.
72+
73+
"""
74+
if reference is not None and isinstance(reference, (str, Path)):
75+
reference = _nbload(str(reference))
76+
77+
_ref = (
78+
transform.reference if reference is None else SpatialReference.factory(reference)
79+
)
80+
81+
if _ref is None:
82+
raise TransformError("Cannot apply transform without reference")
83+
84+
if isinstance(spatialimage, (str, Path)):
85+
spatialimage = _nbload(str(spatialimage))
86+
87+
data = np.asanyarray(spatialimage.dataobj)
88+
targets = ImageGrid(spatialimage).index( # data should be an image
89+
_as_homogeneous(transform.map(_ref.ndcoords.T), dim=_ref.ndim)
90+
)
91+
92+
resampled = ndi.map_coordinates(
93+
data,
94+
targets.T,
95+
output=output_dtype,
96+
order=order,
97+
mode=mode,
98+
cval=cval,
99+
prefilter=prefilter,
100+
)
101+
102+
if isinstance(_ref, ImageGrid): # If reference is grid, reshape
103+
hdr = None
104+
if _ref.header is not None:
105+
hdr = _ref.header.copy()
106+
hdr.set_data_dtype(output_dtype or spatialimage.get_data_dtype())
107+
moved = spatialimage.__class__(
108+
resampled.reshape(_ref.shape),
109+
_ref.affine,
110+
hdr,
111+
)
112+
return moved
113+
114+
return resampled

0 commit comments

Comments
 (0)