Passed
Pull Request — master (#182)
by Fernando
01:03
created

GridSampler.parse_sizes()   A

Complexity

Conditions 3

Size

Total Lines 21
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 16
nop 3
dl 0
loc 21
rs 9.6
c 0
b 0
f 0
1
import numpy as np
2
from torch.utils.data import Dataset
3
4
from ..sampler.sampler import PatchSampler
5
from ...utils import to_tuple
6
from ...torchio import LOCATION, TypeTuple, TypeTripletInt
7
from ..subject import Subject
8
9
10
class GridSampler(PatchSampler, Dataset):
11
    r"""Extract patches across a whole volume.
12
13
    Grid samplers are useful to perform inference using all patches from a
14
    volume. It is often used with a :py:class:`~torchio.data.GridAggregator`.
15
16
    Args:
17
        sample: Instance of :py:class:`~torchio.data.subject.Subject`
18
            from which patches will be extracted.
19
        patch_size: Tuple of integers :math:`(d, h, w)` to generate patches
20
            of size :math:`d \times h \times w`.
21
            If a single number :math:`n` is provided,
22
            :math:`d = h = w = n`.
23
        patch_overlap: Tuple of integers :math:`(d_o, h_o, w_o)` specifying the
24
            overlap between patches for dense inference. If a single number
25
            :math:`n` is provided, :math:`d_o = h_o = w_o = n`.
26
27
    .. note:: Adapted from NiftyNet. See `this NiftyNet tutorial
28
        <https://niftynet.readthedocs.io/en/dev/window_sizes.html>`_ for more
29
        information.
30
    """
31
    def __init__(
32
            self,
33
            sample: Subject,
34
            patch_size: TypeTuple,
35
            patch_overlap: TypeTuple,
36
            ):
37
        self.sample = sample
38
        PatchSampler.__init__(self, patch_size)
39
        patch_size = to_tuple(patch_size, length=3)
40
        patch_overlap = to_tuple(patch_overlap, length=3)
41
        sizes = self.sample.spatial_shape, patch_size, patch_overlap
42
        self.parse_sizes(*sizes)
43
        self.locations = self.get_patches_locations(*sizes)
44
45
    def __len__(self):
46
        return len(self.locations)
47
48
    def __getitem__(self, index):
49
        # Assume 3D
50
        location = self.locations[index]
51
        index_ini = location[:3]
52
        index_fin = location[3:]
53
        cropped_sample = self.extract_patch(self.sample, index_ini, index_fin)
54
        cropped_sample[LOCATION] = location
55
        return cropped_sample
56
57
    @staticmethod
58
    def parse_sizes(
59
            image_size: TypeTripletInt,
60
            patch_size: TypeTripletInt,
61
            patch_overlap: TypeTripletInt,
62
            ) -> None:
63
        image_size = np.array(image_size)
64
        patch_size = np.array(patch_size)
65
        patch_overlap = np.array(patch_overlap)
66
        if np.any(patch_size > image_size):
67
            message = (
68
                f'Patch size {tuple(patch_size)} cannot be'
69
                f' larger than image size {tuple(image_size)}'
70
            )
71
            raise ValueError(message)
72
        if np.any(patch_overlap >= patch_size):
73
            message = (
74
                f'Patch overlap {tuple(patch_overlap)} must be smaller'
75
                f' than patch size {tuple(image_size)}'
76
            )
77
            raise ValueError(message)
78
79
    def extract_patch(
80
            self,
81
            sample: Subject,
82
            index_ini: TypeTripletInt,
83
            index_fin: TypeTripletInt,
84
            ) -> Subject:
85
        crop = self.get_crop_transform(
86
            sample.spatial_shape,
87
            index_ini,
88
            index_fin - index_ini,
89
        )
90
        cropped_sample = crop(sample)
91
        return cropped_sample
92
93
    @staticmethod
94
    def get_patches_locations(
95
            image_size: TypeTripletInt,
96
            patch_size: TypeTripletInt,
97
            patch_overlap: TypeTripletInt,
98
            ) -> np.ndarray:
99
        indices = []
100
        zipped = zip(image_size, patch_size, patch_overlap)
101
        for im_size_dim, patch_size_dim, patch_overlap_dim in zipped:
102
            end = im_size_dim + 1 - patch_size_dim
103
            step = patch_size_dim - patch_overlap_dim
104
            indices_dim = list(range(0, end, step))
105
            if im_size_dim % step:
106
                indices_dim.append(im_size_dim - patch_size_dim)
107
            indices.append(indices_dim)
108
        indices_ini = np.array(np.meshgrid(*indices)).reshape(3, -1).T
109
        indices_ini = np.unique(indices_ini, axis=0)
110
        indices_fin = indices_ini + np.array(patch_size)
111
        locations = np.hstack((indices_ini, indices_fin))
112
        return np.array(sorted(locations.tolist()))
113