Passed
Push — master ( 4133e1...824ae8 )
by Fernando
06:45
created

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