|
1
|
|
|
import copy |
|
2
|
|
|
import numbers |
|
3
|
|
|
from abc import ABC, abstractmethod |
|
4
|
|
|
from contextlib import contextmanager |
|
5
|
|
|
from typing import Optional, Union, Tuple, Sequence |
|
6
|
|
|
|
|
7
|
|
|
import torch |
|
8
|
|
|
import numpy as np |
|
9
|
|
|
import SimpleITK as sitk |
|
10
|
|
|
|
|
11
|
|
|
from ..data.subject import Subject |
|
12
|
|
|
from .. import TypeData, DATA, TypeNumber |
|
13
|
|
|
from ..utils import nib_to_sitk, sitk_to_nib, to_tuple |
|
14
|
|
|
from .interpolation import Interpolation |
|
15
|
|
|
from .data_parser import DataParser, TypeTransformInput |
|
16
|
|
|
|
|
17
|
|
|
|
|
18
|
|
|
class Transform(ABC): |
|
19
|
|
|
"""Abstract class for all TorchIO transforms. |
|
20
|
|
|
|
|
21
|
|
|
All subclasses should overwrite |
|
22
|
|
|
:py:meth:`torchio.tranforms.Transform.apply_transform`, |
|
23
|
|
|
which takes data, applies some transformation and returns the result. |
|
24
|
|
|
|
|
25
|
|
|
The input can be an instance of |
|
26
|
|
|
:py:class:`torchio.Subject`, |
|
27
|
|
|
:py:class:`torchio.Image`, |
|
28
|
|
|
:py:class:`numpy.ndarray`, |
|
29
|
|
|
:py:class:`torch.Tensor`, |
|
30
|
|
|
:py:class:`SimpleITK.image`, |
|
31
|
|
|
or a Python dictionary. |
|
32
|
|
|
|
|
33
|
|
|
Args: |
|
34
|
|
|
p: Probability that this transform will be applied. |
|
35
|
|
|
copy: Make a shallow copy of the input before applying the transform. |
|
36
|
|
|
keys: Mandatory if the input is a Python dictionary. The transform will |
|
37
|
|
|
be applied only to the data in each key. |
|
38
|
|
|
""" |
|
39
|
|
|
def __init__( |
|
40
|
|
|
self, |
|
41
|
|
|
p: float = 1, |
|
42
|
|
|
copy: bool = True, |
|
43
|
|
|
keys: Optional[Sequence[str]] = None, |
|
44
|
|
|
): |
|
45
|
|
|
self.probability = self.parse_probability(p) |
|
46
|
|
|
self.copy = copy |
|
47
|
|
|
self.keys = keys |
|
48
|
|
|
|
|
49
|
|
|
def __call__( |
|
50
|
|
|
self, |
|
51
|
|
|
data: TypeTransformInput, |
|
52
|
|
|
) -> TypeTransformInput: |
|
53
|
|
|
"""Transform data and return a result of the same type. |
|
54
|
|
|
|
|
55
|
|
|
Args: |
|
56
|
|
|
data: Instance of 1) :py:class:`~torchio.Subject`, 4D |
|
57
|
|
|
:py:class:`torch.Tensor` or NumPy array with dimensions |
|
58
|
|
|
:math:`(C, W, H, D)`, where :math:`C` is the number of channels |
|
59
|
|
|
and :math:`W, H, D` are the spatial dimensions. If the input is |
|
60
|
|
|
a tensor, the affine matrix will be set to identity. Other |
|
61
|
|
|
valid input types are a SimpleITK image, a |
|
62
|
|
|
:py:class:`torch.Image`, a NiBabel Nifti1 Image or a Python |
|
63
|
|
|
dictionary. The output type is the same as te input type. |
|
64
|
|
|
""" |
|
65
|
|
|
if torch.rand(1).item() > self.probability: |
|
66
|
|
|
return data |
|
67
|
|
|
data_parser = DataParser(data, keys=self.keys) |
|
68
|
|
|
subject = data_parser.get_subject() |
|
69
|
|
|
if self.copy: |
|
70
|
|
|
subject = copy.copy(subject) |
|
71
|
|
|
with np.errstate(all='raise'): |
|
72
|
|
|
transformed = self.apply_transform(subject) |
|
73
|
|
|
self.add_transform_to_subject_history(transformed) |
|
74
|
|
|
for image in transformed.get_images(intensity_only=False): |
|
75
|
|
|
ndim = image[DATA].ndim |
|
76
|
|
|
assert ndim == 4, f'Output of {self.name} is {ndim}D' |
|
77
|
|
|
output = data_parser.get_output(transformed) |
|
78
|
|
|
return output |
|
79
|
|
|
|
|
80
|
|
|
def __repr__(self): |
|
81
|
|
|
if hasattr(self, 'args_names'): |
|
82
|
|
|
names = self.args_names |
|
83
|
|
|
args_strings = [f'{arg}={getattr(self, arg)}' for arg in names] |
|
84
|
|
|
if hasattr(self, 'invert_transform') and self.invert_transform: |
|
85
|
|
|
args_strings.append('invert=True') |
|
86
|
|
|
args_string = ', '.join(args_strings) |
|
87
|
|
|
return f'{self.name}({args_string})' |
|
88
|
|
|
else: |
|
89
|
|
|
return super().__repr__() |
|
90
|
|
|
|
|
91
|
|
|
@property |
|
92
|
|
|
def name(self): |
|
93
|
|
|
return self.__class__.__name__ |
|
94
|
|
|
|
|
95
|
|
|
@abstractmethod |
|
96
|
|
|
def apply_transform(self, subject: Subject): |
|
97
|
|
|
raise NotImplementedError |
|
98
|
|
|
|
|
99
|
|
|
def add_transform_to_subject_history(self, subject): |
|
100
|
|
|
from .augmentation import RandomTransform |
|
101
|
|
|
from . import Compose, OneOf, CropOrPad |
|
102
|
|
|
call_others = ( |
|
103
|
|
|
RandomTransform, |
|
104
|
|
|
Compose, |
|
105
|
|
|
OneOf, |
|
106
|
|
|
CropOrPad, |
|
107
|
|
|
) |
|
108
|
|
|
if not isinstance(self, call_others): |
|
109
|
|
|
subject.add_transform(self, self.get_arguments()) |
|
110
|
|
|
|
|
111
|
|
|
@staticmethod |
|
112
|
|
|
def to_range(n, around): |
|
113
|
|
|
if around is None: |
|
114
|
|
|
return 0, n |
|
115
|
|
|
else: |
|
116
|
|
|
return around - n, around + n |
|
117
|
|
|
|
|
118
|
|
|
def parse_params(self, params, around, name, make_ranges=True, **kwargs): |
|
119
|
|
|
params = to_tuple(params) |
|
120
|
|
|
if len(params) == 1 or (len(params) == 2 and make_ranges): # d or (a, b) |
|
121
|
|
|
params *= 3 # (d, d, d) or (a, b, a, b, a, b) |
|
122
|
|
|
if len(params) == 3 and make_ranges: # (a, b, c) |
|
123
|
|
|
items = [self.to_range(n, around) for n in params] |
|
124
|
|
|
# (-a, a, -b, b, -c, c) or (1-a, 1+a, 1-b, 1+b, 1-c, 1+c) |
|
125
|
|
|
params = [n for prange in items for n in prange] |
|
126
|
|
|
if make_ranges: |
|
127
|
|
|
if len(params) != 6: |
|
128
|
|
|
message = ( |
|
129
|
|
|
f'If "{name}" is a sequence, it must have length 2, 3 or 6,' |
|
130
|
|
|
f' not {len(params)}' |
|
131
|
|
|
) |
|
132
|
|
|
raise ValueError(message) |
|
133
|
|
|
for param_range in zip(params[::2], params[1::2]): |
|
134
|
|
|
self.parse_range(param_range, name, **kwargs) |
|
135
|
|
|
return tuple(params) |
|
136
|
|
|
|
|
137
|
|
|
@staticmethod |
|
138
|
|
|
def parse_range( |
|
139
|
|
|
nums_range: Union[TypeNumber, Tuple[TypeNumber, TypeNumber]], |
|
140
|
|
|
name: str, |
|
141
|
|
|
min_constraint: TypeNumber = None, |
|
142
|
|
|
max_constraint: TypeNumber = None, |
|
143
|
|
|
type_constraint: type = None, |
|
144
|
|
|
) -> Tuple[TypeNumber, TypeNumber]: |
|
145
|
|
|
r"""Adapted from ``torchvision.transforms.RandomRotation``. |
|
146
|
|
|
|
|
147
|
|
|
Args: |
|
148
|
|
|
nums_range: Tuple of two numbers :math:`(n_{min}, n_{max})`, |
|
149
|
|
|
where :math:`n_{min} \leq n_{max}`. |
|
150
|
|
|
If a single positive number :math:`n` is provided, |
|
151
|
|
|
:math:`n_{min} = -n` and :math:`n_{max} = n`. |
|
152
|
|
|
name: Name of the parameter, so that an informative error message |
|
153
|
|
|
can be printed. |
|
154
|
|
|
min_constraint: Minimal value that :math:`n_{min}` can take, |
|
155
|
|
|
default is None, i.e. there is no minimal value. |
|
156
|
|
|
max_constraint: Maximal value that :math:`n_{max}` can take, |
|
157
|
|
|
default is None, i.e. there is no maximal value. |
|
158
|
|
|
type_constraint: Precise type that :math:`n_{max}` and |
|
159
|
|
|
:math:`n_{min}` must take. |
|
160
|
|
|
|
|
161
|
|
|
Returns: |
|
162
|
|
|
A tuple of two numbers :math:`(n_{min}, n_{max})`. |
|
163
|
|
|
|
|
164
|
|
|
Raises: |
|
165
|
|
|
ValueError: if :attr:`nums_range` is negative |
|
166
|
|
|
ValueError: if :math:`n_{max}` or :math:`n_{min}` is not a number |
|
167
|
|
|
ValueError: if :math:`n_{max} \lt n_{min}` |
|
168
|
|
|
ValueError: if :attr:`min_constraint` is not None and |
|
169
|
|
|
:math:`n_{min}` is smaller than :attr:`min_constraint` |
|
170
|
|
|
ValueError: if :attr:`max_constraint` is not None and |
|
171
|
|
|
:math:`n_{max}` is greater than :attr:`max_constraint` |
|
172
|
|
|
ValueError: if :attr:`type_constraint` is not None and |
|
173
|
|
|
:math:`n_{max}` and :math:`n_{max}` are not of type |
|
174
|
|
|
:attr:`type_constraint`. |
|
175
|
|
|
""" |
|
176
|
|
|
if isinstance(nums_range, numbers.Number): # single number given |
|
177
|
|
|
if nums_range < 0: |
|
178
|
|
|
raise ValueError( |
|
179
|
|
|
f'If {name} is a single number,' |
|
180
|
|
|
f' it must be positive, not {nums_range}') |
|
181
|
|
|
if min_constraint is not None and nums_range < min_constraint: |
|
182
|
|
|
raise ValueError( |
|
183
|
|
|
f'If {name} is a single number, it must be greater' |
|
184
|
|
|
f' than {min_constraint}, not {nums_range}' |
|
185
|
|
|
) |
|
186
|
|
|
if max_constraint is not None and nums_range > max_constraint: |
|
187
|
|
|
raise ValueError( |
|
188
|
|
|
f'If {name} is a single number, it must be smaller' |
|
189
|
|
|
f' than {max_constraint}, not {nums_range}' |
|
190
|
|
|
) |
|
191
|
|
|
if type_constraint is not None: |
|
192
|
|
|
if not isinstance(nums_range, type_constraint): |
|
193
|
|
|
raise ValueError( |
|
194
|
|
|
f'If {name} is a single number, it must be of' |
|
195
|
|
|
f' type {type_constraint}, not {nums_range}' |
|
196
|
|
|
) |
|
197
|
|
|
min_range = -nums_range if min_constraint is None else nums_range |
|
198
|
|
|
return (min_range, nums_range) |
|
199
|
|
|
|
|
200
|
|
|
try: |
|
201
|
|
|
min_value, max_value = nums_range |
|
202
|
|
|
except (TypeError, ValueError): |
|
203
|
|
|
raise ValueError( |
|
204
|
|
|
f'If {name} is not a single number, it must be' |
|
205
|
|
|
f' a sequence of len 2, not {nums_range}' |
|
206
|
|
|
) |
|
207
|
|
|
|
|
208
|
|
|
min_is_number = isinstance(min_value, numbers.Number) |
|
209
|
|
|
max_is_number = isinstance(max_value, numbers.Number) |
|
210
|
|
|
if not min_is_number or not max_is_number: |
|
211
|
|
|
message = ( |
|
212
|
|
|
f'{name} values must be numbers, not {nums_range}') |
|
213
|
|
|
raise ValueError(message) |
|
214
|
|
|
|
|
215
|
|
|
if min_value > max_value: |
|
216
|
|
|
raise ValueError( |
|
217
|
|
|
f'If {name} is a sequence, the second value must be' |
|
218
|
|
|
f' equal or greater than the first, but it is {nums_range}') |
|
219
|
|
|
|
|
220
|
|
|
if min_constraint is not None and min_value < min_constraint: |
|
221
|
|
|
raise ValueError( |
|
222
|
|
|
f'If {name} is a sequence, the first value must be greater' |
|
223
|
|
|
f' than {min_constraint}, but it is {min_value}' |
|
224
|
|
|
) |
|
225
|
|
|
|
|
226
|
|
|
if max_constraint is not None and max_value > max_constraint: |
|
227
|
|
|
raise ValueError( |
|
228
|
|
|
f'If {name} is a sequence, the second value must be smaller' |
|
229
|
|
|
f' than {max_constraint}, but it is {max_value}' |
|
230
|
|
|
) |
|
231
|
|
|
|
|
232
|
|
|
if type_constraint is not None: |
|
233
|
|
|
min_type_ok = isinstance(min_value, type_constraint) |
|
234
|
|
|
max_type_ok = isinstance(max_value, type_constraint) |
|
235
|
|
|
if not min_type_ok or not max_type_ok: |
|
236
|
|
|
raise ValueError( |
|
237
|
|
|
f'If "{name}" is a sequence, its values must be of' |
|
238
|
|
|
f' type "{type_constraint}", not "{type(nums_range)}"' |
|
239
|
|
|
) |
|
240
|
|
|
return nums_range |
|
241
|
|
|
|
|
242
|
|
|
@staticmethod |
|
243
|
|
|
def parse_interpolation(interpolation: str) -> str: |
|
244
|
|
|
if not isinstance(interpolation, str): |
|
245
|
|
|
itype = type(interpolation) |
|
246
|
|
|
raise TypeError(f'Interpolation must be a string, not {itype}') |
|
247
|
|
|
interpolation = interpolation.lower() |
|
248
|
|
|
is_string = isinstance(interpolation, str) |
|
249
|
|
|
supported_values = [key.name.lower() for key in Interpolation] |
|
250
|
|
|
is_supported = interpolation.lower() in supported_values |
|
251
|
|
|
if is_string and is_supported: |
|
252
|
|
|
return interpolation |
|
253
|
|
|
message = ( |
|
254
|
|
|
f'Interpolation "{interpolation}" of type {type(interpolation)}' |
|
255
|
|
|
f' must be a string among the supported values: {supported_values}' |
|
256
|
|
|
) |
|
257
|
|
|
raise ValueError(message) |
|
258
|
|
|
|
|
259
|
|
|
@staticmethod |
|
260
|
|
|
def parse_probability(probability: float) -> float: |
|
261
|
|
|
is_number = isinstance(probability, numbers.Number) |
|
262
|
|
|
if not (is_number and 0 <= probability <= 1): |
|
263
|
|
|
message = ( |
|
264
|
|
|
'Probability must be a number in [0, 1],' |
|
265
|
|
|
f' not {probability}' |
|
266
|
|
|
) |
|
267
|
|
|
raise ValueError(message) |
|
268
|
|
|
return probability |
|
269
|
|
|
|
|
270
|
|
|
@staticmethod |
|
271
|
|
|
def nib_to_sitk(data: TypeData, affine: TypeData) -> sitk.Image: |
|
272
|
|
|
return nib_to_sitk(data, affine) |
|
273
|
|
|
|
|
274
|
|
|
@staticmethod |
|
275
|
|
|
def sitk_to_nib(image: sitk.Image) -> Tuple[torch.Tensor, np.ndarray]: |
|
276
|
|
|
return sitk_to_nib(image) |
|
277
|
|
|
|
|
278
|
|
|
def get_arguments(self): |
|
279
|
|
|
""" |
|
280
|
|
|
Return a dictionary with the arguments that would be necessary to |
|
281
|
|
|
reproduce the transform exactly. |
|
282
|
|
|
""" |
|
283
|
|
|
return {name: getattr(self, name) for name in self.args_names} |
|
284
|
|
|
|
|
285
|
|
|
def is_invertible(self): |
|
286
|
|
|
return hasattr(self, 'invert_transform') |
|
287
|
|
|
|
|
288
|
|
|
def inverse(self): |
|
289
|
|
|
if not self.is_invertible(): |
|
290
|
|
|
raise RuntimeError(f'{self.name} is not invertible') |
|
291
|
|
|
new = copy.deepcopy(self) |
|
292
|
|
|
new.invert_transform = not self.invert_transform |
|
293
|
|
|
return new |
|
294
|
|
|
|
|
295
|
|
|
@staticmethod |
|
296
|
|
|
@contextmanager |
|
297
|
|
|
def use_seed(seed): |
|
298
|
|
|
"""Perform an operation using a specific seed for the PyTorch RNG""" |
|
299
|
|
|
torch_rng_state = torch.random.get_rng_state() |
|
300
|
|
|
torch.manual_seed(seed) |
|
301
|
|
|
yield |
|
302
|
|
|
torch.random.set_rng_state(torch_rng_state) |
|
303
|
|
|
|