forked from Project-MONAI/MONAI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcroppers.py
172 lines (154 loc) · 7.92 KB
/
croppers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# Copyright (c) MONAI Consortium
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations
import unittest
from copy import deepcopy
import numpy as np
from monai.data.meta_tensor import MetaTensor
from monai.transforms import Randomizable
from monai.transforms.lazy.functional import apply_pending
from monai.transforms.transform import MapTransform
from tests.test_utils import TEST_NDARRAYS_ALL, assert_allclose
class CropTest(unittest.TestCase):
@staticmethod
def get_arr(shape):
return np.random.randint(100, size=shape).astype(float)
def crop_test(self, input_param, input_shape, expected_shape, same_area=None):
base_comparison = None
input_image = self.get_arr(input_shape)
for im_type in TEST_NDARRAYS_ALL:
with self.subTest(im_type=im_type):
# input parameters, such as roi_start can be numpy, torch, list etc.
for param_type in TEST_NDARRAYS_ALL + (None,):
with self.subTest(param_type=param_type):
input_param_mod = deepcopy(input_param)
if param_type is not None:
for k in ("roi_start", "roi_end", "roi_center", "roi_size", "roi_scale"):
if k in input_param:
input_param_mod[k] = param_type(input_param[k])
im = im_type(input_image)
cropper = self.Cropper(**input_param_mod)
is_map = isinstance(cropper, MapTransform)
input_data = {"img": im} if is_map else im
result = cropper(input_data)
out_im = result["img"] if is_map else result
self.assertIsInstance(out_im, MetaTensor)
self.assertTupleEqual(out_im.shape, expected_shape)
if same_area is not None:
assert_allclose(out_im, im[same_area], type_test=False)
# check result is the same regardless of input type
if base_comparison is None:
base_comparison = out_im
else:
assert_allclose(out_im, base_comparison)
# test inverse
inv = cropper.inverse(result)
inv_im = inv["img"] if is_map else inv
self.assertIsInstance(inv_im, MetaTensor)
if same_area is not None:
assert_allclose(inv_im[same_area], im[same_area], type_test=False)
self.assertEqual(inv_im.applied_operations, [])
def crop_test_value(self, input_param, input_arr, expected_array):
cropper = self.Cropper(**input_param)
is_map = isinstance(cropper, MapTransform)
for im_type in TEST_NDARRAYS_ALL:
with self.subTest(im_type=im_type):
im = im_type(input_arr)
input_data = {"img": im} if is_map else im
result = self.Cropper(**input_param)(input_data)
out_im = result["img"] if is_map else result
self.assertIsInstance(out_im, MetaTensor)
assert_allclose(out_im, expected_array, type_test=False)
def multi_inverse(self, input_shape, init_params):
input_data = np.arange(np.prod(input_shape)).reshape(*input_shape) + 1
xform = self.Cropper(**init_params)
xform.set_random_state(1234)
out = xform(input_data)
if "num_samples" in init_params:
self.assertEqual(len(out), init_params["num_samples"])
inv = xform.inverse(out)
self.assertIsInstance(inv, MetaTensor)
self.assertEqual(inv.applied_operations, [])
self.assertTrue("patch_index" not in inv.meta)
self.assertTupleEqual(inv.shape, input_shape)
inv_np = inv.numpy()
# get list of all numbers that exist inside the crops
uniques = set()
for o in out:
uniques.update(set(o.flatten().tolist()))
# make sure that
for i in uniques:
a = np.where(input_data == i)
b = np.where(inv_np == i)
self.assertTupleEqual(a, b)
# there should be as many zeros as elements missing from uniques
missing = input_data.size - len(uniques)
self.assertEqual((inv_np == 0).sum(), missing)
def crop_test_pending_ops(self, input_param, input_shape, align_corners=False):
crop_fn = self.Cropper(**input_param)
data = self.get_arr(input_shape)
is_map = isinstance(crop_fn, MapTransform)
im = MetaTensor(data, meta={"a": "b", "affine": np.eye(len(input_shape))})
input_data = {"img": im} if is_map else im
# non-lazy
result_non_lazy = crop_fn(input_data)
expected = result_non_lazy["img"] if is_map else result_non_lazy
self.assertIsInstance(expected, MetaTensor)
# lazy
crop_fn.lazy = True
pending_result = crop_fn(input_data)
pending_result = pending_result["img"] if is_map else pending_result
self.assertIsInstance(pending_result, MetaTensor)
assert_allclose(pending_result.peek_pending_affine(), expected.affine)
assert_allclose(pending_result.peek_pending_shape(), expected.shape[1:])
# only support nearest
overrides = {"mode": "nearest", "align_corners": align_corners}
result = apply_pending(pending_result, overrides=overrides)[0]
# compare
assert_allclose(result, expected, rtol=1e-5)
if isinstance(result, MetaTensor) and not isinstance(crop_fn, MapTransform):
crop_fn.lazy = False
inverted = crop_fn.inverse(result)
self.assertTrue((not inverted.applied_operations) and (not inverted.pending_operations))
self.assertEqual(inverted.shape, im.shape)
def crop_test_combine_ops(self, funcs, input_shape):
_funcs = []
for func in funcs:
for _func, _params in func.items():
_funcs.append(_func(**_params))
is_map = isinstance(_funcs[0], MapTransform)
data = self.get_arr(input_shape)
im = MetaTensor(data, meta={"a": "b", "affine": np.eye(len(input_shape))})
input_data = {"img": im} if is_map else im
# non-lazy
non_lazy_result = input_data
for _func in _funcs:
if isinstance(_func, Randomizable):
_func.set_random_state(seed=123)
non_lazy_result = _func(non_lazy_result)
expected = non_lazy_result["img"] if is_map else non_lazy_result
self.assertIsInstance(expected, MetaTensor)
# lazy
pending_result = input_data
for _func in _funcs:
_func.lazy = True
if isinstance(_func, Randomizable):
_func.set_random_state(seed=123)
pending_result = _func(pending_result)
pending_result = pending_result["img"] if is_map else pending_result
self.assertIsInstance(pending_result, MetaTensor)
assert_allclose(pending_result.peek_pending_affine(), expected.affine)
assert_allclose(pending_result.peek_pending_shape(), expected.shape[1:])
# TODO: mode="bilinear" may report error
overrides = {"mode": "nearest", "align_corners": False}
result = apply_pending(pending_result, overrides=overrides)[0]
# compare
assert_allclose(result, expected, rtol=1e-5)