TestCropOrPad.test_only_crop()   A
last analyzed

Complexity

Conditions 2

Size

Total Lines 7
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 7
nop 1
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
import numpy as np
2
import pytest
3
4
import torchio as tio
5
6
from ...utils import TorchioTestCase
7
8
9
class TestCropOrPad(TorchioTestCase):
10
    """Tests for `CropOrPad`."""
11
12
    def test_no_changes(self):
13
        sample_t1 = self.sample_subject['t1']
14
        shape = sample_t1.spatial_shape
15
        transform = tio.CropOrPad(shape)
16
        transformed = transform(self.sample_subject)
17
        self.assert_tensor_equal(sample_t1.data, transformed['t1'].data)
18
        self.assert_tensor_equal(sample_t1.affine, transformed['t1'].affine)
19
20
    def test_no_changes_mask(self):
21
        sample_t1 = self.sample_subject['t1']
22
        sample_mask = self.sample_subject['label'].data
23
        sample_mask *= 0
24
        shape = sample_t1.spatial_shape
25
        transform = tio.CropOrPad(shape, mask_name='label')
26
        with pytest.warns(RuntimeWarning):
27
            transformed = transform(self.sample_subject)
28
        for key in transformed:
29
            image = self.sample_subject[key]
30
            self.assert_tensor_equal(image.data, transformed[key].data)
31
            self.assert_tensor_equal(image.affine, transformed[key].affine)
32
33
    def test_different_shape(self):
34
        shape = self.sample_subject['t1'].spatial_shape
35
        target_shape = 9, 21, 30
36
        transform = tio.CropOrPad(target_shape)
37
        transformed = transform(self.sample_subject)
38
        for key in transformed:
39
            result_shape = transformed[key].spatial_shape
40
            self.assertNotEqual(shape, result_shape)
41
42
    def test_shape_right(self):
43
        target_shape = 9, 21, 30
44
        transform = tio.CropOrPad(target_shape)
45
        transformed = transform(self.sample_subject)
46
        for key in transformed:
47
            result_shape = transformed[key].spatial_shape
48
            assert target_shape == result_shape
49
50
    def test_only_pad(self):
51
        target_shape = 11, 22, 30
52
        transform = tio.CropOrPad(target_shape)
53
        transformed = transform(self.sample_subject)
54
        for key in transformed:
55
            result_shape = transformed[key].spatial_shape
56
            assert target_shape == result_shape
57
58
    def test_only_crop(self):
59
        target_shape = 9, 18, 30
60
        transform = tio.CropOrPad(target_shape)
61
        transformed = transform(self.sample_subject)
62
        for key in transformed:
63
            result_shape = transformed[key].spatial_shape
64
            assert target_shape == result_shape
65
66
    def test_shape_negative(self):
67
        with pytest.raises(ValueError):
68
            tio.CropOrPad(-1)
69
70
    def test_shape_float(self):
71
        with pytest.raises(ValueError):
72
            tio.CropOrPad(2.5)
73
74
    def test_shape_string(self):
75
        with pytest.raises(ValueError):
76
            tio.CropOrPad('')
77
78
    def test_shape_one(self):
79
        transform = tio.CropOrPad(1)
80
        transformed = transform(self.sample_subject)
81
        for key in transformed:
82
            result_shape = transformed[key].spatial_shape
83
            assert result_shape == (1, 1, 1)
84
85
    def test_wrong_mask_name(self):
86
        cop = tio.CropOrPad(1, mask_name='wrong')
87
        with pytest.warns(RuntimeWarning):
88
            cop(self.sample_subject)
89
90
    def test_empty_mask(self):
91
        target_shape = 8, 22, 30
92
        transform = tio.CropOrPad(target_shape, mask_name='label')
93
        mask = self.sample_subject['label'].data
94
        mask *= 0
95
        with pytest.warns(RuntimeWarning):
96
            transform(self.sample_subject)
97
98
    def mask_only(self, target_shape):
99
        transform = tio.CropOrPad(target_shape, mask_name='label')
100
        mask = self.sample_subject['label'].data
101
        mask *= 0
102
        mask[0, 4:6, 5:8, 3:7] = 1
103
        transformed = transform(self.sample_subject)
104
        shapes = []
105
        for key in transformed:
106
            result_shape = transformed[key].spatial_shape
107
            shapes.append(result_shape)
108
        set_shapes = set(shapes)
109
        message = f'Images have different shapes: {set_shapes}'
110
        assert len(set_shapes) == 1, message
111
        for key in transformed:
112
            result_shape = transformed[key].spatial_shape
113
            assert target_shape == result_shape, f'Wrong shape for image: {key}'
114
115
    def test_mask_only_pad(self):
116
        self.mask_only((11, 22, 30))
117
118
    def test_mask_only_crop(self):
119
        self.mask_only((9, 18, 30))
120
121
    def test_center_mask(self):
122
        """The mask bounding box and the input image have the same center."""
123
        target_shape = 8, 22, 30
124
        transform_center = tio.CropOrPad(target_shape)
125
        transform_mask = tio.CropOrPad(target_shape, mask_name='label')
126
        mask = self.sample_subject['label'].data
127
        mask *= 0
