forked from mlcommons/GaNDLF
-
Notifications
You must be signed in to change notification settings - Fork 1
/
gandlf_padder
227 lines (195 loc) · 8.87 KB
/
gandlf_padder
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
#!usr/bin/env python
# -*- coding: utf-8 -*-
import os, argparse, sys
from pathlib import Path
from datetime import date
import numpy as np
import SimpleITK as sitk
from GANDLF.utils import parseTrainingCSV
from GANDLF.parseConfig import parseConfig
from GANDLF.data.ImagesFromDataFrame import global_preprocessing_dict
import torchio
def main():
copyrightMessage = (
"Contact: [email protected]\n\n"
+ "This program is NOT FDA/CE approved and NOT intended for clinical use.\nCopyright (c) "
+ str(date.today().year)
+ " University of Pennsylvania. All rights reserved."
)
parser = argparse.ArgumentParser(
prog="GANDLF_Padder",
formatter_class=argparse.RawTextHelpFormatter,
description="Generate training/inference data which are padded to reduce RAM footprint during training.\n\n"
+ copyrightMessage,
)
parser.add_argument(
"-config",
type=str,
help="The configuration file (contains all the information related to the training/inference session), this is read from 'output' during inference",
required=True,
)
parser.add_argument(
"-data",
type=str,
help="Data csv file that is used for training/inference; can also take a comma-separate training-validatation pre-split CSV",
required=True,
)
parser.add_argument(
"-output",
type=str,
help="Output directory to save intermediate files and model weights",
required=True,
)
parser.add_argument(
"-labelPad",
type=str,
default="constant",
help="Padding type for labels, defaults to 'constant:0' [full list: https://numpy.org/doc/stable/reference/generated/numpy.pad.html]",
required=False,
)
args = parser.parse_args()
Path(args.output).mkdir(parents=True, exist_ok=True)
# read the csv
dataframe, headers = parseTrainingCSV(
args.data, train=False
) # don't care if the dataframe gets shuffled or not
parameters = parseConfig(args.config)
# csv headers
channelHeaders = headers["channelHeaders"]
labelHeader = headers["labelHeader"]
subjectIDHeader = headers["subjectIDHeader"]
psize = parameters["psize"]
if "verbose" in parameters:
verbose = parameters["verbose"]
else:
verbose = False
num_row, num_col = dataframe.shape
dataframe.columns = range(0, num_col)
dataframe.index = range(0, num_row)
preprocessing = parameters["data_preprocessing"]
for patient in range(num_row):
# We need this dict for storing the meta data for each subject
# such as different image modalities, labels, any other data
subject_dict = {}
subject_dict_to_write = {}
subject_dict_label = {}
subject_dict["subject_id"] = dataframe[subjectIDHeader][patient]
subject_dict_to_write["subject_id"] = subject_dict["subject_id"]
current_output_dir = os.path.join(args.output, subject_dict["subject_id"])
Path(current_output_dir).mkdir(parents=True, exist_ok=True)
skip_subject = False
# iterating through the channels/modalities/timepoints of the subject
for channel in channelHeaders:
# sanity check for malformed csv
if not os.path.isfile(str(dataframe[channel][patient])):
skip_subject = True
# assigning the dict key to the channel
subject_dict[str(channel)] = torchio.Image(
str(dataframe[channel][patient]), type=torchio.INTENSITY
)
if labelHeader is not None:
if not os.path.isfile(str(dataframe[labelHeader][patient])):
skip_subject = True
subject_dict_label["label"] = torchio.Image(
str(dataframe[labelHeader][patient]), type=torchio.LABEL
)
# skip subject the condition was tripped
if not skip_subject:
if verbose:
print(
"Started padding images for '" + subject_dict["subject_id"] + "'",
flush=True,
)
# Initializing the subject object using the dict
subject = torchio.Subject(subject_dict)
subject_label = torchio.Subject(subject_dict_label)
# first, we want to do the resampling, if it is present - required for inference as well
resampler = None
if "resample" in preprocessing:
if "resolution" in preprocessing["resample"]:
# resample_split = str(aug).split(':')
resample_values = tuple(
np.array(preprocessing["resample"]["resolution"]).astype(
np.float
)
)
if len(resample_values) == 2:
resample_values = tuple(np.append(resample_values, 1))
resampler = torchio.transforms.Resample(resample_values)
# next, we want to do the intensity normalize - required for inference as well
normalizer = None
if "normalize" in preprocessing:
normalizer = global_preprocessing_dict["normalize"]
elif "normalize_nonZero" in preprocessing:
normalizer = global_preprocessing_dict["normalize_nonZero"]
elif "normalize_nonZero_masked" in preprocessing:
normalizer = global_preprocessing_dict["normalize_nonZero_masked"]
# apply normalizer to only image and label
if normalizer is not None:
subject = normalizer(subject)
# apply a different padding mode to image and label (so that label information is not duplicated)
psize_pad = list(np.asarray(np.ceil(np.divide(psize, 2)), dtype=int))
padder = torchio.transforms.Pad(
psize_pad, padding_mode="symmetric"
) # for modes: https://numpy.org/doc/stable/reference/generated/numpy.pad.html
subject = padder(subject)
if labelHeader is not None:
if verbose:
print(
"Applying specialized padding to label image and then generating crops based on it",
flush=True,
)
padder_label = torchio.transforms.Pad(
psize_pad, padding_mode=args.labelPad
) # for modes: https://numpy.org/doc/stable/reference/generated/numpy.pad.html
subject_label = padder_label(subject_label)
# now combine the label with the original subject dictionary to do sampling
subject["label"] = subject_label["label"]
# apply resampling to both image(s) and label
if resampler is not None:
subject = resampler(subject)
sampler = torchio.data.LabelSampler(psize)
generator = sampler(subject, num_patches=1)
for patch in generator:
for channel in channelHeaders:
subject_dict_to_write[str(channel)] = patch[str(channel)]
subject_dict_to_write["label"] = patch["label"]
else:
subject_dict_to_write = subject
# apply resampling to image(s)
if resampler is not None:
subject_dict_to_write = resampler(subject_dict_to_write)
if verbose:
print(
"Writing padded images for '" + subject_dict["subject_id"] + "'",
flush=True,
)
# write new images
for key in channelHeaders:
pth = Path(subject_dict_to_write[str(key)]["path"])
image_to_write = subject_dict_to_write[str(key)].as_sitk()
image_file = os.path.join(current_output_dir, pth.name)
print("image_file:", image_file)
print("image_file.size():", image_to_write.GetSize())
if not os.path.isfile(image_file):
if verbose:
print("Writing", image_file)
try:
sitk.WriteImage(image_to_write, image_file)
except:
print("Could not write:", image_file, file=sys.stderr, flush=True)
# now try to write the label
if "label" in subject_dict_to_write:
pth = Path(subject_dict_to_write["label"]["path"])
image_to_write = subject_dict_to_write["label"].as_sitk()
image_file = os.path.join(current_output_dir, pth.name)
if not os.path.isfile(image_file):
if verbose:
print("Writing", image_file)
try:
sitk.WriteImage(image_to_write, image_file)
except:
print("Could not write:", image_file, file=sys.stderr, flush=True)
# main function
if __name__ == "__main__":
main()