|
1
|
|
|
import numbers |
|
2
|
|
|
import warnings |
|
|
|
|
|
|
3
|
|
|
from copy import deepcopy |
|
4
|
|
|
from abc import ABC, abstractmethod |
|
5
|
|
|
|
|
6
|
|
|
import torch |
|
|
|
|
|
|
7
|
|
|
import SimpleITK as sitk |
|
|
|
|
|
|
8
|
|
|
|
|
9
|
|
|
from .. import TypeData, TYPE |
|
|
|
|
|
|
10
|
|
|
from ..data.images import Subject |
|
11
|
|
|
from ..utils import is_image_dict, nib_to_sitk, sitk_to_nib |
|
|
|
|
|
|
12
|
|
|
|
|
13
|
|
|
|
|
14
|
|
|
class Transform(ABC): |
|
15
|
|
|
"""Abstract class for all TorchIO transforms. |
|
16
|
|
|
|
|
17
|
|
|
All classes used to transform a sample from an |
|
18
|
|
|
:py:class:`~torchio.ImagesDataset` should subclass it. |
|
19
|
|
|
All subclasses should overwrite |
|
20
|
|
|
:py:meth:`torchio.tranforms.Transform.apply_transform`, |
|
21
|
|
|
which takes a sample, applies some transformation and returns the result. |
|
22
|
|
|
|
|
23
|
|
|
Args: |
|
24
|
|
|
p: Probability that this transform will be applied. |
|
25
|
|
|
""" |
|
26
|
|
|
def __init__(self, p: float = 1): |
|
27
|
|
|
self.probability = self.parse_probability(p) |
|
28
|
|
|
|
|
29
|
|
|
def __call__(self, sample: Subject): |
|
30
|
|
|
"""Transform a sample and return the result.""" |
|
31
|
|
|
self.parse_sample(sample) |
|
32
|
|
|
if torch.rand(1).item() > self.probability: |
|
33
|
|
|
return sample |
|
34
|
|
|
sample = deepcopy(sample) |
|
35
|
|
|
sample = self.apply_transform(sample) |
|
36
|
|
|
return sample |
|
37
|
|
|
|
|
38
|
|
|
@abstractmethod |
|
39
|
|
|
def apply_transform(self, sample: Subject): |
|
40
|
|
|
raise NotImplementedError |
|
41
|
|
|
|
|
42
|
|
|
@staticmethod |
|
43
|
|
|
def parse_probability(probability: float) -> float: |
|
44
|
|
|
is_number = isinstance(probability, numbers.Number) |
|
45
|
|
|
if not (is_number and 0 <= probability <= 1): |
|
46
|
|
|
message = ( |
|
47
|
|
|
'Probability must be a number in [0, 1],' |
|
48
|
|
|
f' not {probability}' |
|
49
|
|
|
) |
|
50
|
|
|
raise ValueError(message) |
|
51
|
|
|
return probability |
|
52
|
|
|
|
|
53
|
|
|
@staticmethod |
|
54
|
|
|
def parse_sample(sample: Subject) -> None: |
|
55
|
|
|
if not isinstance(sample, Subject) or not sample.is_sample: |
|
56
|
|
|
message = ( |
|
57
|
|
|
'Inputs to transforms must be instances of torchio.Subject' |
|
58
|
|
|
f' generated by a torchio.ImagesDataset, not "{type(sample)}"' |
|
59
|
|
|
) |
|
60
|
|
|
raise RuntimeError(message) |
|
61
|
|
|
|
|
62
|
|
|
@staticmethod |
|
63
|
|
|
def nib_to_sitk(data: TypeData, affine: TypeData): |
|
64
|
|
|
return nib_to_sitk(data, affine) |
|
65
|
|
|
|
|
66
|
|
|
@staticmethod |
|
67
|
|
|
def sitk_to_nib(image: sitk.Image): |
|
68
|
|
|
return sitk_to_nib(image) |
|
69
|
|
|
|