128
        mask[0, 4:6, 9:11, 14:16] = 1
129
        transformed_center = transform_center(self.sample_subject)
130
        transformed_mask = transform_mask(self.sample_subject)
131
        zipped = zip(
132
            transformed_center.values(),
133
            transformed_mask.values(),
134
            strict=True,
135
        )
136
        for image_center, image_mask in zipped:
137
            self.assert_tensor_equal(
138
                image_center.data,
139
                image_mask.data,
140
                msg='Data is different after cropping',
141
            )
142
            self.assert_tensor_equal(
143
                image_center.affine,
144
                image_mask.affine,
145
                msg='Physical position is different after cropping',
146
            )
147
148
    def test_mask_corners(self):
149
        """The mask bounding box and the input image have the same center."""
150
        target_shape = 8, 22, 30
151
        transform_center = tio.CropOrPad(target_shape)
152
        transform_mask = tio.CropOrPad(
153
            target_shape,
154
            mask_name='label',
155
        )
156
        mask = self.sample_subject['label'][tio.DATA]
157
        mask *= 0
158
        mask[0, 0, 0, 0] = 1
159
        mask[0, -1, -1, -1] = 1
160
        transformed_center = transform_center(self.sample_subject)
161
        transformed_mask = transform_mask(self.sample_subject)
162
        zipped = zip(
163
            transformed_center.values(),
164
            transformed_mask.values(),
165
            strict=True,
166
        )
167
        for image_center, image_mask in zipped:
168
            self.assert_tensor_equal(
169
                image_center.data,
170
                image_mask.data,
171
                msg='Data is different after cropping',
172
            )
173
            self.assert_tensor_equal(
174
                image_center.affine,
175
                image_mask.affine,
176
                msg='Physical position is different after cropping',
177
            )
178
179
    def test_2d(self):
180
        # https://github.com/TorchIO-project/torchio/issues/434
181
        image = np.random.rand(1, 16, 16, 1)
182
        mask = np.zeros_like(image, dtype=bool)
183
        mask[0, 7, 0] = True
184
        subject = tio.Subject(
185
            image=tio.ScalarImage(tensor=image),
186
            mask=tio.LabelMap(tensor=mask),
187
        )
188
        transform = tio.CropOrPad((12, 12, 1), mask_name='mask')
189
        transformed = transform(subject)
190
        assert transformed.shape == (1, 12, 12, 1)
191
192
    def test_no_target_no_mask(self):
193
        with pytest.raises(ValueError):
194
            tio.CropOrPad()
195
196
    def test_labels_but_no_mask(self):
197
        with pytest.raises(ValueError):
198
            tio.CropOrPad(target_shape=(3, 4, 5), labels=[2, 3])
199
200
    def test_no_target(self):
201
        crop_with_mask = tio.CropOrPad(mask_name='label')
202
        crop_with_mask(self.sample_subject)
203
204
    def test_persistent_bounds_params(self):
205
        # https://github.com/TorchIO-project/torchio/issues/757
206
        shape = (1, 5, 5, 5)
207
        mask_a = np.zeros(shape)
208
        mask_a[0, 2, 2, 2] = 1
209
        mask_b = mask_a.copy()
210
        mask_b[0, 1:4, 1:4, 1:4] = 1
211
        tensor = np.ones(shape)
212
        image_a = tio.ScalarImage(tensor=tensor)
213
        mask_a = tio.LabelMap(tensor=mask_a)
214
        subject_a = tio.Subject(image=image_a, mask=mask_a)
215
        image_b = tio.ScalarImage(tensor=tensor)
216
        mask_b = tio.LabelMap(tensor=mask_b)
217
        subject_b = tio.Subject(image=image_b, mask=mask_b)
218
        crop = tio.CropOrPad(mask_name='mask')
219
        for _ in range(2):
220
            shape_a = crop(subject_a).image.shape
221
            shape_b = crop(subject_b).image.shape
222
            assert shape_a != shape_b
223
224
    def test_only_crop_pad_true(self):
225
        with pytest.raises(ValueError):
226
            tio.CropOrPad((1, 2, 3), only_crop=True, only_pad=True)
227
228
    def test_only_pad_true(self):
229
        target_shape = 9, 21, 30
230
        orig_shape = self.sample_subject['t1'].spatial_shape
231
        expected_shape = tuple(
232
            t if t > o else o for o, t in zip(orig_shape, target_shape, strict=True)
233
        )
234
        transform = tio.CropOrPad(target_shape, only_pad=True)
235
        transformed = transform(self.sample_subject)
236
        for key in transformed:
237
            result_shape = transformed[key].spatial_shape
238
            assert result_shape == expected_shape
239
240
    def test_only_crop_true(self):
241
        target_shape = 9, 21, 30
242
        orig_shape = self.sample_subject['t1'].spatial_shape
243
        expected_shape = tuple(
244
            t if t < o else o for o, t in zip(orig_shape, target_shape, strict=True)
245
        )
246
        transform = tio.CropOrPad(target_shape, only_crop=True)
247
        transformed = transform(self.sample_subject)
248
        for key in transformed:
249
            result_shape = transformed[key].spatial_shape
250
            assert result_shape == expected_shape
251