Passed
Push — master ( 23d6b7...46cc7d )
by Fernando
01:09
created

torchio.data.image.Image.data()   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
import warnings
2
from pathlib import Path
3
from typing import Any, Dict, Tuple, Optional
4
5
import torch
6
import numpy as np
7
import nibabel as nib
8
import SimpleITK as sitk
9
10
from ..utils import nib_to_sitk
11
from ..torchio import (
12
    TypePath,
13
    TypeTripletInt,
14
    TypeTripletFloat,
15
    DATA,
16
    TYPE,
17
    AFFINE,
18
    PATH,
19
    STEM,
20
    INTENSITY,
21
)
22
from .io import read_image
23
24
25
class Image(dict):
26
    r"""Class to store information about an image.
27
28
    Args:
29
        path: Path to a file that can be read by
30
            :mod:`SimpleITK` or :mod:`nibabel` or to a directory containing
31
            DICOM files.
32
        type: Type of image, such as :attr:`torchio.INTENSITY` or
33
            :attr:`torchio.LABEL`. This will be used by the transforms to
34
            decide whether to apply an operation, or which interpolation to use
35
            when resampling.
36
        tensor: If :attr:`path` is not given, :attr:`tensor` must be a 4D
37
            :py:class:`torch.Tensor` with dimensions :math:`(C, D, H, W)`,
38
            where :math:`C` is the number of channels and :math:`D, H, W`
39
            are the spatial dimensions.
40
        affine: If :attr:`path` is not given, :attr:`affine` must be a
41
            :math:`4 \times 4` NumPy array. If ``None``, :attr:`affine` is an
42
            identity matrix.
43
        **kwargs: Items that will be added to image dictionary within the
44
            subject sample.
45
    """
46
    def __init__(
47
            self,
48
            path: Optional[TypePath] = None,
49
            type: str = INTENSITY,
50
            tensor: Optional[torch.Tensor] = None,
51
            affine: Optional[torch.Tensor] = None,
52
            **kwargs: Dict[str, Any],
53
            ):
54
        if path is None and tensor is None:
55
            raise ValueError('A value for path or tensor must be given')
56
        if path is not None:
57
            if tensor is not None or affine is not None:
58
                message = 'If a path is given, tensor and affine must be None'
59
                raise ValueError(message)
60
        self._tensor = self.parse_tensor(tensor)
61
        self._affine = self.parse_affine(affine)
62
        if self._affine is None:
63
            self._affine = np.eye(4)
64
        for key in (DATA, AFFINE, TYPE, PATH, STEM):
65
            if key in kwargs:
66
                raise ValueError(f'Key {key} is reserved. Use a different one')
67
68
        super().__init__(**kwargs)
69
        self.path = self._parse_path(path)
70
        self.type = type
71
        self.is_sample = False  # set to True by ImagesDataset
72
73
    @property
74
    def data(self):
75
        return self[DATA]
76
77
    @property
78
    def affine(self):
79
        return self[AFFINE]
80
81
    @property
82
    def shape(self) -> Tuple[int, int, int, int]:
83
        return self[DATA].shape
84
85
    @property
86
    def spatial_shape(self) -> TypeTripletInt:
87
        return self.shape[1:]
88
89
    @property
90
    def orientation(self):
91
        return nib.aff2axcodes(self[AFFINE])
92
93
    @staticmethod
94
    def _parse_path(path: TypePath) -> Path:
95
        if path is None:
96
            return None
97
        try:
98
            path = Path(path).expanduser()
99
        except TypeError:
100
            message = f'Conversion to path not possible for variable: {path}'
101
            raise TypeError(message)
102
        if not (path.is_file() or path.is_dir()):  # might be a dir with DICOM
103
            raise FileNotFoundError(f'File not found: {path}')
104
        return path
105
106
    @staticmethod
107
    def parse_tensor(tensor: torch.Tensor) -> torch.Tensor:
108
        if tensor is None:
109
            return None
110
        num_dimensions = tensor.dim()
111
        if num_dimensions != 3:
112
            message = (
113
                'The input tensor must have 3 dimensions (D, H, W),'
114
                f' but has {num_dimensions}: {tensor.shape}'
115
            )
116
            raise RuntimeError(message)
117
        tensor = tensor.unsqueeze(0)  # add channels dimension
118
        return tensor
119
120
    @staticmethod
121
    def parse_affine(affine: np.ndarray) -> np.ndarray:
122
        if affine is None:
123
            return np.eye(4)
124
        if not isinstance(affine, np.ndarray):
125
            raise TypeError(f'Affine must be a NumPy array, not {type(affine)}')
126
        if affine.shape != (4, 4):
127
            raise ValueError(f'Affine shape must be (4, 4), not {affine.shape}')
128
        return affine
129
130
    def load(self, check_nans: bool = True) -> Tuple[torch.Tensor, np.ndarray]:
131
        r"""Load the image from disk.
132
133
        The file is expected to be monomodal/grayscale and 2D or 3D.
134
        A channels dimension is added to the tensor.
135
136
        Args:
137
            check_nans: If ``True``, issues a warning if NaNs are found
138
                in the image
139
140
        Returns:
141
            Tuple containing a 4D data tensor of size
142
            :math:`(1, D_{in}, H_{in}, W_{in})`
143
            and a 2D 4x4 affine matrix
144
        """
145
        if self.path is None:
146
            return self._tensor, self._affine
147
        tensor, affine = read_image(self.path)
148
        # https://github.com/pytorch/pytorch/issues/9410#issuecomment-404968513
149
        tensor = tensor[(None,) * (3 - tensor.ndim)]  # force to be 3D
150
        # Remove next line and uncomment the two following ones once/if this issue
151
        # gets fixed:
152
        # https://github.com/pytorch/pytorch/issues/29010
153
        # See also https://discuss.pytorch.org/t/collating-named-tensors/78650/4
154
        tensor = tensor.unsqueeze(0)  # add channels dimension
155
        # name_dimensions(tensor, affine)
156
        # tensor = tensor.align_to('channels', ...)
157
        if check_nans and torch.isnan(tensor).any():
158
            warnings.warn(f'NaNs found in file "{self.path}"')
159
        return tensor, affine
160
161
    def is_2d(self) -> bool:
162
        return self.shape[-3] == 1
163
164
    def numpy(self) -> np.ndarray:
165
        return self[DATA].numpy()
166
167
    def as_sitk(self) -> sitk.Image:
168
        return nib_to_sitk(self[DATA], self[AFFINE])
169
170
    def get_center(self, lps: bool = False) -> TypeTripletFloat:
171
        """Get image center in RAS (default) or LPS coordinates."""
172
        image = self.as_sitk()
173
        size = np.array(image.GetSize())
174
        center_index = (size - 1) / 2
175
        l, p, s = image.TransformContinuousIndexToPhysicalPoint(center_index)
176
        if lps:
177
            return (l, p, s)
178
        else:
179
            return (-l, -p, s)
180