Passed
Pull Request — master (#182)
by Fernando
57s
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
        # Do not crop patches at the border of the volume
42
        # Unless we're padding the volume in the grid sampler. In that case,
43
        # it doesn't matter if we don't crop patches at the border, because the
44
        # output volume will be cropped
45
        if not self.volume_padded:
46
            border_ini = np.tile(border, (num_locations, 1))
47
            border_fin = border_ini.copy()
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
            indices_ini += border_ini
54
            indices_fin -= border_fin
55
56
        crop_shapes = indices_fin - indices_ini
57
        patch_shape = batch.shape[2:]  # ignore batch and channels dim
58
        cropped_patches = []
59
        for patch, crop_shape in zip(batch, crop_shapes):
60
            diff = patch_shape - crop_shape
61
            left = (diff / 2).astype(int)
62
            i_ini, j_ini, k_ini = left
63
            i_fin, j_fin, k_fin = left + crop_shape
64
            cropped_patch = patch[:, i_ini:i_fin, j_ini:j_fin, k_ini:k_fin]
65
            cropped_patches.append(cropped_patch)
66
        return cropped_patches, crop_locations
67
68
    def initialize_output_tensor(self, batch: torch.Tensor) -> None:
69
        if self._output_tensor is not None:
70
            return
71
        num_channels = batch.shape[CHANNELS_DIMENSION]
72
        self._output_tensor = torch.zeros(
73
            num_channels,
74
            *self.spatial_shape,
75
            dtype=batch.dtype,
76
        )
77
78
    def add_batch(
79
            self,
80
            batch_tensor: torch.Tensor,
81
            locations: torch.Tensor,
82
            ) -> None:
83
        """Add batch processed by a CNN to the output prediction volume.
84
85
        Args:
86
            batch_tensor: 5D tensor, typically the output of a convolutional
87
                neural network, e.g. ``batch['image'][torchio.DATA]``.
88
            locations: 2D tensor with shape :math:`(B, 6)` representing the
89
                patch indices in the original image. They are typically
90
                extracted using ``batch[torchio.LOCATION]``.
91
        """
92
        batch = batch_tensor.cpu()
93
        locations = locations.cpu().numpy()
94
        self.initialize_output_tensor(batch)
95
        cropped_patches, crop_locations = self.crop_batch(
96
            batch,
97
            locations,
98
            self.patch_overlap,
99
        )
100
        for patch, crop_location in zip(cropped_patches, crop_locations):
101
            i_ini, j_ini, k_ini, i_fin, j_fin, k_fin = crop_location
102
            self._output_tensor[
103
                :,
104
                i_ini:i_fin,
105
                j_ini:j_fin,
106
                k_ini:k_fin] = patch
107
108
    def get_output_tensor(self) -> torch.Tensor:
109
        """Get the aggregated volume after dense inference."""
110
        if self._output_tensor.dtype == torch.int64:
111
            message = (
112
                'Medical image frameworks such as ITK do not support int64.'
113
                ' Casting to int32...'
114
            )
115
            warnings.warn(message)
116
            self._output_tensor = self._output_tensor.type(torch.int32)
117
        if self.volume_padded:
118
            from ...transforms import Crop
119
            border = self.patch_overlap // 2
120
            cropping = border.repeat(2)
121
            crop = Crop(cropping)
122
            return crop(self._output_tensor)
123
        else:
124
            return self._output_tensor
125