Passed
Pull Request — master (#334)
by Fernando
01:13
created

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

Complexity

Conditions 3

Size

Total Lines 13
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 10
nop 3
dl 0
loc 13
rs 9.9
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._parse_images(self.get_images(intensity_only=False))
49
        self.update_attributes()  # this allows me to do e.g. subject.t1
50
        self.history = []
51
52
    def __repr__(self):
53
        num_images = len(self.get_images(intensity_only=False))
54
        string = (
55
            f'{self.__class__.__name__}'
56
            f'(Keys: {tuple(self.keys())}; images: {num_images})'
57
        )
58
        return string
59
60
    def __copy__(self):
61
        result_dict = {}
62
        for key, value in self.items():
63
            if isinstance(value, Image):
64
                value = copy.copy(value)
65
            else:
66
                value = copy.deepcopy(value)
67
            result_dict[key] = value
68
        new = Subject(result_dict)
69
        new.history = self.history[:]
70
        return new
71
72
    def __len__(self):
73
        return len(self.get_images(intensity_only=False))
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_attribute('shape')
88
        return self.get_first_image().shape
89
90
    @property
91
    def spatial_shape(self):
92
        """Return spatial shape of first image in subject.
93
94
        Consistency of spatial shapes across images in the subject is checked
95
        first.
96
        """
97
        self.check_consistent_spatial_shape()
98
        return self.get_first_image().spatial_shape
99
100
    @property
101
    def spacing(self):
102
        """Return spacing of first image in subject.
103
104
        Consistency of spacings across images in the subject is checked first.
105
        """
106
        self.check_consistent_attribute('spacing')
107
        return self.get_first_image().spacing
108
109
    def check_consistent_attribute(self, attribute: str) -> None:
110
        values_dict = {}
111
        iterable = self.get_images_dict(intensity_only=False).items()
112
        for image_name, image in iterable:
113
            values_dict[image_name] = getattr(image, attribute)
114
        num_unique_values = len(set(values_dict.values()))
115
        if num_unique_values > 1:
116
            message = (
117
                f'More than one {attribute} found in subject images:'
118
                f'\n{pprint.pformat(values_dict)}'
119
            )
120
            raise RuntimeError(message)
121
122
    def check_consistent_spatial_shape(self) -> None:
123
        self.check_consistent_attribute('spatial_shape')
124
125
    def check_consistent_orientation(self) -> None:
126
        self.check_consistent_attribute('orientation')
127
128
    def get_images_dict(self, intensity_only=True):
129
        images = {}
130
        for image_name, image in self.items():
131
            if not isinstance(image, Image):
132
                continue
133
            if intensity_only and not image[TYPE] == INTENSITY:
134
                continue
135
            images[image_name] = image
136
        return images
137
138
    def get_images(self, intensity_only=True):
139
        images_dict = self.get_images_dict(intensity_only=intensity_only)
140
        return list(images_dict.values())
141
142
    def get_first_image(self):
143
        return self.get_images(intensity_only=False)[0]
144
145
    # flake8: noqa: F821
146
    def add_transform(
147
            self,
148
            transform: 'Transform',
149
            parameters_dict: dict,
150
            ) -> None:
151
        self.history.append((transform.name, parameters_dict))
152
153
    def load(self):
154
        """Load images in subject."""
155
        for image in self.get_images(intensity_only=False):
156
            image.load()
157
158
    def update_attributes(self):
159
        # This allows to get images using attribute notation, e.g. subject.t1
160
        self.__dict__.update(self)
161
162
    def add_image(self, image: Image, image_name: str) -> None:
163
        """Add an image."""
164
        self[image_name] = image
165
        self.update_attributes()
166
167
    def remove_image(self, image_name: str) -> None:
168
        """Remove an image."""
169
        del self[image_name]
170
171
    def plot(self, **kwargs) -> None:
172
        """Plot images."""
173
        from ..visualization import plot_subject  # avoid circular import
174
        plot_subject(self, **kwargs)
175