-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransforms.py
192 lines (172 loc) · 6.63 KB
/
transforms.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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
import numpy as np
from monai.transforms import CropForegroundd, NormalizeIntensity, SpatialCrop
from monai.transforms.compose import MapTransform
from monai.transforms.utils import generate_spatial_bounding_box
from skimage.transform import resize
class PreprocessAnisotropic(MapTransform):
"""
This transform class takes NNUNet's preprocessing method for reference.
That code is in:
https://github.com/MIC-DKFZ/nnUNet/blob/master/nnunet/preprocessing/preprocessing.py
"""
def __init__(
self,
keys,
clip_values,
pixdim,
normalize_values,
model_mode,
) -> None:
super().__init__(keys)
self.keys = keys
self.low = clip_values[0]
self.high = clip_values[1]
self.target_spacing = pixdim
self.mean = normalize_values[0]
self.std = normalize_values[1]
self.training = False
self.crop_foreg = CropForegroundd(keys=["image", "label"], source_key="image")
self.normalize_intensity = NormalizeIntensity(nonzero=True, channel_wise=True)
self.training = model_mode == "fit"
def calculate_new_shape(self, spacing, shape):
spacing_ratio = np.array(spacing) / np.array(self.target_spacing)
new_shape = (spacing_ratio * np.array(shape)).astype(int).tolist()
return new_shape
@staticmethod
def check(spacing):
return np.max(spacing) / np.min(spacing) >= 3
def check_anisotrophy(self, spacing):
return check(spacing) or check(self.target_spacing)
@staticmethod
def resample_image(image, shape, anisotrophy_flag):
resized_channels = []
if anisotrophy_flag:
for image_c in image:
resized_slices = []
for i in range(image_c.shape[-1]):
image_c_2d_slice = image_c[:, :, i]
image_c_2d_slice = resize(
image_c_2d_slice,
shape[:-1],
order=3,
mode="edge",
cval=0,
clip=True,
anti_aliasing=False,
)
resized_slices.append(image_c_2d_slice)
resized = np.stack(resized_slices, axis=-1)
resized = resize(
resized,
shape,
order=0,
mode="constant",
cval=0,
clip=True,
anti_aliasing=False,
)
resized_channels.append(resized)
else:
for image_c in image:
resized = resize(
image_c,
shape,
order=3,
mode="edge",
cval=0,
clip=True,
anti_aliasing=False,
)
resized_channels.append(resized)
resized = np.stack(resized_channels, axis=0)
return resized
@staticmethod
def resample_label(label, shape, anisotrophy_flag):
reshaped = np.zeros(shape, dtype=np.uint8)
n_class = np.max(label)
if anisotrophy_flag:
shape_2d = shape[:-1]
depth = label.shape[-1]
reshaped_2d = np.zeros((*shape_2d, depth), dtype=np.uint8)
for class_ in range(1, int(n_class) + 1):
for depth_ in range(depth):
mask = label[0, :, :, depth_] == class_
resized_2d = resize(
mask.astype(float),
shape_2d,
order=1,
mode="edge",
cval=0,
clip=True,
anti_aliasing=False,
)
reshaped_2d[:, :, depth_][resized_2d >= 0.5] = class_
for class_ in range(1, int(n_class) + 1):
mask = reshaped_2d == class_
resized = resize(
mask.astype(float),
shape,
order=0,
mode="constant",
cval=0,
clip=True,
anti_aliasing=False,
)
reshaped[resized >= 0.5] = class_
else:
for class_ in range(1, int(n_class) + 1):
mask = label[0] == class_
resized = resize(
mask.astype(float),
shape,
order=1,
mode="edge",
cval=0,
clip=True,
anti_aliasing=False,
)
reshaped[resized >= 0.5] = class_
reshaped = np.expand_dims(reshaped, 0)
return reshaped
def __call__(self, data):
# load data
d = dict(data)
image = d["image"]
image_spacings = d["image_meta_dict"]["pixdim"][1:4].tolist()
if "label" in self.keys:
label = d["label"]
label[label < 0] = 0
if self.training:
# only task 04 does not be impacted
cropped_data = self.crop_foreg({"image": image, "label": label})
image, label = cropped_data["image"], cropped_data["label"]
else:
d["original_shape"] = np.array(image.shape[1:])
box_start, box_end = generate_spatial_bounding_box(image)
image = SpatialCrop(roi_start=box_start, roi_end=box_end)(image)
d["bbox"] = np.vstack([box_start, box_end])
d["crop_shape"] = np.array(image.shape[1:])
original_shape = image.shape[1:]
# calculate shape
resample_flag = False
anisotrophy_flag = False
if self.target_spacing != image_spacings:
# resample
resample_flag = True
resample_shape = self.calculate_new_shape(image_spacings, original_shape)
anisotrophy_flag = self.check_anisotrophy(image_spacings)
image = self.resample_image(image, resample_shape, anisotrophy_flag)
if self.training:
label = self.resample_label(label, resample_shape, anisotrophy_flag)
d["resample_flag"] = resample_flag
d["anisotrophy_flag"] = anisotrophy_flag
# clip image for CT dataset
if self.low != 0 or self.high != 0:
image = np.clip(image, self.low, self.high)
image = (image - self.mean) / self.std
else:
image = self.normalize_intensity(image.copy())
d["image"] = image
if "label" in self.keys:
d["label"] = label
return d