forked from ypy516478793/Lung_nodule_detection_pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprepare.py
1522 lines (1351 loc) · 65.6 KB
/
prepare.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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Usage instructions:
python prepare.py ch_infopath \
-s="/home/cougarnet.uh.edu/pyuan2/Datasets/Methodist_incidental/data_Ben/labeled/"
python prepare.py ass_pet \
-s="/home/cougarnet.uh.edu/pyuan2/Datasets/Methodist_incidental/data_Ben/labeled/"
python prepare.py prep_methodist \
-s="/home/cougarnet.uh.edu/pyuan2/Datasets/Methodist_incidental/data_Ben/masked_first/" \
-r="/home/cougarnet.uh.edu/pyuan2/Datasets/Methodist_incidental/data_Ben/labeled/" \
-m=True \
-c=True
python prepare.py prep_luna
python prepare.py get_info \
-r="/home/cougarnet.uh.edu/pyuan2/Datasets/Methodist_incidental/data_Ben/labeled"
python prepare.py extract \
-r="/home/cougarnet.uh.edu/pyuan2/Datasets/Methodist_incidental/additional_0412/raw" \
-s="/home/cougarnet.uh.edu/pyuan2/Datasets/Methodist_incidental/additional_0412" \
-p="/home/cougarnet.uh.edu/pyuan2/Datasets/Methodist_incidental/additional_0412/checklist.xlsx" \
-n=False
python prepare.py convert \
-r="/home/cougarnet.uh.edu/pyuan2/Datasets/Methodist_incidental/additional_0412/raw" \
-s="/home/cougarnet.uh.edu/pyuan2/Datasets/Methodist_incidental/additional_0412" \
-a="labels_my-project-name_2021-04-20-11-13-39.csv" \
-n=False
python prepare.py update_details \
-r="/home/cougarnet.uh.edu/pyuan2/Projects/DeepLung-3D_Lung_Nodule_Detection/Methodist_incidental/data_Ben/labeled" \
-s="/home/cougarnet.uh.edu/pyuan2/Projects/DeepLung-3D_Lung_Nodule_Detection/Methodist_incidental"
python prepare.py update_checklist \
-r="/home/cougarnet.uh.edu/pyuan2/Projects/DeepLung-3D_Lung_Nodule_Detection/Methodist_incidental/data_Ben/labeled" \
-s="/home/cougarnet.uh.edu/pyuan2/Projects/DeepLung-3D_Lung_Nodule_Detection/Methodist_incidental" \
-p="/home/cougarnet.uh.edu/pyuan2/Projects/DeepLung-3D_Lung_Nodule_Detection/Methodist_incidental/checklist_Ben.xlsx"
"""
import os
from shutil import copyfile
import numpy as np
import scipy
import matplotlib.pyplot as plt
from scipy.ndimage.interpolation import zoom
from sklearn.cluster import KMeans
from skimage import morphology
from skimage import measure
import SimpleITK as sitk
from scipy.ndimage.morphology import binary_dilation, generate_binary_structure
from skimage.morphology import convex_hull_image
import pandas
from multiprocessing import Pool
from functools import partial
from tqdm import tqdm
from natsort import natsorted
import pandas as pd
import argparse
import warnings
config = {'train_data_path': ['LUNA16/raw_files/subset0/',
'LUNA16/raw_files/subset1/',
'LUNA16/raw_files/subset2/',
'LUNA16/raw_files/subset3/',
'LUNA16/raw_files/subset4/',
'LUNA16/raw_files/subset5/',
'LUNA16/raw_files/subset6/',
'LUNA16/raw_files/subset7/',
'LUNA16/raw_files/subset8/'],
'val_data_path': ['LUNA16/raw_files/subset9/'],
'test_data_path': ['LUNA16/raw_files/subset9/'],
'train_preprocess_result_path': 'LUNA16/raw_npz/',
# 'train_preprocess_result_path': 'LUNA16/preprocessed/',
# contains numpy for the data and label, which is generated by prepare.py
'val_preprocess_result_path': 'LUNA16/raw_npz/',
# 'val_preprocess_result_path': 'LUNA16/preprocessed/',
# make sure copy all the numpy into one folder after prepare.py
'test_preprocess_result_path': 'LUNA16/raw_npz/',
# 'test_preprocess_result_path': 'LUNA16/preprocessed/',
'train_annos_path': 'LUNA16/annotations.csv',
'val_annos_path': 'LUNA16/annotations.csv',
'test_annos_path': 'LUNA16/annotations.csv',
'black_list': [],
'preprocessing_backend': 'python',
'luna_segment': 'LUNA16/seg-lungs-LUNA16/', # download from https://luna16.grand-challenge.org/data/
# 'preprocess_result_path': 'LUNA16/preprocessed/',
'preprocess_result_path': 'LUNA16/raw_npz/',
'luna_data': 'LUNA16/raw_files/',
'luna_label': 'LUNA16/annotations.csv'
}
def resample(imgs, spacing, new_spacing, order=2):
if len(imgs.shape) == 3:
new_shape = np.round(imgs.shape * spacing / new_spacing)
true_spacing = spacing * imgs.shape / new_shape
resize_factor = new_shape / imgs.shape
imgs = zoom(imgs, resize_factor, mode='nearest', order=order)
return imgs, true_spacing
elif len(imgs.shape) == 4:
n = imgs.shape[-1]
newimg = []
for i in range(n):
slice = imgs[:, :, :, i]
newslice, true_spacing = resample(slice, spacing, new_spacing)
newimg.append(newslice)
newimg = np.transpose(np.array(newimg), [1, 2, 3, 0])
return newimg, true_spacing
else:
raise ValueError('wrong shape')
def worldToVoxelCoord(worldCoord, origin, spacing):
stretchedVoxelCoord = np.absolute(worldCoord - origin)
voxelCoord = stretchedVoxelCoord / spacing
return voxelCoord
def load_itk_image(filename):
with open(filename) as f:
contents = f.readlines()
line = [k for k in contents if k.startswith('TransformMatrix')][0]
transformM = np.array(line.split(' = ')[1].split(' ')).astype('float')
transformM = np.round(transformM)
if np.any(transformM != np.array([1, 0, 0, 0, 1, 0, 0, 0, 1])):
isflip = True
else:
isflip = False
itkimage = sitk.ReadImage(filename)
print("read itkimage successfully")
numpyImage = sitk.GetArrayFromImage(itkimage)
numpyOrigin = np.array(list(reversed(itkimage.GetOrigin())))
numpySpacing = np.array(list(reversed(itkimage.GetSpacing())))
return numpyImage, numpyOrigin, numpySpacing, isflip
def process_mask(mask):
convex_mask = np.copy(mask)
for i_layer in range(convex_mask.shape[0]):
mask1 = np.ascontiguousarray(mask[i_layer])
if np.sum(mask1) > 0:
mask2 = convex_hull_image(mask1)
if np.sum(mask2) > 1.5 * np.sum(mask1):
mask2 = mask1
else:
mask2 = mask1
convex_mask[i_layer] = mask2
struct = generate_binary_structure(3, 1)
dilatedMask = binary_dilation(convex_mask, structure=struct, iterations=10)
return dilatedMask
def lumTrans(img):
lungwin = np.array([-1200., 600.])
newimg = (img - lungwin[0]) / (lungwin[1] - lungwin[0])
newimg[newimg < 0] = 0
newimg[newimg > 1] = 1
newimg = (newimg * 255).astype('uint8')
return newimg
def binarize_per_slice(image, spacing, intensity_th=-600, sigma=1, area_th=30, eccen_th=0.99, bg_patch_size=10):
bw = np.zeros(image.shape, dtype=bool)
# prepare a mask, with all corner values set to nan
image_size = image.shape[1]
grid_axis = np.linspace(-image_size / 2 + 0.5, image_size / 2 - 0.5, image_size)
x, y = np.meshgrid(grid_axis, grid_axis)
d = (x ** 2 + y ** 2) ** 0.5
nan_mask = (d < image_size / 2).astype(float)
nan_mask[nan_mask == 0] = np.nan
for i in range(image.shape[0]):
# Check if corner pixels are identical, if so the slice before Gaussian filtering
if len(np.unique(image[i, 0:bg_patch_size, 0:bg_patch_size])) == 1:
current_bw = scipy.ndimage.filters.gaussian_filter(np.multiply(image[i].astype('float32'), nan_mask), sigma,
truncate=2.0) < intensity_th
else:
current_bw = scipy.ndimage.filters.gaussian_filter(image[i].astype('float32'), sigma,
truncate=2.0) < intensity_th
# select proper components
label = measure.label(current_bw)
properties = measure.regionprops(label)
valid_label = set()
for prop in properties:
if prop.area * spacing[1] * spacing[2] > area_th and prop.eccentricity < eccen_th:
valid_label.add(prop.label)
current_bw = np.in1d(label, list(valid_label)).reshape(label.shape)
bw[i] = current_bw
return bw
def all_slice_analysis(bw, spacing, cut_num=0, vol_limit=[0.68, 8.2], area_th=6e3, dist_th=62):
# in some cases, several top layers need to be removed first
if cut_num > 0:
bw0 = np.copy(bw)
bw[-cut_num:] = False
label = measure.label(bw, connectivity=1)
# remove components access to corners
mid = int(label.shape[2] / 2)
bg_label = set([label[0, 0, 0], label[0, 0, -1], label[0, -1, 0], label[0, -1, -1], \
label[-1 - cut_num, 0, 0], label[-1 - cut_num, 0, -1], label[-1 - cut_num, -1, 0],
label[-1 - cut_num, -1, -1], \
label[0, 0, mid], label[0, -1, mid], label[-1 - cut_num, 0, mid], label[-1 - cut_num, -1, mid]])
for l in bg_label:
label[label == l] = 0
# select components based on volume
properties = measure.regionprops(label)
for prop in properties:
if prop.area * spacing.prod() < vol_limit[0] * 1e6 or prop.area * spacing.prod() > vol_limit[1] * 1e6:
label[label == prop.label] = 0
# prepare a distance map for further analysis
x_axis = np.linspace(-label.shape[1] / 2 + 0.5, label.shape[1] / 2 - 0.5, label.shape[1]) * spacing[1]
y_axis = np.linspace(-label.shape[2] / 2 + 0.5, label.shape[2] / 2 - 0.5, label.shape[2]) * spacing[2]
x, y = np.meshgrid(x_axis, y_axis)
d = (x ** 2 + y ** 2) ** 0.5
vols = measure.regionprops(label)
valid_label = set()
# select components based on their area and distance to center axis on all slices
for vol in vols:
single_vol = label == vol.label
slice_area = np.zeros(label.shape[0])
min_distance = np.zeros(label.shape[0])
for i in range(label.shape[0]):
slice_area[i] = np.sum(single_vol[i]) * np.prod(spacing[1:3])
min_distance[i] = np.min(single_vol[i] * d + (1 - single_vol[i]) * np.max(d))
if np.average([min_distance[i] for i in range(label.shape[0]) if slice_area[i] > area_th]) < dist_th:
valid_label.add(vol.label)
bw = np.in1d(label, list(valid_label)).reshape(label.shape)
# fill back the parts removed earlier
if cut_num > 0:
# bw1 is bw with removed slices, bw2 is a dilated version of bw, part of their intersection is returned as final mask
bw1 = np.copy(bw)
bw1[-cut_num:] = bw0[-cut_num:]
bw2 = np.copy(bw)
bw2 = scipy.ndimage.binary_dilation(bw2, iterations=cut_num)
bw3 = bw1 & bw2
label = measure.label(bw, connectivity=1)
label3 = measure.label(bw3, connectivity=1)
l_list = list(set(np.unique(label)) - {0})
valid_l3 = set()
for l in l_list:
indices = np.nonzero(label == l)
l3 = label3[indices[0][0], indices[1][0], indices[2][0]]
if l3 > 0:
valid_l3.add(l3)
bw = np.in1d(label3, list(valid_l3)).reshape(label3.shape)
return bw, len(valid_label)
def fill_hole(bw):
# fill 3d holes
label = measure.label(~bw)
# idendify corner components
bg_label = set([label[0, 0, 0], label[0, 0, -1], label[0, -1, 0], label[0, -1, -1], \
label[-1, 0, 0], label[-1, 0, -1], label[-1, -1, 0], label[-1, -1, -1]])
bw = ~np.in1d(label, list(bg_label)).reshape(label.shape)
return bw
def two_lung_only(bw, spacing, max_iter=22, max_ratio=4.8):
def extract_main(bw, cover=0.95):
for i in range(bw.shape[0]):
current_slice = bw[i]
label = measure.label(current_slice)
properties = measure.regionprops(label)
properties.sort(key=lambda x: x.area, reverse=True)
area = [prop.area for prop in properties]
count = 0
sum = 0
while sum < np.sum(area) * cover:
sum = sum + area[count]
count = count + 1
filter = np.zeros(current_slice.shape, dtype=bool)
for j in range(count):
bb = properties[j].bbox
filter[bb[0]:bb[2], bb[1]:bb[3]] = filter[bb[0]:bb[2], bb[1]:bb[3]] | properties[j].convex_image
bw[i] = bw[i] & filter
label = measure.label(bw)
properties = measure.regionprops(label)
properties.sort(key=lambda x: x.area, reverse=True)
bw = label == properties[0].label
return bw
def fill_2d_hole(bw):
for i in range(bw.shape[0]):
current_slice = bw[i]
label = measure.label(current_slice)
properties = measure.regionprops(label)
for prop in properties:
bb = prop.bbox
current_slice[bb[0]:bb[2], bb[1]:bb[3]] = current_slice[bb[0]:bb[2], bb[1]:bb[3]] | prop.filled_image
bw[i] = current_slice
return bw
found_flag = False
iter_count = 0
bw0 = np.copy(bw)
while not found_flag and iter_count < max_iter:
label = measure.label(bw, connectivity=2)
properties = measure.regionprops(label)
properties.sort(key=lambda x: x.area, reverse=True)
if len(properties) > 1 and properties[0].area / properties[1].area < max_ratio:
found_flag = True
bw1 = label == properties[0].label
bw2 = label == properties[1].label
else:
bw = scipy.ndimage.binary_erosion(bw)
iter_count = iter_count + 1
if found_flag:
d1 = scipy.ndimage.morphology.distance_transform_edt(bw1 == False, sampling=spacing)
d2 = scipy.ndimage.morphology.distance_transform_edt(bw2 == False, sampling=spacing)
bw1 = bw0 & (d1 < d2)
bw2 = bw0 & (d1 > d2)
bw1 = extract_main(bw1)
bw2 = extract_main(bw2)
else:
bw1 = bw0
bw2 = np.zeros(bw.shape).astype('bool')
bw1 = fill_2d_hole(bw1)
bw2 = fill_2d_hole(bw2)
bw = bw1 | bw2
return bw1, bw2, bw
def step1_python_tianchi(case_path):
# case = load_scan(case_path)
# case_pixels, spacing = get_pixels_hu(case)
''' For the mhd file reader '''
resolution = np.array([1, 1, 1])
sliceim, origin, spacing, isflip = load_itk_image(case_path + '.mhd')
if isflip:
sliceim = sliceim[:, ::-1, ::-1]
print('flip!')
# sliceim = lumTrans(sliceim)
# sliceim1,_ = resample(sliceim,spacing,resolution,order=1)
case_pixels = np.array(sliceim)
bw = binarize_per_slice(case_pixels, spacing)
flag = 0
cut_num = 0
cut_step = 2
bw0 = np.copy(bw)
while flag == 0 and cut_num < bw.shape[0]:
bw = np.copy(bw0)
bw, flag = all_slice_analysis(bw, spacing, cut_num=cut_num, vol_limit=[0.68, 7.5])
cut_num = cut_num + cut_step
bw = fill_hole(bw)
bw1, bw2, bw = two_lung_only(bw, spacing)
return case_pixels, bw1, bw2, spacing, origin, isflip
def savenpy(id, annos, filelist, data_path, prep_folder):
resolution = np.array([1, 1, 1])
name = filelist[id]
im, m1, m2, spacing, origin, isflip = step1_python_tianchi(os.path.join(data_path, name))
missingmask = False
if os.path.exists(os.path.join(prep_folder, name + '_clean.npy')) and \
os.path.exists(os.path.join(prep_folder, name + '_originbox.npy')) and \
os.path.exists(os.path.join(prep_folder, name + '_spacing.npy')) and \
os.path.exists(os.path.join(prep_folder, name + '_origin.npy')) and \
os.path.exists(os.path.join(prep_folder, name + '_label.npy')):
if not isflip:
print('skip', name)
return
else:
missingmask = True
print('process', name)
label = annos[annos[:, 0] == name]
# label = label.astype('float')
label = label[:, [3, 1, 2, 4]].astype('float') # z, y, x, d
Mask = m1 + m2
newshape = np.round(np.array(Mask.shape) * spacing / resolution)
xx, yy, zz = np.where(Mask)
if xx.size == 0 or yy.size == 0 or zz.size == 0:
print(name)
assert 1 == 0
box = np.array([[np.min(xx), np.max(xx)], [np.min(yy), np.max(yy)], [np.min(zz), np.max(zz)]])
box = box * np.expand_dims(spacing, 1) / np.expand_dims(resolution, 1)
box = np.floor(box).astype('int')
margin = 5
extendbox = np.vstack(
[np.max([[0, 0, 0], box[:, 0] - margin], 0), np.min([newshape, box[:, 1] + 2 * margin], axis=0).T]).T
extendbox = extendbox.astype('int')
if extendbox[0, 0] == extendbox[0, 1] or extendbox[1, 0] == extendbox[1, 1] or extendbox[2, 0] == extendbox[2, 1]:
print(name)
assert 1 == 0
convex_mask = m1
dm1 = process_mask(m1)
dm2 = process_mask(m2)
dilatedMask = dm1 + dm2
Mask = m1 + m2
if missingmask:
np.save(os.path.join(prep_folder, name + '_mask.npy'), Mask)
print('skip', name)
return
extramask = dilatedMask - Mask
bone_thresh = 210
pad_value = 170
im[np.isnan(im)] = -2000
sliceim = lumTrans(im)
sliceim = sliceim * dilatedMask + pad_value * (1 - dilatedMask).astype('uint8')
bones = sliceim * extramask > bone_thresh
sliceim[bones] = pad_value
sliceim1, _ = resample(sliceim, spacing, resolution, order=1)
sliceim2 = sliceim1[extendbox[0, 0]:extendbox[0, 1],
extendbox[1, 0]:extendbox[1, 1],
extendbox[2, 0]:extendbox[2, 1]]
sliceim = sliceim2[np.newaxis, ...]
np.save(os.path.join(prep_folder, name + '_clean.npy'), sliceim)
np.save(os.path.join(prep_folder, name + '_originbox.npy'), extendbox)
np.save(os.path.join(prep_folder, name + '_spacing.npy'), spacing)
np.save(os.path.join(prep_folder, name + '_origin.npy'), origin)
print(im.shape, '_clean', sliceim.shape, '_originbox', extendbox.shape, '_space', spacing, '_origin', origin)
this_annos = np.copy(annos[annos[:, 0] == name])
label = []
print('label', this_annos.shape, name)
if len(this_annos) > 0:
for c in this_annos:
pos = worldToVoxelCoord(c[1:4][::-1], origin=origin, spacing=spacing)
if isflip:
pos[1:] = Mask.shape[1:3] - pos[1:]
label.append(np.concatenate([pos, [c[4] / spacing[1]]]))
label = np.array(label)
if len(label) == 0:
label2 = np.array([[0, 0, 0, 0]])
else:
label2 = np.copy(label).T
label2[:3] = label2[:3] * np.expand_dims(spacing, 1) / np.expand_dims(resolution, 1)
label2[3] = label2[3] * spacing[1] / resolution[1]
label2[:3] = label2[:3] - np.expand_dims(extendbox[:, 0], 1)
label2 = label2[:4].T
np.save(os.path.join(prep_folder, name + '_label.npy'), label2)
print(name)
def full_prep(train=True, val=True, test=True):
warnings.filterwarnings("ignore")
# preprocess_result_path = './prep_result'
train_prep_folder = config['train_preprocess_result_path']
val_prep_folder = config['val_preprocess_result_path']
test_prep_folder = config['test_preprocess_result_path']
train_data_path = config['train_data_path']
val_data_path = config['val_data_path']
test_data_path = config['test_data_path']
finished_flag = '.flag_preptianchi'
if not os.path.exists(finished_flag):
trainlabelfiles = config['train_annos_path']
vallabelfiles = config['val_annos_path']
testlabelfiles = config['test_annos_path']
traincontent = np.array(pandas.read_csv(trainlabelfiles))
traincontent = traincontent[traincontent[:, 0] != np.nan]
trainalllabel = traincontent[1:, :] # filename, x, y, z, d
trainfilelist = []
for f in os.listdir(config['train_data_path']):
if f.endswith('.mhd'):
if f[:-4] in config['black_list']:
continue
trainfilelist.append(f[:-4])
valcontent = np.array(pandas.read_csv(vallabelfiles))
valcontent = valcontent[valcontent[:, 0] != np.nan]
valalllabel = valcontent[1:, :] # filename, x, y, z, d
valfilelist = []
for f in os.listdir(config['val_data_path']):
if f.endswith('.mhd'):
if f[:-4] in config['black_list']:
continue
valfilelist.append(f[:-4])
testcontent = np.array(pandas.read_csv(testlabelfiles))
testcontent = testcontent[testcontent[:, 0] != np.nan]
testalllabel = testcontent[1:, :] # filename, x, y, z, d
testfilelist = []
for f in os.listdir(config['test_data_path']):
if f.endswith('.mhd'):
if f[:-4] in config['black_list']:
continue
testfilelist.append(f[:-4])
if not os.path.exists(train_prep_folder):
os.mkdir(train_prep_folder)
if not os.path.exists(val_prep_folder):
os.mkdir(val_prep_folder)
if not os.path.exists(test_prep_folder):
os.mkdir(test_prep_folder)
# eng.addpath('preprocessing/',nargout=0)
if train:
print('starting train preprocessing')
pool = Pool(10)
partial_savenpy = partial(savenpy, annos=trainalllabel, filelist=trainfilelist, data_path=train_data_path,
prep_folder=train_prep_folder)
N = len(trainfilelist)
savenpy(1)
_ = pool.map(partial_savenpy, list(range(N)))
print('end train preprocessing')
if val:
print('starting val preprocessing')
partial_savenpy = partial(savenpy, annos=valalllabel, filelist=valfilelist, data_path=val_data_path,
prep_folder=val_prep_folder)
N = len(valfilelist)
savenpy(1)
_ = pool.map(partial_savenpy, list(range(N)))
print('end val preprocessing')
if test:
print('starting test preprocessing')
partial_savenpy = partial(savenpy, annos=testalllabel, filelist=testfilelist, data_path=test_data_path,
prep_folder=test_prep_folder)
N = len(testfilelist)
savenpy(1)
_ = pool.map(partial_savenpy, list(range(N)))
pool.close()
pool.join()
print('end test preprocessing')
f = open(finished_flag, "w+")
def splitvaltestcsv():
testfiles = []
for f in os.listdir(config['test_data_path']):
if f.endswith('.mhd'):
testfiles.append(f[:-4])
valcsvlines = []
testcsvlines = []
import csv
valf = open(config['val_annos_path'], 'r')
valfcsv = csv.reader(valf)
for line in valfcsv:
if line[0] in testfiles:
testcsvlines.append(line)
else:
valcsvlines.append(line)
valf.close()
testf = open(config['test_annos_path'] + 'annotations.csv', 'w')
testfcsv = csv.writer(testf)
for line in testcsvlines:
testfcsv.writerow(line)
testf.close()
valf = open(config['val_annos_path'], 'w')
valfcsv = csv.writer(valf)
for line in valcsvlines:
valfcsv.writerow(line)
valf.close()
def savenpy_luna_raw(id, annos, filelist, luna_segment, luna_data, savepath):
islabel = True
isClean = True
resolution = np.array([1, 1, 1])
# resolution = np.array([2,2,2])
name = filelist[id]
sliceim, origin, spacing, isflip = load_itk_image(os.path.join(luna_data, name + '.mhd'))
ori_shape = sliceim.shape
# Mask,origin,spacing,isflip = load_itk_image(os.path.join(luna_segment,name+'.mhd'))
# if isflip:
# Mask = Mask[:,::-1,::-1]
# newshape = np.round(np.array(Mask.shape)*spacing/resolution).astype('int')
# m1 = Mask==3
# m2 = Mask==4
# Mask = m1+m2
#
# xx,yy,zz= np.where(Mask)
# box = np.array([[np.min(xx),np.max(xx)],[np.min(yy),np.max(yy)],[np.min(zz),np.max(zz)]])
# box = box*np.expand_dims(spacing,1)/np.expand_dims(resolution,1)
# box = np.floor(box).astype('int')
# margin = 5
# extendbox = np.vstack([np.max([[0,0,0],box[:,0]-margin],0),np.min([newshape,box[:,1]+2*margin],axis=0).T]).T
if isClean:
# convex_mask = m1
# dm1 = process_mask(m1)
# dm2 = process_mask(m2)
# dilatedMask = dm1+dm2
# Mask = m1+m2
#
# extramask = dilatedMask ^ Mask
# bone_thresh = 210
# pad_value = 170
if isflip:
sliceim = sliceim[:, ::-1, ::-1]
print('flip!')
sliceim1, _ = resample(sliceim, spacing, resolution, order=1)
sliceim1 = lumTrans(sliceim1)
# sliceim = sliceim*dilatedMask+pad_value*(1-dilatedMask).astype('uint8')
# bones = (sliceim*extramask)>bone_thresh
# sliceim[bones] = pad_value
#
# sliceim1,_ = resample(sliceim,spacing,resolution,order=1)
# sliceim2 = sliceim1[extendbox[0,0]:extendbox[0,1],
# extendbox[1,0]:extendbox[1,1],
# extendbox[2,0]:extendbox[2,1]]
sliceim = sliceim1[np.newaxis, ...]
np.savez_compressed(os.path.join(savepath, name + '_image.npz'), image=sliceim)
# np.save(os.path.join(savepath, name+'_spacing.npy'), spacing)
# np.save(os.path.join(savepath, name+'_extendbox.npy'), extendbox)
# np.save(os.path.join(savepath, name+'_origin.npy'), origin)
# np.save(os.path.join(savepath, name+'_mask.npy'), Mask)
if islabel:
this_annos = np.copy(annos[annos[:, 0] == (name)])
label = []
if len(this_annos) > 0:
for c in this_annos:
pos = worldToVoxelCoord(c[1:4][::-1], origin=origin, spacing=spacing)
if isflip:
# pos[1:] = Mask.shape[1:3]-pos[1:]
pos[1:] = ori_shape[1:3] - pos[1:]
label.append(np.concatenate([pos, [c[4] / spacing[1]]]))
label = np.array(label)
if len(label) == 0:
label2 = np.array([[0, 0, 0, 0]])
else:
label2 = np.copy(label).T
label2[:3] = label2[:3] * np.expand_dims(spacing, 1) / np.expand_dims(resolution, 1)
label2[3] = label2[3] * spacing[1] / resolution[1]
# label2[:3] = label2[:3]-np.expand_dims(extendbox[:,0],1)
label2 = label2[:4].T
# np.save(os.path.join(savepath,name+'_label.npy'), label2)
# np.savez_compressed(os.path.join(savepath, name + '_label.npz'), label=label2)
print(name)
def savenpy_luna(id, annos, filelist, luna_segment, luna_data, savepath):
islabel = True
isClean = True
resolution = np.array([1, 1, 1])
# resolution = np.array([2,2,2])
name = filelist[id]
sliceim, origin, spacing, isflip = load_itk_image(os.path.join(luna_data, name + '.mhd'))
Mask, origin, spacing, isflip = load_itk_image(os.path.join(luna_segment, name + '.mhd'))
if isflip:
Mask = Mask[:, ::-1, ::-1]
newshape = np.round(np.array(Mask.shape) * spacing / resolution).astype('int')
m1 = Mask == 3
m2 = Mask == 4
Mask = m1 + m2
xx, yy, zz = np.where(Mask)
box = np.array([[np.min(xx), np.max(xx)], [np.min(yy), np.max(yy)], [np.min(zz), np.max(zz)]])
box = box * np.expand_dims(spacing, 1) / np.expand_dims(resolution, 1)
box = np.floor(box).astype('int')
margin = 5
extendbox = np.vstack(
[np.max([[0, 0, 0], box[:, 0] - margin], 0), np.min([newshape, box[:, 1] + 2 * margin], axis=0).T]).T
this_annos = np.copy(annos[annos[:, 0] == (name)])
if isClean:
convex_mask = m1
dm1 = process_mask(m1)
dm2 = process_mask(m2)
dilatedMask = dm1 + dm2
Mask = m1 + m2
extramask = dilatedMask ^ Mask
bone_thresh = 210
pad_value = 170
if isflip:
sliceim = sliceim[:, ::-1, ::-1]
print('flip!')
sliceim = lumTrans(sliceim)
sliceim = sliceim * dilatedMask + pad_value * (1 - dilatedMask).astype('uint8')
bones = (sliceim * extramask) > bone_thresh
sliceim[bones] = pad_value
sliceim1, _ = resample(sliceim, spacing, resolution, order=1)
sliceim2 = sliceim1[extendbox[0, 0]:extendbox[0, 1],
extendbox[1, 0]:extendbox[1, 1],
extendbox[2, 0]:extendbox[2, 1]]
sliceim = sliceim2[np.newaxis, ...]
# np.save(os.path.join(savepath, name+'_clean.npy'), sliceim)
# np.save(os.path.join(savepath, name+'_spacing.npy'), spacing)
# np.save(os.path.join(savepath, name+'_extendbox.npy'), extendbox)
# np.save(os.path.join(savepath, name+'_origin.npy'), origin)
# np.save(os.path.join(savepath, name+'_mask.npy'), Mask)
if islabel:
this_annos = np.copy(annos[annos[:, 0] == (name)])
label = []
if len(this_annos) > 0:
for c in this_annos:
pos = worldToVoxelCoord(c[1:4][::-1], origin=origin, spacing=spacing)
if isflip:
pos[1:] = Mask.shape[1:3] - pos[1:]
label.append(np.concatenate([pos, [c[4] / spacing[1]]]))
label = np.array(label)
if len(label) == 0:
label2 = np.array([[0, 0, 0, 0]])
else:
label2 = np.copy(label).T
label2[:3] = label2[:3] * np.expand_dims(spacing, 1) / np.expand_dims(resolution, 1)
label2[3] = label2[3] * spacing[1] / resolution[1]
label2[:3] = label2[:3] - np.expand_dims(extendbox[:, 0], 1)
label2 = label2[:4].T
# np.save(os.path.join(savepath,name+'_label.npy'), label2)
print(name)
def preprocess_luna():
luna_segment = config['luna_segment']
savepath = config['preprocess_result_path']
luna_data = config['luna_data']
luna_label = config['luna_label']
finished_flag = '.flag_preprocessluna_______'
print('starting preprocessing luna')
if not os.path.exists(finished_flag):
annos = np.array(pandas.read_csv(luna_label))
# pool = Pool()
if not os.path.exists(savepath):
os.mkdir(savepath)
for setidx in range(0, 1):
print('process subset', setidx)
filelist = [f.split('.mhd')[0] for f in os.listdir(luna_data + 'subset' + str(setidx)) if
f.endswith('.mhd')]
# filelist = ["1.3.6.1.4.1.14519.5.2.1.6279.6001.105756658031515062000744821260"]
if not os.path.exists(savepath + 'subset' + str(setidx)):
os.mkdir(savepath + 'subset' + str(setidx))
# partial_savenpy_luna = partial(savenpy_luna, annos=annos, filelist=filelist,
# luna_segment=luna_segment, luna_data=luna_data+'subset'+str(setidx)+'/',
# savepath=savepath+'subset'+str(setidx)+'/')
N = len(filelist)
for i in tqdm(range(N)):
_ = savenpy_luna_raw(i, annos, filelist=filelist,
luna_segment=luna_segment, luna_data=luna_data + 'subset' + str(setidx) + '/',
savepath=savepath + 'subset' + str(setidx) + '/')
# savenpy(1)
# _=pool.map(partial_savenpy_luna,list(range(N)))
# pool.close()
# pool.join()
print('end preprocessing luna')
f = open(finished_flag, "w+")
def change_root_info(dst_dir):
file = os.path.join(dst_dir, "CTinfo.npz")
infos = np.load(file, allow_pickle=True)["info"]
s = infos[0]["imagePath"].find("Lung_patient")
if s == -1:
get_infos_from_npz(dst_dir)
file = os.path.join(dst_dir, "CTinfo.npz")
infos = np.load(file, allow_pickle=True)["info"]
for info in infos:
s = info["imagePath"].find("Lung_patient")
subPath = info["imagePath"][s:].replace("\\", "/")
subPathClean = subPath.replace(".npz", "_clean.npz")
if not os.path.exists(os.path.join(dst_dir, subPath)) and \
not os.path.exists(os.path.join(dst_dir, subPathClean)):
subPathList = subPath.split("/")
subPathList[0] = subPathList[0].rsplit("_", 1)[0]
# if not os.path.exists(os.path.exists(os.path.join(dst_dir, "/".join(subPathList)))):
# subPath = subPath.replace(".npz", "_extendbox.npz")
# # subPath = "/".join(subPathList)
# assert os.path.exists(os.path.join(dst_dir, subPath))
subPath = "/".join(subPathList)
assert os.path.exists(os.path.join(dst_dir, subPath))
info["imagePath"] = os.path.join(dst_dir, subPath)
print(infos)
import shutil
shutil.move(file, os.path.join(dst_dir, "CTinfo_old.npz"))
np.savez_compressed(file, info=infos)
print("Save all scan infos to {:s}".format(file))
def make_lungmask(img, display=False):
raw_img = np.copy(img)
row_size = img.shape[0]
col_size = img.shape[1]
mean = np.mean(img)
std = np.std(img)
if std == 0:
return np.zeros_like(img), np.zeros_like(img, dtype=np.int8)
img = img - mean
img = img / std
# Find the average pixel value near the lungs
# to renormalize washed out images
# middle = img[int(col_size / 5):int(col_size / 5 * 4), int(row_size / 5):int(row_size / 5 * 4)]
middle = img[0:col_size, 0:row_size]
mean = np.mean(middle)
max = np.max(img)
min = np.min(img)
# To improve threshold finding, I'm moving the
# underflow and overflow on the pixel spectrum
img[img == max] = mean
img[img == min] = mean
#
# Using Kmeans to separate foreground (soft tissue / bone) and background (lung/air)
#
kmeans = KMeans(n_clusters=2).fit(np.reshape(middle, [np.prod(middle.shape), 1]))
centers = sorted(kmeans.cluster_centers_.flatten())
threshold = np.mean(centers)
thresh_img = np.where(img < threshold, 1.0, 0.0) # threshold the image
# First erode away the finer elements, then dilate to include some of the pixels surrounding the lung.
# We don't want to accidentally clip the lung.
eroded = morphology.erosion(thresh_img, np.ones([5, 5]))
dilation = morphology.dilation(eroded, np.ones([8, 8]))
labels = measure.label(dilation) # Different labels are displayed in different colors
label_vals = np.unique(labels)
regions = measure.regionprops(labels)
good_labels = []
for prop in regions:
B = prop.bbox
if B[2] - B[0] < row_size / 10 * 9 and B[3] - B[1] < col_size / 10 * 9 and B[0] > row_size / 10 and B[
2] < col_size / 10 * 9:
good_labels.append(prop.label)
mask = np.ndarray([row_size, col_size], dtype=np.int8)
mask[:] = 0 # mask = np.zeros([row_size, col_size], dtype=np.int8)
#
# After just the lungs are left, we do another large dilation
# in order to fill in and out the lung mask
#
for N in good_labels:
mask = mask + np.where(labels == N, 1, 0)
mask = morphology.dilation(mask, np.ones([12, 12])) # one last dilation
if (display):
fig, ax = plt.subplots(3, 2, figsize=[12, 12])
ax[0, 0].set_title("Original")
ax[0, 0].imshow(img, cmap='gray')
ax[0, 0].axis('off')
ax[0, 1].set_title("Threshold")
ax[0, 1].imshow(thresh_img, cmap='gray')
ax[0, 1].axis('off')
ax[1, 0].set_title("After Erosion and Dilation")
ax[1, 0].imshow(dilation, cmap='gray')
ax[1, 0].axis('off')
ax[1, 1].set_title("Color Labels")
ax[1, 1].imshow(labels)
ax[1, 1].axis('off')
ax[2, 0].set_title("Final Mask")
ax[2, 0].imshow(mask, cmap='gray')
ax[2, 0].axis('off')
ax[2, 1].set_title("Apply Mask on Original")
ax[2, 1].imshow(mask * img, cmap='gray')
ax[2, 1].axis('off')
plt.show()
return mask * raw_img, mask
def mask_scan(images):
masked_images = []
masks = []
for img in images:
masked_image, mask = make_lungmask(img)
masked_images.append(masked_image)
masks.append(mask)
masked_images = np.stack(masked_images)
masks = np.stack(masks)
return masked_images, masks
def prepare_masked_images(root_dir, save_dir):
info_path = os.path.join(root_dir, "CTinfo.npz")
infos = np.load(info_path, allow_pickle=True)["info"]
for info in tqdm(infos):
s = info["imagePath"].find("Lung_patient")
save_path = os.path.join(save_dir, info["imagePath"][s:].replace("\\", "/"))
load_path = os.path.join(root_dir, info["imagePath"][s:].replace("\\", "/"))
os.makedirs(os.path.dirname(save_path), exist_ok=True)
imgs = np.load(load_path, allow_pickle=True)["image"]
imgs = mask_scan(imgs)
imgs = lumTrans(imgs)
info["imagePath"] = save_path
np.savez_compressed(save_path, image=imgs, info=info)
print("Save masked images to {:s}".format(save_path))
new_info_path = os.path.join(save_dir, "CTinfo.npz")
np.savez_compressed(new_info_path, info=infos)
print("Save all scan infos to {:s}".format(new_info_path))
def prepare_masked_cropped_images(root_dir, save_dir):
info_path = os.path.join(root_dir, "CTinfo.npz")
infos = np.load(info_path, allow_pickle=True)["info"]
for info in tqdm(infos):
s = info["imagePath"].find("Lung_patient")
save_path = os.path.join(save_dir, info["imagePath"][s:].replace("\\", "/"))
load_path = os.path.join(root_dir, info["imagePath"][s:].replace("\\", "/"))
os.makedirs(os.path.dirname(save_path), exist_ok=True)
savepath = os.path.dirname(save_path)
name = os.path.basename(save_path).strip(".npz")
if os.path.exists(os.path.join(savepath, name + '_extendbox.npz')):
continue
imgs = np.load(load_path, allow_pickle=True)["image"]
imgs, masks = mask_scan(imgs)
imgs = lumTrans(imgs)
zz, yy, xx = np.where(masks)
box = np.array([[np.min(zz), np.max(zz)], [np.min(yy), np.max(yy)], [np.min(xx), np.max(xx)]])
box = np.floor(box).astype('int')
margin = 5
extendbox = np.vstack([np.max([[0, 0, 0], box[:, 0] - margin], 0),
np.min([masks.shape, box[:, 1] + 2 * margin], axis=0).T]).T
sliceim = imgs[extendbox[0, 0]:extendbox[0, 1],
extendbox[1, 0]:extendbox[1, 1],
extendbox[2, 0]:extendbox[2, 1]]
sliceim = sliceim[np.newaxis, ...]
# savepath = os.path.dirname(save_path)
# name = os.path.basename(save_path).strip(".npz")
# spacing = np.array([1, 1, 1])
# origin = np.array([0, 0, 0])
np.savez_compressed(os.path.join(savepath, name+'_clean.npz'), image=sliceim, info=info)
# np.save(os.path.join(savepath, name+'_spacing.npy'), spacing)
np.savez_compressed(os.path.join(savepath, name+'_extendbox.npz'), extendbox=extendbox)
# np.save(os.path.join(savepath, name+'_origin.npy'), origin)
np.savez_compressed(os.path.join(savepath, name+'_mask.npz'), masks=masks)
new_info_path = os.path.join(save_dir, "CTinfo.npz")
np.savez_compressed(new_info_path, info=infos)
print("Save all scan infos to {:s}".format(new_info_path))
change_root_info(save_dir)
pos_label_file = "pos_labels_norm.csv"
if os.path.exists(os.path.join(root_dir, pos_label_file)):
copyfile(os.path.join(root_dir, pos_label_file), os.path.join(save_dir, pos_label_file))
def assign_PET_label(dst_dir):
PET_series = ["CT SLICES 50cm DFOV", "CTAC", "CT SLICES 50cm", "CT SLICES 50 CM", "Lung/Bone+ 50cm"]
file = os.path.join(dst_dir, "CTinfo.npz")
infos = np.load(file, allow_pickle=True)["info"]
# D = {}
# for i, a in enumerate(infos):
# if a["series"] not in D:
# D[a["series"]] = []
# D[a["series"]].append(i)
for i, info in tqdm(enumerate(infos)):
series = info["series"]
if "PET" in info and (info["PET"] == "Y" or info["PET"] == "N"):
continue
if series in PET_series:
info["PET"] = "Y"
try:
shape = np.load(info['imagePath'])["image"].shape
except FileNotFoundError:
shape = np.load(info['imagePath'].replace(".npz", "_clean.npz"))["image"].shape
num_slices = shape[0] if len(shape) == 3 else shape[1]
if not num_slices >= 500:
print("index {:}, series is {:}, shape is {:}".format(i, series, shape))
else:
info["PET"] = "N"
try:
shape = np.load(info['imagePath'])["image"].shape
except FileNotFoundError:
shape = np.load(info['imagePath'].replace(".npz", "_clean.npz"))["image"].shape
num_slices = shape[0] if len(shape) == 3 else shape[1]
if not num_slices < 500:
print("index {:}, series is {:}, shape is {:}".format(i, series, shape))
assert len(shape) == 3, "index {:}, series is {:}, shape is {:}".format(i, series, shape)
print(infos)
import shutil
shutil.move(file, os.path.join(dst_dir, "CTinfo_old.npz"))
np.savez_compressed(file, info=infos)
print("Save all scan infos to {:s}".format(file))
def resample_pos(label, thickness, spacing, new_spacing=[1, 1, 1], imgshape=None):
"""
:param label: (x, y, z, d) in original resolution
:param thickness: float z
:param spacing: original resolution, list [y, x]
:param new_spacing: new resolution, list [z, y, x]