-
Notifications
You must be signed in to change notification settings - Fork 5
/
torchio_transforms.py
299 lines (251 loc) · 11.3 KB
/
torchio_transforms.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
from torchio import RandomElasticDeformation, RandomAffine, RandomFlip, RandomNoise, RandomMotion, RandomSpike, RandomBiasField, RandomBlur, RandomGamma
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torch
import sys
import torchio as tio
from torchio.transforms.augmentation.intensity.random_bias_field import RandomBiasField
class ElasticTransform(object):
"""
A transformation to add random elastic deformation
the distance between nibabel grid points is 3mm
Params:
replace: the value in the image to replace
distr: the distribution of the gaussian to use for replacing values
"""
def __init__(self, max_disp= 20, num_control_points=(8, 8, 6), locked_borders=2):
self.max_disp = max_disp
self.num_control_points = num_control_points
self.transform = RandomElasticDeformation(
max_displacement=max_disp,
num_control_points=num_control_points,
locked_borders=locked_borders,
)
# interpolate 0 with mean values
def __call__(self, sample):
"""
img, label, pct = sample['img'], sample['label'], sample['90_pct']
trans_img = self.transform(img)
reproduce_transform = trans_img.get_composed_history()
trans_label = reproduce_transform(label)
return {'img': trans_img, 'label': trans_label, 'fn': sample['fn'], '90_pct': sample['90_pct']}
"""
trans_img = self.transform(sample)
return trans_img
class TorchioAffine(object):
def __init__(self, scales=0, degrees=(11, 11, 11), translation=(10, 10, 5), default_pad_value='mean', isotropic=False, center='image', image_interpolation='linear'):
'''
Random affine transformations
scales -- Tuple (a1,b1,a2,b2,a3,b3) defining the scaling ranges. The scaling values along each dimension are (s1,s2,s3), where si∼U(ai,bi).
If two values (a,b) are provided, then si∼U(a,b). If only one value x is provided, then si∼U(1−x,1+x). If three values (x1,x2,x3) are provided, then si∼U(1−xi,1+xi).
For example, using scales=(0.5, 0.5) will zoom out the image, making the objects inside look twice as small while preserving the physical size and position of the image bounds.
degrees -- tuple (a1,b1,a2,b2,a3,b3) defining rotation in degrees. Rotation sampled as Theta_i ~ U(ai,bi), or Theta_i ~ U(-ai, ai) if only one value per axis provided.
translation -- tuple (a1,b1,a2,b2,a3,b3) defining translation ranges in mm. translation t_i ~ U(ai,bi) or t_i ~ U(-a_i,a_i) if no bi provided.
isotropic -- if True, scaling factor along all dimensions the same.
center -- if 'image', rotation and scaling will be done about image center. If 'origin', will be performed about origin in real world coordinates.
default_pad_value -- How to pad images near border after rotation
image_interpolation -- linear, nearest, bspline
'''
self.transform = RandomAffine(
scales=scales,
degrees=degrees,
translation=translation,
default_pad_value=default_pad_value,
isotropic=isotropic,
center=center,
image_interpolation=image_interpolation,
)
def __call__(self, sample):
trans_img = self.transform(sample)
return trans_img
class TorchioFlip(object):
def __init__(self, axes =(0,1,2), flip_probability=0.5):
self.transform = RandomFlip(
axes=axes,
flip_probability=flip_probability,
)
def __call__(self, sample):
trans_img = self.transform(sample)
return trans_img
class TorchioNoise(object):
'''
mean – Mean μ of the Gaussian distribution from which the noise is sampled. If two values (a,b) are provided, then μ∼U(a,b). If only one value d is provided, μ∼U(−d,d)
std – Standard deviation of the Gaussian distribution from which the noise is sampled. If two values (a,b) are provided, then σ∼U(a,b). If only one value d is provided, σ∼U(0,d).
'''
def __init__(self, mean=(0,0), std=(0.25,0.5)):
self.transform = RandomNoise(
mean=mean,
std=std,
)
def __call__(self, sample):
trans_img = self.transform(sample)
return trans_img
class TorchioBlur(object):
"""
Blur an image using a random Gaussian filter
Param:
std: Tuple :math:`(a_1, b_1, a_2, b_2, a_3, b_3)` representing the
ranges (in mm) of the standard deviations
:math:`(\sigma_1, \sigma_2, \sigma_3)` of the Gaussian kernels used
to blur the image along each axis, where
:math:`\sigma_i \sim \mathcal{U}(a_i, b_i)`.
If two values :math:`(a, b)` are provided,
then :math:`\sigma_i \sim \mathcal{U}(a, b)`.
If only one value :math:`x` is provided,
then :math:`\sigma_i \sim \mathcal{U}(0, x)`.
If three values :math:`(x_1, x_2, x_3)` are provided,
then :math:`\sigma_i \sim \mathcal{U}(0, x_i)`.
"""
def __init__(self, std =(0.25)):
self.transform = RandomBlur(
std=std
)
def __call__(self,sample):
trans_img = self.transform(sample)
return trans_img
class TorchioGamma(object):
"""
Randomly change contrast of an image by raising its values to the power γ
Params:
log_gamma – Tuple (a,b) to compute the exponent γ=e^β, where β∼U(a,b).
If a single value d is provided, then β∼U(−d,d). Negative and positive values for this argument perform gamma compression and expansion, respectively.
"""
def __init__(self, log_gamma=(-0.3,0.3)):
self.transform = RandomGamma(
log_gamma=log_gamma
)
def __call__(self,sample):
trans_img = self.transform(sample)
return trans_img
class TorchioMotion(object):
"""
Add a random motion artifact to MRI images.
Params:
degrees: Tuple :math:`(a, b)` defining the rotation range in degrees of
the simulated movements. The rotation angles around each axis are
(\theta_1, \theta_2, \theta_3),
where `\theta_i ~ {U}(a, b)`.
If only one value :math:`d` is provided,
:math:`\theta_i \sim \mathcal{U}(-d, d)`.
Larger values generate more distorted images.
translation: Tuple :math:`(a, b)` defining the translation in mm of
the simulated movements. The translations along each axis are
:math:`(t_1, t_2, t_3)`,
where :math:`t_i \sim \mathcal{U}(a, b)`.
If only one value :math:`t` is provided,
:math:`t_i \sim \mathcal{U}(-t, t)`.
Larger values generate more distorted images.
num_transforms: Number of simulated movements.
Larger values generate more distorted images.
image_interpolation: Interpolation
"""
def __init__(self,degrees=10,translation=10,num_transforms=2,image_interpolation='linear'):
self.transform = RandomMotion(
degrees=degrees,
translation=translation,
num_transforms=num_transforms,
image_interpolation=image_interpolation,
)
def __call__(self, sample):
trans_img = self.transform(sample)
return trans_img
class TorchioSpike(object):
"""
Add random spike artifacts
Params:
num_spikes: Number of spikes :n present in k-space.
If a tuple :math:`(a, b)` is provided, then
n ~\mathcal{U}(a, b) \cap \mathbb{N}`.
If only one value :d is provided,
n ~ \mathcal{U}(0, d) \cap \mathbb{N}`.
Larger values generate more distorted images.
intensity: Ratio :math:`r` between the spike intensity and the maximum
of the spectrum.
If a tuple :math:`(a, b)` is provided, then
:math:`r \sim \mathcal{U}(a, b)`.
If only one value :math:`d` is provided,
:math:`r \sim \mathcal{U}(-d, d)`.
Larger values generate more distorted images.
"""
def __init__(self, num_spikes=1, intensity=(1,3)):
self.transform = RandomSpike(
num_spikes=num_spikes,
intensity=intensity
)
def __call__(self, sample):
trans_img = self.transform(sample)
return trans_img
class TorchioBiasField(object):
"""
Adds bias field to the image
Params:
coefficients – Maximum magnitude n of polynomial coefficients. If a tuple (a,b) is specified, then n∼U(a,b)
order – Order of the basis polynomial functions.
"""
def __init__(self, coefficients=0.5,order=3):
self.transform = RandomBiasField(
coefficients=coefficients,
order=order
)
def __call__(self, sample):
trans_img = self.transform(sample)
return trans_img
class TorchioIntensity(object):
"""
A transformation to scale the intensity of an image
Params:
scale: the constant factor to multiply the image by
"""
def __init__(self, scale,):
self.scale = scale
def __call__(self, sample):
scale = random(self.scale[0], self.scale[1])
img, label = sample['img']['data'], sample['label']['data']
img *= scale
return tio.Subject({
'img': tio.ScalarImage(tensor=img),
'label': tio.LabelMap(tensor=label),
'fn': sample['fn'],
'fn_img_path': sample['fn_img_path'],
'fn_label_path': sample['fn_label_path'],
'fn_label': sample['fn_label'],
'90_pct': sample['90_pct'],
'low' : sample['low'],
'affine' : sample['affine'],
'label_affine': sample['label_affine'],
'pad_amnt': sample['pad_amnt']
})
class TorchioBrightness(object):
"""
A transformation to scale the brightness of an image. This can scale either only the
labeled area, or the entire image.
Params:
scale: the constant factor to add to the image
full_image: True if the entire image should be scaled, False otherwise
"""
def __init__(self, scale, full_image=False):
self.scale = scale
self.full_image = full_image
def __call__(self, sample):
scale = random(self.scale[0], self.scale[1])
img, label = sample['img']['data'], sample['label']['data']
if self.full_image:
img += scale
else:
img[label==1] += scale
return tio.Subject({
'img': tio.ScalarImage(tensor=img),
'label': tio.LabelMap(tensor=label),
'fn': sample['fn'],
'fn_img_path': sample['fn_img_path'],
'fn_label_path': sample['fn_label_path'],
'fn_label': sample['fn_label'],
'90_pct': sample['90_pct'],
'low' : sample['low'],
'affine' : sample['affine'],
'label_affine': sample['label_affine'],
'pad_amnt': sample['pad_amnt']
})
def random(lower, upper):
return np.random.random() * (upper - lower) + lower