-
Notifications
You must be signed in to change notification settings - Fork 40
/
data_iterators.py
2250 lines (1790 loc) · 98.8 KB
/
data_iterators.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
import numpy as np
import utils_lung
import pathfinder
import utils
# 6% to 28% for nodules 5 to 10 mm,
prob5 = (0.01+0.06)/2.
slope10 = (0.28-prob5) / (10.-5.)
offset10 = prob5 - slope10*5.
slope20 = (0.64-0.28) / (20.-10.)
offset20 = 0.28 - slope20*10.
# and 64% to 82% for nodules >20 mm in diameter
slope25 = (0.82-0.64) / (25.-20.)
offset25 = 0.64 - slope25*20.
slope30 = (0.93-0.82) / (30.-25.)
offset30 = 0.82 - slope30*25.
# For nodules more than 3 cm in diameter, 93% to 97% are malignant
slope40 = (0.97-0.93) / (40.-30.)
offset40 = 0.93 - slope40*30.
def diameter_to_prob(diam):
# The prevalence of malignancy is 0% to 1% for nodules <5 mm,
if diam < 5:
p = prob5*diam/5.
elif diam < 10:
p = slope10*diam+offset10
elif diam < 20:
p = slope20*diam+offset20
elif diam < 25:
p = slope25*diam+offset25
elif diam < 30:
p = slope30*diam+offset30
else:
p = slope40 * diam + offset40
return np.clip(p ,0.,1.)
class LunaDataGenerator(object):
def __init__(self, data_path, transform_params, data_prep_fun, rng,
random, infinite, patient_ids=None, **kwargs):
self.patient_ids = patient_ids
if patient_ids:
self.patient_paths = [data_path + '/' + p + '.mhd' for p in patient_ids]
else:
patient_paths = utils_lung.get_patient_data_paths(data_path)
self.patient_paths = [p for p in patient_paths if '.mhd' in p]
self.id2annotations = utils_lung.read_luna_annotations(pathfinder.LUNA_LABELS_PATH)
self.nsamples = len(self.patient_paths)
self.data_path = data_path
self.rng = rng
self.random = random
self.infinite = infinite
self.data_prep_fun = data_prep_fun
self.transform_params = transform_params
def generate(self):
while True:
rand_idxs = np.arange(self.nsamples)
if self.random:
self.rng.shuffle(rand_idxs)
for pos in xrange(0, len(rand_idxs)):
idx = rand_idxs[pos]
patient_path = self.patient_paths[idx]
pid = utils_lung.extract_pid_filename(patient_path)
img, origin, pixel_spacing = utils_lung.read_mhd(patient_path)
x, y, annotations, tf_matrix = self.data_prep_fun(data=img,
pixel_spacing=pixel_spacing,
luna_annotations=
self.id2annotations[pid],
luna_origin=origin)
x = np.float32(x)[None, None, :, :, :]
y = np.float32(y)[None, None, :, :, :]
yield x, y, None, annotations, tf_matrix, pid
if not self.infinite:
break
class LunaSimpleDataGenerator(object):
def __init__(self, data_path, patient_ids=None, **kwargs):
self.patient_ids = patient_ids
self.data_path = data_path
self.file_extension = '.pkl' if 'pkl' in data_path else '.mhd'
if patient_ids:
self.patient_paths = [data_path + '/' + p + self.file_extension for p in patient_ids]
else:
patient_paths = utils_lung.get_patient_data_paths(data_path)
self.patient_paths = [p for p in patient_paths if self.file_extension in p]
self.nsamples = len(self.patient_paths)
print self.data_path
def generate(self):
for patient_path in self.patient_paths:
pid = utils_lung.extract_pid_filename(patient_path)
img, origin, pixel_spacing = utils_lung.read_pkl(patient_path) \
if self.file_extension == '.pkl' else utils_lung.read_mhd(patient_path)
x = np.float32(img)
yield x, pid
class LunaScanPositiveDataGenerator(LunaDataGenerator):
def __init__(self, data_path, transform_params, data_prep_fun, rng,
random, infinite, patient_ids=None, **kwargs):
super(LunaScanPositiveDataGenerator, self).__init__(data_path, transform_params, data_prep_fun, rng,
random, infinite, patient_ids, **kwargs)
patient_ids_all = [utils_lung.extract_pid_filename(p) for p in self.patient_paths]
patient_ids_pos = [pid for pid in patient_ids_all if pid in self.id2annotations.keys()]
self.patient_paths = [data_path + '/' + p + '.mhd' for p in patient_ids_pos]
self.nsamples = len(self.patient_paths)
class LunaScanPositiveLungMaskDataGenerator(LunaDataGenerator):
def __init__(self, data_path, batch_size, transform_params, data_prep_fun, rng,
full_batch, random, infinite, patient_ids=None, **kwargs):
super(LunaScanPositiveLungMaskDataGenerator, self).__init__(data_path, transform_params,
data_prep_fun, rng,
random, infinite, patient_ids, **kwargs)
def generate(self):
while True:
rand_idxs = np.arange(self.nsamples)
if self.random:
self.rng.shuffle(rand_idxs)
for pos in xrange(0, len(rand_idxs)):
idx = rand_idxs[pos]
patient_path = self.patient_paths[idx]
pid = utils_lung.extract_pid_filename(patient_path)
img, origin, pixel_spacing = utils_lung.read_mhd(patient_path)
x, y, lung_mask, annotations, tf_matrix = self.data_prep_fun(data=img,
pixel_spacing=pixel_spacing,
luna_annotations=
self.id2annotations[pid],
luna_origin=origin)
x = np.float32(x)[None, None, :, :, :]
y = np.float32(y)[None, None, :, :, :]
lung_mask = np.float32(lung_mask)[None, None, :, :, :]
yield x, y, lung_mask, annotations, tf_matrix, pid
if not self.infinite:
break
class LunaScanMaskPositiveDataGenerator(LunaDataGenerator):
def __init__(self, data_path, seg_data_path, batch_size, transform_params, data_prep_fun, rng,
full_batch, random, infinite, patient_ids=None, **kwargs):
super(LunaScanMaskPositiveDataGenerator, self).__init__(data_path, transform_params,
data_prep_fun, rng,
random, infinite, patient_ids, **kwargs)
self.seg_data_path = seg_data_path
self.mask_paths = [seg_data_path + '/' + p + '.mhd' for p in self.patient_ids]
def generate(self):
while True:
rand_idxs = np.arange(self.nsamples)
if self.random:
self.rng.shuffle(rand_idxs)
for pos in xrange(0, len(rand_idxs)):
idx = rand_idxs[pos]
ct_scan_path = self.patient_paths[idx]
mask_path = self.mask_paths[idx]
pid = utils_lung.extract_pid_filename(ct_scan_path)
ct_scan, ct_origin, ct_pixel_spacing = utils_lung.read_mhd(ct_scan_path)
mask, mask_origin, mask_pixel_spacing = utils_lung.read_mhd(mask_path)
assert(sum(abs(ct_origin-mask_origin)) < 1e-9)
assert(sum(abs(ct_pixel_spacing-mask_pixel_spacing)) < 1e-9)
ct, lung_mask, annotations, tf_matrix = self.data_prep_fun(ct_scan=ct_scan, mask=mask,
pixel_spacing=ct_pixel_spacing,
luna_annotations=
self.id2annotations[pid],
luna_origin=ct_origin)
ct = np.float32(ct)[None, None, :, :, :]
lung_mask = np.float32(lung_mask)[None, None, :, :, :]
yield ct, lung_mask, annotations, tf_matrix, pid
if not self.infinite:
break
#for lung segmentation, does not work yet
class PatchLunaDataGenerator(object):
def __init__(self, ct_data_path, seg_data_path, batch_size, transform_params, data_prep_fun, rng,
full_batch, random, infinite, patient_ids=None, **kwargs):
if patient_ids:
self.patient_ids = patient_ids
#self.patient_paths = [data_path + '/' + p + '.mhd' for p in patient_ids]
else:
patient_paths = utils_lung.get_patient_data_paths(data_path)
#self.patient_paths = [p for p in patient_paths if '.mhd' in p]
self.patient_ids = [utils_lung.extract_pid_filename(p) for p in self.patient_paths]\
self.nsamples = len(self.patient_ids)
self.ct_data_path = ct_data_path
self.seg_data_path = seg_data_path
self.rng = rng
self.random = random
self.infinite = infinite
self.data_prep_fun = data_prep_fun
self.transform_params = transform_params
self.batch_size = batch_size
self.full_batch = full_batch
def generate(self):
while True:
rand_idxs = np.arange(self.nsamples)
if self.random:
self.rng.shuffle(rand_idxs)
for pos in xrange(0, len(rand_idxs), self.batch_size):
idxs_batch = rand_idxs[pos:pos + self.batch_size]
nb = len(idxs_batch)
# allocate batches
x_batch = np.zeros((nb, 1) + self.transform_params['patch_size'], dtype='float32')
y_batch = np.zeros((nb, 1) + self.transform_params['patch_size'], dtype='float32')
patients_ids = []
for i, idx in enumerate(idxs_batch):
pid = self.patient_ids[idx]
ct_path = self.ct_data_path + pid + '.mhd'
seg_path = self.seg_data_path + pid + '.mhd'
patients_ids.append(pid)
ct_img, ct_origin, ct_pixel_spacing = utils_lung.read_mhd(ct_path)
seg_img, seg_origin, seg_pixel_spacing = utils_lung.read_mhd(seg_path)
assert(np.sum(ct_origin-seg_origin) < 1e-9)
assert(np.sum(ct_pixel_spacing-seg_pixel_spacing) < 1e-9)
print 'ct_img.shape', ct_img.shape
print 'seg_img.shape', seg_img.shape
w,h,d = self.transform_params['patch_size']
patch_center = [self.rng.randint(w/2, ct_img.shape[0]-w/2),
self.rng.randint(h/2, ct_img.shape[1]-h/2),
self.rng.randint(d/2, ct_img.shape[1]-d/2)]
print patch_center
x_batch[i, 0, :, :, :], y_batch[i, 0, :, :, :] = self.data_prep_fun(ct_img=ct_img, seg_img=seg_img,
patch_center=patch_center,
pixel_spacing=ct_pixel_spacing,
luna_origin=ct_origin)
# y_batch[i, 0, :, :, :], = self.data_prep_fun(data=seg_img,
# patch_center=patch_center,
# pixel_spacing=seg_pixel_spacing,
# luna_origin=seg_origin)
if self.full_batch:
if nb == self.batch_size:
yield x_batch, y_batch, patients_ids
else:
yield x_batch, y_batch, patients_ids
if not self.infinite:
break
#works, tested
class LunaScanDataGenerator(object):
def __init__(self, ct_data_path, seg_data_path, patient_ids=None, **kwargs):
if patient_ids:
self.patient_ids = patient_ids
#self.patient_paths = [data_path + '/' + p + '.mhd' for p in patient_ids]
else:
patient_paths = utils_lung.get_patient_data_paths(ct_data_path)
#self.patient_paths = [p for p in patient_paths if '.mhd' in p]
self.patient_ids = [utils_lung.extract_pid_filename(p) for p in self.patient_paths]\
self.nsamples = len(self.patient_ids)
self.ct_data_path = ct_data_path
self.seg_data_path = seg_data_path
def generate(self):
for pid in self.patient_ids:
ct_path = self.ct_data_path + pid + '.mhd'
seg_path = self.seg_data_path + pid + '.mhd'
ct_img, ct_origin, ct_pixel_spacing = utils_lung.read_mhd(ct_path)
seg_img, seg_origin, seg_pixel_spacing = utils_lung.read_mhd(seg_path)
assert(np.sum(ct_origin-seg_origin) < 1e-9)
assert(np.sum(ct_pixel_spacing-seg_pixel_spacing) < 1e-9)
print 'ct_img.shape', ct_img.shape
print 'seg_img.shape', seg_img.shape
yield ct_img, seg_img, pid
class PatchPositiveLunaDataGenerator(object):
def __init__(self, data_path, batch_size, transform_params, data_prep_fun, rng,
full_batch, random, infinite, patient_ids=None, **kwargs):
self.id2annotations = utils_lung.read_luna_annotations(pathfinder.LUNA_LABELS_PATH)
if patient_ids:
self.patient_paths = [data_path + '/' + p + '.mhd' for p in patient_ids]
else:
patient_paths = utils_lung.get_patient_data_paths(data_path)
self.patient_paths = [p for p in patient_paths if '.mhd' in p]
patient_ids_all = [utils_lung.extract_pid_filename(p) for p in self.patient_paths]
patient_ids_pos = [pid for pid in patient_ids_all if pid in self.id2annotations.keys()]
self.patient_paths = [data_path + '/' + p + '.mhd' for p in patient_ids_pos]
self.nsamples = len(self.patient_paths)
self.data_path = data_path
self.rng = rng
self.random = random
self.infinite = infinite
self.data_prep_fun = data_prep_fun
self.transform_params = transform_params
self.batch_size = batch_size
self.full_batch = full_batch
def generate(self):
while True:
rand_idxs = np.arange(self.nsamples)
if self.random:
self.rng.shuffle(rand_idxs)
for pos in xrange(0, len(rand_idxs), self.batch_size):
idxs_batch = rand_idxs[pos:pos + self.batch_size]
nb = len(idxs_batch)
# allocate batches
x_batch = np.zeros((nb, 1) + self.transform_params['patch_size'], dtype='float32')
y_batch = np.zeros((nb, 1) + self.transform_params['patch_size'], dtype='float32')
patients_ids = []
for i, idx in enumerate(idxs_batch):
patient_path = self.patient_paths[idx]
id = utils_lung.extract_pid_filename(patient_path)
patients_ids.append(id)
img, origin, pixel_spacing = utils_lung.read_mhd(patient_path)
patient_annotations = self.id2annotations[id]
patch_center = patient_annotations[self.rng.randint(len(patient_annotations))]
x_batch[i, 0, :, :, :], y_batch[i, 0, :, :, :] = self.data_prep_fun(data=img,
patch_center=patch_center,
pixel_spacing=pixel_spacing,
luna_annotations=patient_annotations,
luna_origin=origin)
if self.full_batch:
if nb == self.batch_size:
yield x_batch, y_batch, patients_ids
else:
yield x_batch, y_batch, patients_ids
if not self.infinite:
break
class ValidPatchPositiveLunaDataGenerator(object):
def __init__(self, data_path, transform_params, patient_ids, data_prep_fun, **kwargs):
id2positive_annotations = utils_lung.read_luna_annotations(pathfinder.LUNA_LABELS_PATH)
self.id2positive_annotations = {}
self.id2patient_path = {}
n_positive = 0
for pid in patient_ids:
if pid in id2positive_annotations:
self.id2positive_annotations[pid] = id2positive_annotations[pid]
n_pos = len(id2positive_annotations[pid])
self.id2patient_path[pid] = data_path + '/' + pid + '.mhd'
n_positive += n_pos
self.nsamples = n_positive
self.data_path = data_path
self.data_prep_fun = data_prep_fun
self.transform_params = transform_params
def generate(self):
for pid in self.id2positive_annotations.iterkeys():
for patch_center in self.id2positive_annotations[pid]:
patient_path = self.id2patient_path[pid]
img, origin, pixel_spacing = utils_lung.read_mhd(patient_path)
patient_annotations = self.id2positive_annotations[pid]
x_batch, y_batch = self.data_prep_fun(data=img,
patch_center=patch_center,
pixel_spacing=pixel_spacing,
luna_annotations=patient_annotations,
luna_origin=origin)
x_batch = np.float32(x_batch)[None, None, :, :, :]
y_batch = np.float32(y_batch)[None, None, :, :, :]
yield x_batch, y_batch, [pid]
class CandidatesLunaDataGenerator(object):
def __init__(self, data_path, batch_size, transform_params, patient_ids, data_prep_fun, rng,
full_batch, random, infinite, positive_proportion, **kwargs):
id2positive_annotations = utils_lung.read_luna_annotations(pathfinder.LUNA_LABELS_PATH)
id2negative_annotations = utils_lung.read_luna_negative_candidates(pathfinder.LUNA_CANDIDATES_PATH)
self.file_extension = '.pkl' if 'pkl' in data_path else '.mhd'
self.id2positive_annotations = {}
self.id2negative_annotations = {}
self.patient_paths = []
n_positive, n_negative = 0, 0
for pid in patient_ids:
if pid in id2positive_annotations:
self.id2positive_annotations[pid] = id2positive_annotations[pid]
self.id2negative_annotations[pid] = id2negative_annotations[pid]
self.patient_paths.append(data_path + '/' + pid + self.file_extension)
n_positive += len(id2positive_annotations[pid])
n_negative += len(id2negative_annotations[pid])
print 'n positive', n_positive
print 'n negative', n_negative
self.nsamples = len(self.patient_paths)
print 'n patients', self.nsamples
self.data_path = data_path
self.batch_size = batch_size
self.rng = rng
self.full_batch = full_batch
self.random = random
self.infinite = infinite
self.data_prep_fun = data_prep_fun
self.transform_params = transform_params
self.positive_proportion = positive_proportion
def generate(self):
while True:
rand_idxs = np.arange(self.nsamples)
if self.random:
self.rng.shuffle(rand_idxs)
for pos in xrange(0, len(rand_idxs), self.batch_size):
idxs_batch = rand_idxs[pos:pos + self.batch_size]
nb = len(idxs_batch)
# allocate batches
x_batch = np.zeros((nb, 1) + self.transform_params['patch_size'], dtype='float32')
y_batch = np.zeros((nb, 1), dtype='float32')
patients_ids = []
for i, idx in enumerate(idxs_batch):
patient_path = self.patient_paths[idx]
id = utils_lung.extract_pid_filename(patient_path, self.file_extension)
patients_ids.append(id)
img, origin, pixel_spacing = utils_lung.read_pkl(patient_path) \
if self.file_extension == '.pkl' else utils_lung.read_mhd(patient_path)
if i < np.rint(self.batch_size * self.positive_proportion):
patient_annotations = self.id2positive_annotations[id]
else:
patient_annotations = self.id2negative_annotations[id]
patch_center = patient_annotations[self.rng.randint(len(patient_annotations))]
y_batch[i] = float(patch_center[-1] > 0)
x_batch[i, 0, :, :, :] = self.data_prep_fun(data=img,
patch_center=patch_center,
pixel_spacing=pixel_spacing,
luna_origin=origin)
if self.full_batch:
if nb == self.batch_size:
yield x_batch, y_batch, patients_ids
else:
yield x_batch, y_batch, patients_ids
if not self.infinite:
break
class CandidatesLunaDataGenerator(object):
def __init__(self, data_path, batch_size, transform_params, patient_ids, data_prep_fun, rng,
full_batch, random, infinite, positive_proportion, return_malignancy=False, **kwargs):
id2positive_annotations = utils_lung.read_luna_annotations(pathfinder.LUNA_LABELS_PATH)
id2negative_annotations = utils_lung.read_luna_negative_candidates(pathfinder.LUNA_CANDIDATES_PATH)
self.file_extension = '.pkl' if 'pkl' in data_path else '.mhd'
self.id2positive_annotations = {}
self.id2negative_annotations = {}
self.patient_paths = []
n_positive, n_negative = 0, 0
for pid in patient_ids:
if pid in id2positive_annotations:
self.id2positive_annotations[pid] = id2positive_annotations[pid]
self.id2negative_annotations[pid] = id2negative_annotations[pid]
self.patient_paths.append(data_path + '/' + pid + self.file_extension)
n_positive += len(id2positive_annotations[pid])
n_negative += len(id2negative_annotations[pid])
print 'n positive', n_positive
print 'n negative', n_negative
self.nsamples = len(self.patient_paths)
print 'n patients', self.nsamples
self.data_path = data_path
self.batch_size = batch_size
self.rng = rng
self.full_batch = full_batch
self.random = random
self.infinite = infinite
self.data_prep_fun = data_prep_fun
self.transform_params = transform_params
self.positive_proportion = positive_proportion
self.return_malignancy = return_malignancy
def generate(self):
while True:
rand_idxs = np.arange(self.nsamples)
if self.random:
self.rng.shuffle(rand_idxs)
for pos in xrange(0, len(rand_idxs), self.batch_size):
idxs_batch = rand_idxs[pos:pos + self.batch_size]
nb = len(idxs_batch)
# allocate batches
x_batch = np.zeros((nb,) + self.transform_params['patch_size'], dtype='float32')
y_batch = np.zeros((nb,), dtype='float32')
patients_ids = []
for i, idx in enumerate(idxs_batch):
patient_path = self.patient_paths[idx]
id = utils_lung.extract_pid_filename(patient_path, self.file_extension)
patients_ids.append(id)
img, origin, pixel_spacing = utils_lung.read_pkl(patient_path) \
if self.file_extension == '.pkl' else utils_lung.read_mhd(patient_path)
if i < np.rint(self.batch_size * self.positive_proportion):
patient_annotations = self.id2positive_annotations[id]
else:
patient_annotations = self.id2negative_annotations[id]
patch_center = patient_annotations[self.rng.randint(len(patient_annotations))]
if self.return_malignancy:
y_batch[i] = np.float32(diameter_to_prob(patch_center[-1]))
else:
y_batch[i] = float(patch_center[-1] > 0)
x_batch[i, :, :, :] = self.data_prep_fun(data=img,
patch_center=patch_center,
pixel_spacing=pixel_spacing,
luna_origin=origin)
if self.full_batch:
if nb == self.batch_size:
yield x_batch, y_batch, patients_ids
else:
yield x_batch, y_batch, patients_ids
if not self.infinite:
break
class CandidatesLunaValidDataGenerator(object):
def __init__(self, data_path, transform_params, patient_ids, data_prep_fun, return_malignancy=False, **kwargs):
rng = np.random.RandomState(42) # do not change this!!!
id2positive_annotations = utils_lung.read_luna_annotations(pathfinder.LUNA_LABELS_PATH)
id2negative_annotations = utils_lung.read_luna_negative_candidates(pathfinder.LUNA_CANDIDATES_PATH)
self.file_extension = '.pkl' if 'pkl' in data_path else '.mhd'
self.id2positive_annotations = {}
self.id2negative_annotations = {}
self.id2patient_path = {}
n_positive, n_negative = 0, 0
for pid in patient_ids:
if pid in id2positive_annotations:
self.id2positive_annotations[pid] = id2positive_annotations[pid]
negative_annotations = id2negative_annotations[pid]
n_pos = len(id2positive_annotations[pid])
n_neg = len(id2negative_annotations[pid])
neg_idxs = rng.choice(n_neg, size=n_pos, replace=False)
negative_annotations_selected = []
for i in neg_idxs:
negative_annotations_selected.append(negative_annotations[i])
self.id2negative_annotations[pid] = negative_annotations_selected
self.id2patient_path[pid] = data_path + '/' + pid + self.file_extension
n_positive += n_pos
n_negative += n_pos
print 'n positive', n_positive
print 'n negative', n_negative
self.nsamples = len(self.id2patient_path)
self.data_path = data_path
self.rng = rng
self.data_prep_fun = data_prep_fun
self.transform_params = transform_params
self.return_malignancy = return_malignancy
def generate(self):
for pid in self.id2positive_annotations.iterkeys():
for patch_center in self.id2positive_annotations[pid]:
patient_path = self.id2patient_path[pid]
img, origin, pixel_spacing = utils_lung.read_pkl(patient_path) \
if self.file_extension == '.pkl' else utils_lung.read_mhd(patient_path)
if self.return_malignancy:
y_batch = np.array([diameter_to_prob(patch_center[-1])], dtype='float32')
else:
y_batch = np.array([1.], dtype='float32')
x_batch = np.float32(self.data_prep_fun(data=img,
patch_center=patch_center,
pixel_spacing=pixel_spacing,
luna_origin=origin))[None, :, :, :]
yield x_batch, y_batch, [pid]
for patch_center in self.id2negative_annotations[pid]:
patient_path = self.id2patient_path[pid]
img, origin, pixel_spacing = utils_lung.read_pkl(patient_path) \
if self.file_extension == '.pkl' else utils_lung.read_mhd(patient_path)
y_batch = np.array([0.], dtype='float32')
x_batch = np.float32(self.data_prep_fun(data=img,
patch_center=patch_center,
pixel_spacing=pixel_spacing,
luna_origin=origin))[None, :, :, :]
yield x_batch, y_batch, [pid]
class FixedCandidatesLunaDataGenerator(object):
def __init__(self, data_path, transform_params, id2candidates_path, data_prep_fun, top_n=None):
self.file_extension = '.pkl' if 'pkl' in data_path else '.mhd'
self.id2candidates_path = id2candidates_path
self.id2patient_path = {}
for pid in id2candidates_path.keys():
self.id2patient_path[pid] = data_path + '/' + pid + self.file_extension
self.nsamples = len(self.id2patient_path)
self.data_path = data_path
self.data_prep_fun = data_prep_fun
self.transform_params = transform_params
self.top_n = top_n
def generate(self):
for pid in self.id2candidates_path.iterkeys():
patient_path = self.id2patient_path[pid]
print 'PATIENT', pid
candidates = utils.load_pkl(self.id2candidates_path[pid])
if self.top_n is not None:
candidates = candidates[:self.top_n]
print candidates
print 'n blobs', len(candidates)
img, origin, pixel_spacing = utils_lung.read_pkl(patient_path) \
if self.file_extension == '.pkl' else utils_lung.read_mhd(patient_path)
for candidate in candidates:
y_batch = np.array(candidate, dtype='float32')
patch_center = candidate[:3]
x_batch = np.float32(self.data_prep_fun(data=img,
patch_center=patch_center,
pixel_spacing=pixel_spacing,
luna_origin=origin))[None, None, :, :, :]
yield x_batch, y_batch, [pid]
class CandidatesLunaSizeDataGenerator(object):
def __init__(self, data_path, batch_size, transform_params, patient_ids, data_prep_fun, rng,
full_batch, random, infinite, positive_proportion, **kwargs):
id2positive_annotations = utils_lung.read_luna_annotations(pathfinder.LUNA_LABELS_PATH)
id2negative_annotations = utils_lung.read_luna_negative_candidates(pathfinder.LUNA_CANDIDATES_PATH)
self.file_extension = '.pkl' if 'pkl' in data_path else '.mhd'
self.id2positive_annotations = {}
self.id2negative_annotations = {}
self.patient_paths = []
n_positive, n_negative = 0, 0
for pid in patient_ids:
if pid in id2positive_annotations:
self.id2positive_annotations[pid] = id2positive_annotations[pid]
self.id2negative_annotations[pid] = id2negative_annotations[pid]
self.patient_paths.append(data_path + '/' + pid + self.file_extension)
n_positive += len(id2positive_annotations[pid])
n_negative += len(id2negative_annotations[pid])
print 'n positive', n_positive
print 'n negative', n_negative
self.nsamples = len(self.patient_paths)
print 'n patients', self.nsamples
self.data_path = data_path
self.batch_size = batch_size
self.rng = rng
self.full_batch = full_batch
self.random = random
self.infinite = infinite
self.data_prep_fun = data_prep_fun
self.transform_params = transform_params
self.positive_proportion = positive_proportion
def generate(self):
while True:
rand_idxs = np.arange(self.nsamples)
if self.random:
self.rng.shuffle(rand_idxs)
for pos in xrange(0, len(rand_idxs), self.batch_size):
idxs_batch = rand_idxs[pos:pos + self.batch_size]
nb = len(idxs_batch)
# allocate batches
x_batch = np.zeros((nb, 1) + self.transform_params['patch_size'], dtype='float32')
y_batch = np.zeros((nb, 1), dtype='float32')
patients_ids = []
for i, idx in enumerate(idxs_batch):
patient_path = self.patient_paths[idx]
id = utils_lung.extract_pid_filename(patient_path, self.file_extension)
patients_ids.append(id)
img, origin, pixel_spacing = utils_lung.read_pkl(patient_path) \
if self.file_extension == '.pkl' else utils_lung.read_mhd(patient_path)
if i < np.rint(self.batch_size * self.positive_proportion):
patient_annotations = self.id2positive_annotations[id]
else:
patient_annotations = self.id2negative_annotations[id]
patch_center = patient_annotations[self.rng.randint(len(patient_annotations))]
y_batch[i] = float(patch_center[-1])
x_batch[i, 0, :, :, :] = self.data_prep_fun(data=img,
patch_center=patch_center,
pixel_spacing=pixel_spacing,
luna_origin=origin)
if self.full_batch:
if nb == self.batch_size:
yield x_batch, y_batch, patients_ids
else:
yield x_batch, y_batch, patients_ids
if not self.infinite:
break
class CandidatesLunaSizeValidDataGenerator(object):
def __init__(self, data_path, transform_params, patient_ids, data_prep_fun, **kwargs):
rng = np.random.RandomState(42) # do not change this!!!
id2positive_annotations = utils_lung.read_luna_annotations(pathfinder.LUNA_LABELS_PATH)
id2negative_annotations = utils_lung.read_luna_negative_candidates(pathfinder.LUNA_CANDIDATES_PATH)
self.file_extension = '.pkl' if 'pkl' in data_path else '.mhd'
self.id2positive_annotations = {}
self.id2negative_annotations = {}
self.id2patient_path = {}
n_positive, n_negative = 0, 0
for pid in patient_ids:
if pid in id2positive_annotations:
self.id2positive_annotations[pid] = id2positive_annotations[pid]
negative_annotations = id2negative_annotations[pid]
n_pos = len(id2positive_annotations[pid])
n_neg = len(id2negative_annotations[pid])
neg_idxs = rng.choice(n_neg, size=n_pos, replace=False)
negative_annotations_selected = []
for i in neg_idxs:
negative_annotations_selected.append(negative_annotations[i])
self.id2negative_annotations[pid] = negative_annotations_selected
self.id2patient_path[pid] = data_path + '/' + pid + self.file_extension
n_positive += n_pos
n_negative += n_pos
print 'n positive', n_positive
print 'n negative', n_negative
self.nsamples = len(self.id2patient_path)
self.data_path = data_path
self.rng = rng
self.data_prep_fun = data_prep_fun
self.transform_params = transform_params
def generate(self):
for pid in self.id2positive_annotations.iterkeys():
for patch_center in self.id2positive_annotations[pid]:
patient_path = self.id2patient_path[pid]
img, origin, pixel_spacing = utils_lung.read_pkl(patient_path) \
if self.file_extension == '.pkl' else utils_lung.read_mhd(patient_path)
y_batch = np.array([[float(patch_center[-1])]], dtype='float32')
x_batch = np.float32(self.data_prep_fun(data=img,
patch_center=patch_center,
pixel_spacing=pixel_spacing,
luna_origin=origin))[None, None, :, :, :]
yield x_batch, y_batch, [pid]
for patch_center in self.id2negative_annotations[pid]:
patient_path = self.id2patient_path[pid]
img, origin, pixel_spacing = utils_lung.read_pkl(patient_path) \
if self.file_extension == '.pkl' else utils_lung.read_mhd(patient_path)
y_batch = np.array([[0.]], dtype='float32')
x_batch = np.float32(self.data_prep_fun(data=img,
patch_center=patch_center,
pixel_spacing=pixel_spacing,
luna_origin=origin))[None, None, :, :, :]
yield x_batch, y_batch, [pid]
class CandidatesLunaSizeBinDataGenerator(object):
def __init__(self, data_path, batch_size, transform_params, patient_ids, data_prep_fun, rng,
full_batch, random, infinite, positive_proportion, bin_borders = [4,8,20,50], **kwargs):
id2positive_annotations = utils_lung.read_luna_annotations(pathfinder.LUNA_LABELS_PATH)
id2negative_annotations = utils_lung.read_luna_negative_candidates(pathfinder.LUNA_CANDIDATES_PATH)
self.file_extension = '.pkl' if 'pkl' in data_path else '.mhd'
self.id2positive_annotations = {}
self.id2negative_annotations = {}
self.patient_paths = []
n_positive, n_negative = 0, 0
for pid in patient_ids:
if pid in id2positive_annotations:
self.id2positive_annotations[pid] = id2positive_annotations[pid]
self.id2negative_annotations[pid] = id2negative_annotations[pid]
self.patient_paths.append(data_path + '/' + pid + self.file_extension)
n_positive += len(id2positive_annotations[pid])
n_negative += len(id2negative_annotations[pid])
print 'n positive', n_positive
print 'n negative', n_negative
self.nsamples = len(self.patient_paths)
print 'n patients', self.nsamples
self.data_path = data_path
self.batch_size = batch_size
self.rng = rng
self.full_batch = full_batch
self.random = random
self.infinite = infinite
self.data_prep_fun = data_prep_fun
self.transform_params = transform_params
self.positive_proportion = positive_proportion
self.bin_borders = bin_borders
def generate(self):
while True:
rand_idxs = np.arange(self.nsamples)
if self.random:
self.rng.shuffle(rand_idxs)
for pos in xrange(0, len(rand_idxs), self.batch_size):
idxs_batch = rand_idxs[pos:pos + self.batch_size]
nb = len(idxs_batch)
# allocate batches
x_batch = np.zeros((nb,) + self.transform_params['patch_size'], dtype='float32')
y_batch = np.zeros((nb,), dtype='float32')
patients_ids = []
for i, idx in enumerate(idxs_batch):
patient_path = self.patient_paths[idx]
id = utils_lung.extract_pid_filename(patient_path, self.file_extension)
patients_ids.append(id)
img, origin, pixel_spacing = utils_lung.read_pkl(patient_path) \
if self.file_extension == '.pkl' else utils_lung.read_mhd(patient_path)
if i < np.rint(self.batch_size * self.positive_proportion):
patient_annotations = self.id2positive_annotations[id]
else:
patient_annotations = self.id2negative_annotations[id]
patch_center = patient_annotations[self.rng.randint(len(patient_annotations))]
diameter = patch_center[-1]
if diameter > 0.:
ybin = 0
for idx, border in enumerate(self.bin_borders):
if diameter<border:
ybin = idx
break
y_batch[i] = 1. + ybin
else:
y_batch[i] = 0.
#print 'y_batch[i]', y_batch[i], 'diameter', diameter
x_batch[i, :, :, :] = self.data_prep_fun(data=img,
patch_center=patch_center,
pixel_spacing=pixel_spacing,
luna_origin=origin)
if self.full_batch:
if nb == self.batch_size:
yield x_batch, y_batch, patients_ids
else:
yield x_batch, y_batch, patients_ids
if not self.infinite:
break
class CandidatesLunaSizeBinValidDataGenerator(object):
def __init__(self, data_path, transform_params, patient_ids, data_prep_fun, bin_borders = [4,8,20,50], **kwargs):
rng = np.random.RandomState(42) # do not change this!!!
id2positive_annotations = utils_lung.read_luna_annotations(pathfinder.LUNA_LABELS_PATH)
id2negative_annotations = utils_lung.read_luna_negative_candidates(pathfinder.LUNA_CANDIDATES_PATH)
self.file_extension = '.pkl' if 'pkl' in data_path else '.mhd'
self.id2positive_annotations = {}
self.id2negative_annotations = {}
self.id2patient_path = {}
n_positive, n_negative = 0, 0
for pid in patient_ids:
if pid in id2positive_annotations:
self.id2positive_annotations[pid] = id2positive_annotations[pid]
negative_annotations = id2negative_annotations[pid]
n_pos = len(id2positive_annotations[pid])
n_neg = len(id2negative_annotations[pid])
neg_idxs = rng.choice(n_neg, size=n_pos, replace=False)
negative_annotations_selected = []
for i in neg_idxs:
negative_annotations_selected.append(negative_annotations[i])
self.id2negative_annotations[pid] = negative_annotations_selected
self.id2patient_path[pid] = data_path + '/' + pid + self.file_extension
n_positive += n_pos
n_negative += n_pos
print 'n positive', n_positive
print 'n negative', n_negative
self.nsamples = len(self.id2patient_path)
self.data_path = data_path
self.rng = rng
self.data_prep_fun = data_prep_fun
self.transform_params = transform_params
self.bin_borders = bin_borders
def generate(self):
for pid in self.id2positive_annotations.iterkeys():
for patch_center in self.id2positive_annotations[pid]:
patient_path = self.id2patient_path[pid]
img, origin, pixel_spacing = utils_lung.read_pkl(patient_path) \
if self.file_extension == '.pkl' else utils_lung.read_mhd(patient_path)
diameter = patch_center[3]
ybin = 0
for idx, border in enumerate(self.bin_borders):
if diameter<border:
ybin = idx
break
y_batch = np.array([1. + ybin], dtype='float32')
x_batch = np.float32(self.data_prep_fun(data=img,
patch_center=patch_center,
pixel_spacing=pixel_spacing,
luna_origin=origin))[None, :, :, :]