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

GridAggregator.add_batch()   A

Complexity

Conditions 2

Size

Total Lines 29
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 18
nop 3
dl 0
loc 29
rs 9.5
c 0
b 0
f 0
1
import warnings
2
from typing import Tuple
3
import torch
4
import numpy as np
5
from ...torchio import TypeData, CHANNELS_DIMENSION
6
from .grid_sampler import GridSampler
7
8
9
class GridAggregator:
10
    r"""Aggregate patches for dense inference.
11
12
    This class is typically used to build a volume made of batches after
13
    inference of patches extracted by a :py:class:`~torchio.data.GridSampler`.
14
15
    Args:
16
        sampler: Instance of :py:class:`~torchio.data.GridSampler` used to
17
            extract the patches.
18
19
    .. note:: Adapted from NiftyNet. See `this NiftyNet tutorial
20
        <https://niftynet.readthedocs.io/en/dev/window_sizes.html>`_ for more
21
        information about patch based sampling.
22
    """
23
    def __init__(self, sampler: GridSampler):
24
        sample = sampler.sample
25
        self.volume_padded = sampler.padding_mode is not None
26
        self.spatial_shape = sample.spatial_shape
27
        self._output_tensor = None
28
        self.patch_overlap = sampler.patch_overlap
29
30
    def crop_batch(
31
            self,
32
            batch: torch.Tensor,
33
            locations: np.ndarray,
34
            overlap: np.ndarray,
35
            ) -> Tuple[TypeData, np.ndarray]:
36
        border = np.array(overlap) // 2  # overlap is even in grid sampler
37
        crop_locations = locations.astype(int).copy()
38
        indices_ini, indices_fin = crop_locations[:, :3], crop_locations[:, 3:]
39
        num_locations = len(crop_locations)
40
41
        border_ini = np.tile(border, (num_locations, 1))
42
        border_fin = border_ini.copy()
43
        # Do not crop patches at the border of the volume
44
        # Unless we're padding the volume in the grid sampler. In that case,
45
        # it doesn't matter if we don't crop patches at the border, because the
46
        # output volume will be cropped
47
        if not self.volume_padded:
48
            mask_border_ini = indices_ini == 0
49
            border_ini[mask_border_ini] = 0
50
            for axis, size in enumerate(self.spatial_shape):
51
                mask_border_fin = indices_fin[:, axis] == size
52
                border_fin[mask_border_fin, axis] = 0
53
54
        indices_ini += border_ini
55
        indices_fin -= border_fin
56
57
        crop_shapes = indices_fin - indices_ini
58
        patch_shape = batch.shape[2:]  # ignore batch and channels dim
59
        cropped_patches = []
60
        for patch, crop_shape in zip(batch, crop_shapes):
61
            diff = patch_shape - crop_shape
62
            left = (diff / 2).astype(int)
63
            i_ini, j_ini, k_ini = left
64
            i_fin, j_fin, k_fin = left + crop_shape
65
            cropped_patch = patch[:, i_ini:i_fin, j_ini:j_fin, k_ini:k_fin]
66
            cropped_patches.append(cropped_patch)
67
        return cropped_patches, crop_locations
68
69
    def initialize_output_tensor(self, batch: torch.Tensor) -> None:
70
        if self._output_tensor is not None:
71
            return
72
        num_channels = batch.shape[CHANNELS_DIMENSION]
73
        self._output_tensor = torch.zeros(
74
            num_channels,
75
            *self.spatial_shape,
76
            dtype=batch.dtype,
77
        )
78
79
    def add_batch(
80
            self,
81
            batch_tensor: torch.Tensor,
82
            locations: torch.Tensor,
83
            ) -> None:
84
        """Add batch processed by a CNN to the output prediction volume.
85
86
        Args:
87
            batch_tensor: 5D tensor, typically the output of a convolutional
88
                neural network, e.g. ``batch['image'][torchio.DATA]``.
89
            locations: 2D tensor with shape :math:`(B, 6)` representing the
90
                patch indices in the original image. They are typically
91
                extracted using ``batch[torchio.LOCATION]``.
92
        """
93
        batch = batch_tensor.cpu()
94
        locations = locations.cpu().numpy()
95
        self.initialize_output_tensor(batch)
96
        cropped_patches, crop_locations = self.crop_batch(
97
            batch,
98
            locations,
99
            self.patch_overlap,
100
        )
101
        for patch, crop_location in zip(cropped_patches, crop_locations):
102
            i_ini, j_ini, k_ini, i_fin, j_fin, k_fin = crop_location
103
            self._output_tensor[
104
                :,
105
                i_ini:i_fin,
106
                j_ini:j_fin,
107
                k_ini:k_fin] = patch
108
109
    def get_output_tensor(self) -> torch.Tensor:
110
        """Get the aggregated volume after dense inference."""
111
        if self._output_tensor.dtype == torch.int64:
112
            message = (
113
                'Medical image frameworks such as ITK do not support int64.'
114
                ' Casting to int32...'
115
            )
116
            warnings.warn(message)
117
            self._output_tensor = self._output_tensor.type(torch.int32)
118
        if self.volume_padded:
119
            from ...transforms import Crop
120
            border = self.patch_overlap // 2
121
            cropping = border.repeat(2)
122
            crop = Crop(cropping)
123
            return crop(self._output_tensor)
124
        else:
125
            return self._output_tensor
126