-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathlibra.py
428 lines (336 loc) · 19.3 KB
/
libra.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
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
#!/usr/bin/python3
import warnings
warnings.filterwarnings("ignore")
from time import time
from glob import glob
from copy import deepcopy
from subprocess import call
from termcolor import colored
import os, pdb, multiprocessing
from get_info import get_info_from_network
from initialize_variables import set_argparse, get_variables
from needed_functions_CPU import run_loop_multi_cpu_just_org_image
from needed_functions_CPU import run_loop_multi_cpu_pec, run_loop_multi_cpu
from needed_functions_CPU import run_loop_multi_cpu_post, run_loop_multi_cpu_denisty_map
################################################################################
################################################################################
class LIBRA(object): # The main class
def __init__(self):
self.version = "version-1.0"
############################################################################
############################################################################
def parse_args(self, argv=None):
args = set_argparse(argv)
self = get_variables(self, args)
if self.multi_cpu == 1:
self.number_cpu_cores = multiprocessing.cpu_count()
else:
self.number_cpu_cores = 1
self.core_multiplier = 1
self.number_of_threads = 1
self.number_cpu_cores = self.number_cpu_cores*self.number_of_threads
self.max_number_of_process = int(self.core_multiplier*self.number_cpu_cores)
self.Keys_txt_file_input = ['image_format', 'num_class', 'save_period',
'model', 'backbone', 'training_mode',
'flag_multi_class', 'A_Range', 'image_final_size']
self.Keys_object = self.Keys_txt_file_input #### this is to name the output keys/ keep it the same
self.saving_folder_name_net_pec_temp, folder_name = os.path.split(self.saving_folder_name_net_pec)
self.saving_folder_name_net_pec_temp = self.saving_folder_name_net_pec_temp+"_temp"
self.saving_folder_name_net_pec_temp = os.path.join(self.saving_folder_name_net_pec_temp, folder_name)
if self.num_gpu == 0:
self.test_batch_size = 1
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = ""
self.batch_size = self.test_batch_size
self.image_final_size = self.final_image_size
self.code_path = os.path.abspath(__file__)
self.code_path,C = os.path.split(self.code_path)
if not os.path.exists(self.output_path): os.makedirs(self.output_path)
self.T_Start = time()
############################################################################
############################################################################
def get_info_based_on_air_cnn(self):
print(colored("[INFO] Loading required info.", 'cyan'))
self.model_path = self.model_path_air
self = get_info_from_network(self, self.model_path,
self.Keys_txt_file_input, self.Keys_object)
############################################################################
############################################################################
def run_just_orginal_image_preprocessing(self):
print(colored("[INFO] Just original image preprocessing.", 'cyan'))
T_Start = time()
if self.input_data[-4:]!=".dcm":
self.Cases = sorted(glob(os.path.join(self.input_data, "*dcm")))
else:
self.Cases = [deepcopy(self.input_data)]
Image_Path = os.path.join(self.output_path, self.saving_folder_name_net_air)
if not(os.path.isdir(Image_Path)): os.makedirs(Image_Path)
if self.multi_cpu == 1:
batch_processes = []
Q = multiprocessing.Queue()
Total_processes = 0
for N, self.Case in enumerate(self.Cases):
p = multiprocessing.Process(target=run_loop_multi_cpu_just_org_image,
args=(self, self.Case, self.code_path, ))
batch_processes.append(p)
p.start()
if len(batch_processes)>self.number_cpu_cores or N+1 == len(self.Cases):
Total_processes += self.number_cpu_cores
for j in batch_processes:
j.join()
if Total_processes > self.max_number_of_process:
Q.close()
Q.join_thread()
Q = multiprocessing.Queue()
Total_processes = 0
batch_processes = []
else:
for self.Case in self.Cases:
Path, File = os.path.split(self.Case)
File = File[:-4]
call(["python3", os.path.join(self.code_path, "just_original_image_preprocessing.py"), "-i",
self.Case, "-o", self.output_path, "-if", self.image_format])
T_End = time()
print("[INFO] The total elapsed time (for all files in just original image preprocessing step): "+'\033[1m'+ \
colored(str(round(T_End-T_Start, 2)), 'red')+'\033[0m'+" seconds")
############################################################################
############################################################################
def run_air_preprocessing(self):
print(colored("[INFO] Air segmentation preprocessing.", 'cyan'))
T_Start = time()
if self.input_data[-4:]!=".dcm":
self.Cases = sorted(glob(os.path.join(self.input_data, "*dcm")))
else:
self.Cases = [deepcopy(self.input_data)]
Image_Path = os.path.join(self.output_path, self.saving_folder_name_net_air)
if not(os.path.isdir(Image_Path)): os.makedirs(Image_Path)
print("[INFO] Saving path for the summary of this step is "+Image_Path)
if self.multi_cpu == 1:
batch_processes = []
Q = multiprocessing.Queue()
Total_processes = 0
for N, self.Case in enumerate(self.Cases):
p = multiprocessing.Process(target=run_loop_multi_cpu,
args=(self, self.Case, self.code_path, ))
batch_processes.append(p)
p.start()
if len(batch_processes)>self.number_cpu_cores or N+1 == len(self.Cases):
Total_processes += self.number_cpu_cores
for j in batch_processes:
j.join()
if Total_processes > self.max_number_of_process:
Q.close()
Q.join_thread()
Q = multiprocessing.Queue()
Total_processes = 0
batch_processes = []
else:
for self.Case in self.Cases:
Path, File = os.path.split(self.Case)
File = File[:-4]
call(["python3", os.path.join(self.code_path, "preprocessing.py"), "-i",
self.Case, "-o", self.output_path, "-if", self.image_format,
"-po", self.print_off, "-sfn", self.saving_folder_name_net_air,
"-ar", str(self.A_Range), "-fis", str(self.final_image_size),
"-lsm", self.libra_segmentation_method, "-fpm", self.find_pacemaker])
T_End = time()
print("[INFO] The total elapsed time (for all files in air preprocessing step): "+'\033[1m'+ \
colored(str(round(T_End-T_Start, 2)), 'red')+'\033[0m'+" seconds")
############################################################################
############################################################################
def run_air_cnn(self):
from load_models import get_network_segmentation
from needed_functions_GPU import test_network_air
T_Start = time()
print(colored("[INFO] Air segmentation using CNN is started.", 'cyan'))
self = get_network_segmentation(self, self.model_path,
self.Keys_txt_file_input, self.Keys_object)
self = test_network_air(self)
T_End = time()
print("[INFO] The total elapsed time (for all files in air CNN step): "+'\033[1m'+ \
colored(str(round(T_End-T_Start, 2)), 'red')+'\033[0m'+" seconds")
print(colored("[INFO] Air segmentation using CNN is done.", 'green'))
############################################################################
############################################################################
def get_info_based_on_pec_cnn(self):
print(colored("[INFO] Loading required info.", 'cyan'))
self.model_path = self.model_path_pec
self = get_info_from_network(self, self.model_path,
self.Keys_txt_file_input, self.Keys_object)
############################################################################
############################################################################
def run_pec_preprocessing(self):
print(colored("[INFO] Preprocessing for breast vs pectroal segmentation.", 'cyan'))
T_Start = time()
Path_segmented_air = os.path.join(self.output_path, self.saving_folder_name_net_pec_temp)
if self.input_data[-4:]!=".dcm":
self.Cases = sorted(glob(os.path.join(Path_segmented_air, "*"+self.image_format)))
else:
_, file_name = os.path.split(self.input_data)
temp_path = os.path.join(Path_segmented_air, file_name[:-4]+
self.air_seg_prefix+self.image_format)
self.Cases = [temp_path]
Image_Path = os.path.join(self.output_path, self.saving_folder_name_net_pec)
if not(os.path.isdir(Image_Path)): os.makedirs(Image_Path)
print("[INFO] Saving path for the summary of this step is "+Image_Path)
if self.multi_cpu == 1:
batch_processes = []
Q = multiprocessing.Queue()
Total_processes = 0
for N, self.Case in enumerate(self.Cases):
p = multiprocessing.Process(target=run_loop_multi_cpu_pec,
args=(self, self.Case, self.code_path, ))
batch_processes.append(p)
p.start()
if len(batch_processes)>self.number_cpu_cores or N+1 == len(self.Cases):
Total_processes += self.number_cpu_cores
for j in batch_processes:
j.join()
if Total_processes > self.max_number_of_process:
Q.close()
Q.join_thread()
Q = multiprocessing.Queue()
Total_processes = 0
batch_processes = []
else:
for self.Case in self.Cases:
_, File = os.path.split(self.Case)
self.File = File[:File.find(self.air_seg_prefix)]
call(["python3", os.path.join(self.code_path, "preprocessing_pec.py"),
"-i", self.Case, "-if", self.image_format, "-cn", self.File,
"-po", self.print_off, "-sfn", self.saving_folder_name_net_pec,
"-ar", str(self.A_Range), "-fis", str(self.final_image_size),
"-o", self.output_path])
T_End = time()
print("[INFO] The total elapsed time (for all files in pectroal preprocessing step): "+'\033[1m'+ \
colored(str(round(T_End-T_Start, 2)), 'red')+'\033[0m'+" seconds")
############################################################################
############################################################################
def run_pec_cnn(self):
from load_models import get_network_segmentation
from needed_functions_GPU import test_network_pec
T_Start = time()
print(colored("[INFO] Pectoral segmentation using CNN is started.", 'cyan'))
self = get_network_segmentation(self, self.model_path,
self.Keys_txt_file_input, self.Keys_object)
self = test_network_pec(self)
T_End = time()
print("[INFO] The total elapsed time (for all files in pectroal CNN): "+'\033[1m'+ \
colored(str(round(T_End-T_Start, 2)), 'red')+'\033[0m'+" seconds")
print(colored("[INFO] Pectoral segmentation using CNN is done.", 'green'))
############################################################################
############################################################################
def run_breast_postprocessing(self):
print(colored("[INFO] Postprocessing for breast vs pectroal segmentation.", 'cyan'))
T_Start = time()
Path_segmented_pectoral = os.path.join(self.output_path, self.saving_folder_name_temp_breast_masks)
if self.input_data[-4:]!=".dcm":
self.Cases = sorted(glob(os.path.join(Path_segmented_pectoral, "*"+self.image_format)))
else:
_, file_name = os.path.split(self.input_data)
temp_path = os.path.join(Path_segmented_pectoral, file_name[:-4]+
self.pec_seg_prefix+self.image_format)
self.Cases = [temp_path]
Image_Path = os.path.join(self.output_path, self.saving_folder_name_final_masked_normalized_images)
if not(os.path.isdir(Image_Path)): os.makedirs(Image_Path)
print("[INFO] Saving path for the summary of this step is "+Image_Path)
if self.multi_cpu == 1:
batch_processes = []
Q = multiprocessing.Queue()
Total_processes = 0
for N, self.Case in enumerate(self.Cases):
p = multiprocessing.Process(target=run_loop_multi_cpu_post,
args=(self, self.Case, self.code_path, ))
batch_processes.append(p)
p.start()
if len(batch_processes)>self.number_cpu_cores or N+1 == len(self.Cases):
Total_processes += self.number_cpu_cores
for j in batch_processes:
j.join()
if Total_processes > self.max_number_of_process:
Q.close()
Q.join_thread()
Q = multiprocessing.Queue()
Total_processes = 0
batch_processes = []
else:
for self.Case in self.Cases:
_, File = os.path.split(self.Case)
self.File = File[:File.find(self.pec_seg_prefix)]
call(["python3", os.path.join(self.code_path, "postprocessing.py"),
"-i", self.Case, "-if", self.image_format, "-cn", self.File,
"-po", self.print_off, "-sfn", self.saving_folder_name_final_masked_normalized_images,
"-ar", str(self.A_Range), "-fis", str(self.final_image_size),
"-o", self.output_path, "-fb", self.find_bottom])
T_End = time()
print("[INFO] The total elapsed time (for all files in breast postprocessing step): "+'\033[1m'+ \
colored(str(round(T_End-T_Start, 2)), 'red')+'\033[0m'+" seconds")
############################################################################
############################################################################
def get_info_based_on_density_cnn(self):
from needed_functions_GPU import test_birads
from load_models import get_network_classification
print(colored("[INFO] Loading breast density CNN.", 'cyan'))
self.model_path = self.model_path_density
self = get_network_classification(self, self.model_path,
self.Keys_txt_file_input, self.Keys_object)
############################################################################
############################################################################
def run_BIRADS_cnn(self):
T_Start = time()
print(colored("[INFO] BIRADS Prediction using CNN is started.", 'cyan'))
self = test_birads(self)
print(colored("[INFO] BIRADS Prediction using CNN is done.", 'green'))
T_End = time()
print("[INFO] The total elapsed time (for all files in BIRADS CNN): "+'\033[1m'+ \
colored(str(round(T_End-T_Start, 2)), 'red')+'\033[0m'+" seconds")
############################################################################
############################################################################
def run_feature_extraction(self):
print(colored("[INFO] Extarcing featrues for feature maps.", 'cyan'))
print("[INFO] Saving summary path is "+self.saving_folder_name_breast_density)
T_Start = time()
Path_density_map = os.path.join(self.output_path, self.saving_folder_name_final_masked_normalized_images)
if self.input_data[-4:]!=".dcm":
self.Cases = sorted(glob(os.path.join(Path_density_map, "*"+self.image_format)))
else:
_, file_name = os.path.split(self.input_data)
temp_path = os.path.join(Path_density_map, file_name[:-4]+self.image_format)
self.Cases = [temp_path]
Image_Path = os.path.join(self.output_path, self.saving_folder_name_breast_density)
if not(os.path.isdir(Image_Path)): os.makedirs(Image_Path)
print("[INFO] Saving path for the summary of this step is "+Image_Path)
if self.multi_cpu == 1:
batch_processes = []
Q = multiprocessing.Queue()
Total_processes = 0
self.timeout_waiting *= self.max_number_of_process
for N, self.Case in enumerate(self.Cases):
p = multiprocessing.Process(target=run_loop_multi_cpu_denisty_map,
args=(self, self.Case, self.code_path, ))
batch_processes.append(p)
p.start()
if len(batch_processes)>self.number_cpu_cores or N+1 == len(self.Cases):
Total_processes += self.number_cpu_cores
for j in batch_processes:
j.join()
if Total_processes > self.max_number_of_process:
Q.close()
Q.join_thread()
Q = multiprocessing.Queue()
Total_processes = 0
batch_processes = []
else:
for self.Case in self.Cases:
_, File = os.path.split(self.Case)
self.File = File[:-4]
call(["python3", os.path.join(self.code_path, "density_map_feature_based.py"),
"-i", self.Case, "-if", self.image_format, "-cn", self.File,
"-po", self.print_off, "-sfn", self.saving_folder_name_breast_density,
"-ar", str(self.A_Range), "-fis", str(self.final_image_size),
"-o", self.output_path, "-lt", str(self.libra_training),
"-pttm", self.model_path_density, "-rii", self.remove_intermediate_images,
"-to", str(self.timeout_waiting)])
T_End = time()
print("[INFO] The total elapsed time (for all files in density mask step): "+'\033[1m'+ \
colored(str(round(T_End-T_Start, 2)), 'red')+'\033[0m'+" seconds")