-
Notifications
You must be signed in to change notification settings - Fork 119
/
augmentation.py
481 lines (394 loc) · 12.2 KB
/
augmentation.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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
# Copyright 2019 Image Analysis Lab, German Center for Neurodegenerative Diseases (DZNE), Bonn
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# IMPORTS
from numbers import Number, Real
from typing import Union, Tuple, Any, Dict
import numpy as np
import numpy.typing as npt
import torch
##
# Transformations for evaluation
##
class ToTensorTest(object):
"""
Convert np.ndarrays in sample to Tensors.
Methods
-------
__call__
Converts image.
"""
def __call__(self, img: npt.NDArray) -> np.ndarray:
"""
Convert the image to float within range [0, 1] and make it torch compatible.
Parameters
----------
img : npt.NDArray
Image to be converted.
Returns
-------
img : np.ndarray
Conformed image.
"""
img = img.astype(np.float32)
# Normalize and clamp between 0 and 1
img = np.clip(img / 255.0, a_min=0.0, a_max=1.0)
# swap color axis because
# numpy image: H x W x C
# torch image: C X H X W
img = img.transpose((2, 0, 1))
return img
class ZeroPad2DTest(object):
"""
Pad the input with zeros to get output size.
Attributes
----------
output_size : Union[Number, Tuple[Number, Number]]
Size of the output image either as Number or tuple of two Number.
pos : str
Position to put the input.
Methods
-------
pad
Pad zeroes of image.
call
Call _pad().
"""
def __init__(
self,
output_size: Union[Number, Tuple[Number, Number]],
pos: str = 'top_left'
):
"""
Construct object.
Parameters
----------
output_size : Union[Number, Tuple[Number, Number]]
Size of the output image either as Number or tuple of two Number.
pos : Union[Number, Tuple[Number, Number]]
Position to put the input. Defaults to 'top_left'.
"""
if isinstance(output_size, Number):
output_size = (int(output_size),) * 2
self.output_size = output_size
self.pos = pos
def _pad(self, image: npt.NDArray) -> np.ndarray:
"""
Pad with zeros of the input image.
Parameters
----------
image : npt.NDArray
The image to pad.
Returns
-------
padded_img : np.ndarray
Original image with padded zeros.
"""
if len(image.shape) == 2:
h, w = image.shape
padded_img = np.zeros(self.output_size, dtype=image.dtype)
else:
h, w, c = image.shape
padded_img = np.zeros(self.output_size + (c,), dtype=image.dtype)
if self.pos == "top_left":
padded_img[0:h, 0:w] = image
return padded_img
def __call__(self, img: npt.NDArray) -> np.ndarray:
"""
Call the _pad() function.
Parameters
----------
img : npt.NDArray
The image to pad.
Returns
-------
img : np.ndarray
Original image with padded zeros.
"""
img = self._pad(img)
return img
##
# Transformations for training
##
class ToTensor(object):
"""
Convert ndarrays in sample to Tensors.
Methods
-------
__call__
Convert image.
"""
def __call__(self, sample: npt.NDArray) -> Dict[str, Any]:
"""
Convert the image to float within range [0, 1] and make it torch compatible.
Parameters
----------
sample : npt.NDArray
Sample image.
Returns
-------
Dict[str, Any]
Converted image.
"""
img, label, weight, sf = (
sample["img"],
sample["label"],
sample["weight"],
sample["scale_factor"],
)
img = img.astype(np.float32)
# Normalize image and clamp between 0 and 1
img = np.clip(img / 255.0, a_min=0.0, a_max=1.0)
# swap color axis because
# numpy image: H x W x C
# torch image: C X H X W
img = img.transpose((2, 0, 1))
return {
"img": torch.from_numpy(img),
"label": torch.from_numpy(label),
"weight": torch.from_numpy(weight),
"scale_factor": torch.from_numpy(sf),
}
class ZeroPad2D(object):
"""
Pad the input with zeros to get output size.
Attributes
----------
output_size : Union[Number, Tuple[Number, Number]]
Size of the output image either as Number or tuple of two Number.
pos : str, Optional
Position to put the input.
Methods
-------
_pad
Pads zeroes of image.
__call__
Cals _pad for sample.
"""
def __init__(
self,
output_size: Union[Number, Tuple[Number, Number]],
pos: Union[None, str] = 'top_left'
):
"""
Initialize position and output_size (as Tuple[float]).
Parameters
----------
output_size : Union[Number, Tuple[Number, Number]]
Size of the output image either as Number or
tuple of two Number.
pos : str, Optional
Position to put the input. Default = 'top_left'.
"""
if isinstance(output_size, Number):
output_size = (int(output_size),) * 2
self.output_size = output_size
self.pos = pos
def _pad(self, image: npt.NDArray) -> np.ndarray:
"""
Pad the input image with zeros.
Parameters
----------
image : npt.NDArray
The image to pad.
Returns
-------
padded_img : np.ndarray
Original image with padded zeros.
"""
if len(image.shape) == 2:
h, w = image.shape
padded_img = np.zeros(self.output_size, dtype=image.dtype)
else:
h, w, c = image.shape
padded_img = np.zeros(self.output_size + (c,), dtype=image.dtype)
if self.pos == "top_left":
padded_img[0:h, 0:w] = image
return padded_img
def __call__(self, sample: Dict[str, Any]) -> Dict[str, Any]:
"""
Pad the image, label and weights.
Parameters
----------
sample : Dict[str, Any]
Sample image.
Returns
-------
Dict[str, Any]
Dictionary including the padded image, label, weight and scale factor.
"""
img, label, weight, sf = (
sample["img"],
sample["label"],
sample["weight"],
sample["scale_factor"],
)
img = self._pad(img)
label = self._pad(label)
weight = self._pad(weight)
return {"img": img, "label": label, "weight": weight, "scale_factor": sf}
class AddGaussianNoise(object):
"""
Add gaussian noise to sample.
Attributes
----------
std
Standard deviation.
mean
Gaussian mean.
Methods
-------
__call__
Adds noise to scale factor.
"""
def __init__(self, mean: Real = 0, std: Real = 0.1):
"""
Construct object.
Parameters
----------
mean : Real
Standard deviation. Default = 0.
std : Real
Gaussian mean. Default = 0.1.
"""
self.std = std
self.mean = mean
def __call__(self, sample: Dict[str, Real]) -> Dict[str, Real]:
"""
Add gaussian noise to scalefactor.
Parameters
----------
sample : Dict[str, Real]
Sample data to add noise.
Returns
-------
Dict[str, Real]
Sample with noise.
"""
img, label, weight, sf = (
sample["img"],
sample["label"],
sample["weight"],
sample["scale_factor"],
)
# change 1 to sf.size() for isotropic scale factors (now same noise change added to both dims)
sf = sf + torch.randn(1) * self.std + self.mean
return {"img": img, "label": label, "weight": weight, "scale_factor": sf}
class AugmentationPadImage(object):
"""
Pad Image with either zero padding or reflection padding of img, label and weight.
Attributes
----------
pad_size_image : tuple
The padding size for the image.
pad_size_mask : tuple
The padding size for the mask.
pad_type : str
The type of padding to be applied.
Methods
-------
__call
Add zeroes.
"""
def __init__(
self,
pad_size: Tuple[Tuple[int, int],
Tuple[int, int]] = ((16, 16), (16, 16)),
pad_type: str = "edge"
):
"""
Construct object.
Parameters
----------
pad_size : tuple
The padding size.
pad_type : str
The type of padding to be applied.
"""
assert isinstance(pad_size, (int, tuple))
if isinstance(pad_size, int):
# Do not pad along the channel dimension
self.pad_size_image = ((pad_size, pad_size), (pad_size, pad_size), (0, 0))
self.pad_size_mask = ((pad_size, pad_size), (pad_size, pad_size))
else:
self.pad_size = pad_size
self.pad_type = pad_type
def __call__(self, sample: Dict[str, Number]):
"""
Pad zeroes of sample image, label and weight.
Attributes
----------
sample : Dict[str, Number]
Sample image and data.
"""
img, label, weight, sf = (
sample["img"],
sample["label"],
sample["weight"],
sample["scale_factor"],
)
img = np.pad(img, self.pad_size_image, self.pad_type)
label = np.pad(label, self.pad_size_mask, self.pad_type)
weight = np.pad(weight, self.pad_size_mask, self.pad_type)
return {"img": img, "label": label, "weight": weight, "scale_factor": sf}
class AugmentationRandomCrop(object):
"""
Randomly Crop Image to given size.
"""
def __init__(self, output_size: Union[int, Tuple], crop_type: str = 'Random'):
"""Construct object.
Attributes
----------
output_size
Size of the output image either an integer or a tuple.
crop_type
The type of crop to be performed.
"""
assert isinstance(output_size, (int, tuple))
if isinstance(output_size, int):
self.output_size = (output_size, output_size)
else:
self.output_size = output_size
self.crop_type = crop_type
def __call__(self, sample: Dict[str, Number]) -> Dict[str, Number]:
"""
Crops the augmentation.
Attributes
----------
sample : Dict[str, Number]
Sample image with data.
Returns
-------
Dict[str, Number]
Cropped sample image.
"""
img, label, weight, sf = (
sample["img"],
sample["label"],
sample["weight"],
sample["scale_factor"],
)
h, w, _ = img.shape
if self.crop_type == "Center":
top = (h - self.output_size[0]) // 2
left = (w - self.output_size[1]) // 2
else:
top = np.random.randint(0, h - self.output_size[0])
left = np.random.randint(0, w - self.output_size[1])
bottom = top + self.output_size[0]
right = left + self.output_size[1]
# print(img.shape)
img = img[top:bottom, left:right, :]
label = label[top:bottom, left:right]
weight = weight[top:bottom, left:right]
return {"img": img, "label": label, "weight": weight, "scale_factor": sf}