Passed
Pull Request — master (#257)
by Fernando
01:05
created

torchio.data.subject.Subject.get_first_image()   A

Complexity

Conditions 1

Size

Total Lines 2
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nop 1
dl 0
loc 2
rs 10
c 0
b 0
f 0
1
import copy
2
import pprint
3
from typing import Any, Dict, List, Tuple
4
from ..torchio import TYPE, INTENSITY
5
from .image import Image
6
7
8
class Subject(dict):
9
    """Class to store information about the images corresponding to a subject.
10
11
    Args:
12
        *args: If provided, a dictionary of items.
13
        **kwargs: Items that will be added to the subject sample.
14
15
    Example:
16
17
        >>> import torchio
18
        >>> from torchio import ScalarImage, LabelMap, Subject
19
        >>> # One way:
20
        >>> subject = Subject(
21
        ...     one_image=ScalarImage('path_to_image.nii.gz'),
22
        ...     a_segmentation=LabelMap('path_to_seg.nii.gz'),
23
        ...     age=45,
24
        ...     name='John Doe',
25
        ...     hospital='Hospital Juan Negrín',
26
        ... )
27
        >>> # If you want to create the mapping before, or have spaces in the keys:
28
        >>> subject_dict = {
29
        ...     'one image': ScalarImage('path_to_image.nii.gz'),
30
        ...     'a segmentation': LabelMap('path_to_seg.nii.gz'),
31
        ...     'age': 45,
32
        ...     'name': 'John Doe',
33
        ...     'hospital': 'Hospital Juan Negrín',
34
        ... }
35
        >>> Subject(subject_dict)
36
37
    """
38
39
    def __init__(self, *args, **kwargs: Dict[str, Any]):
40
        if args:
41
            if len(args) == 1 and isinstance(args[0], dict):
42
                kwargs.update(args[0])
43
            else:
44
                message = (
45
                    'Only one dictionary as positional argument is allowed')
46
                raise ValueError(message)
47
        super().__init__(**kwargs)
48
        self.images = [
49
            (k, v) for (k, v) in self.items()
50
            if isinstance(v, Image)
51
        ]
52
        self._parse_images(self.images)
53
        self.update_attributes()  # this allows me to do e.g. subject.t1
54
        self.history = []
55
56
    def __repr__(self):
57
        string = (
58
            f'{self.__class__.__name__}'
59
            f'(Keys: {tuple(self.keys())}; images: {len(self.images)})'
60
        )
61
        return string
62
63
    def __copy__(self):
64
        result_dict = {}
65
        for key, value in self.items():
66
            if isinstance(value, Image):
67
                value = copy.copy(value)
68
            else:
69
                value = copy.deepcopy(value)
70
            result_dict[key] = value
71
        new = Subject(result_dict)
72
        new.history = self.history
73
        return new
74
75
    @staticmethod
76
    def _parse_images(images: List[Tuple[str, Image]]) -> None:
77
        # Check that it's not empty
78
        if not images:
79
            raise ValueError('A subject without images cannot be created')
80
81
    @property
82
    def shape(self):
83
        """Return shape of first image in subject.
84
85
        Consistency of shapes across images in the subject is checked first.
86
        """
87
        self.check_consistent_shape()
88
        image = self.get_images(intensity_only=False)[0]
89
        return image.shape
90
91
    @property
92
    def spatial_shape(self):
93
        """Return spatial shape of first image in subject.
94
95
        Consistency of shapes across images in the subject is checked first.
96
        """
97
        return self.shape[1:]
98
99
    @property
100
    def spacing(self):
101
        """Return spacing of first image in subject.
102
103
        Consistency of shapes across images in the subject is checked first.
104
        """
105
        self.check_consistent_shape()
106
        image = self.get_images(intensity_only=False)[0]
107
        return image.spacing
108
109
    def get_images_dict(self, intensity_only=True):
110
        images = {}
111
        for image_name, image in self.items():
112
            if not isinstance(image, Image):
113
                continue
114
            if intensity_only and not image[TYPE] == INTENSITY:
115
                continue
116
            images[image_name] = image
117
        return images
118
119
    def get_images(self, intensity_only=True):
120
        images_dict = self.get_images_dict(intensity_only=intensity_only)
121
        return list(images_dict.values())
122
123
    def get_first_image(self):
124
        return self.get_images(intensity_only=False)[0]
125
126
    def check_consistent_shape(self) -> None:
127
        shapes_dict = {}
128
        iterable = self.get_images_dict(intensity_only=False).items()
129
        for image_name, image in iterable:
130
            shapes_dict[image_name] = image.shape
131
        num_unique_shapes = len(set(shapes_dict.values()))
132
        if num_unique_shapes > 1:
133
            message = (
134
                'Images in subject have inconsistent shapes:'
135
                f'\n{pprint.pformat(shapes_dict)}'
136
            )
137
            raise ValueError(message)
138
139
    def check_consistent_orientation(self) -> None:
140
        orientations_dict = {}
141
        iterable = self.get_images_dict(intensity_only=False).items()
142
        for image_name, image in iterable:
143
            orientations_dict[image_name] = image.orientation
144
        num_unique_orientations = len(set(orientations_dict.values()))
145
        if num_unique_orientations > 1:
146
            message = (
147
                'Images in subject have inconsistent orientations:'
148
                f'\n{pprint.pformat(orientations_dict)}'
149
            )
150
            raise ValueError(message)
151
152
    def add_transform(
153
            self,
154
            transform: 'Transform',
155
            parameters_dict: dict,
156
            ) -> None:
157
        self.history.append((transform.name, parameters_dict))
158
159
    def load(self):
160
        for image in self.get_images(intensity_only=False):
161
            image._load()
162
163
    def crop(self, index_ini, index_fin):
164
        result_dict = {}
165
        for key, value in self.items():
166
            if isinstance(value, Image):
167
                # patch.clone() is much faster than copy.deepcopy(patch)
168
                value = value.crop(index_ini, index_fin)
169
            else:
170
                value = copy.deepcopy(value)
171
            result_dict[key] = value
172
        new = Subject(result_dict)
173
        new.history = self.history
174
        return new
175
176
    def update_attributes(self):
177
        # This allows to get images using attribute notation, e.g. subject.t1
178
        self.__dict__.update(self)
179
180
    def add_image(self, image, image_name):
181
        self[image_name] = image
182
        self.update_attributes()
183