-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathprocessor.py
executable file
·4502 lines (3979 loc) · 187 KB
/
processor.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
from email.mime import image
import os
join=os.path.join
from turtle import left
from PIL import Image
import pandas as pd
import json
import numpy as np
from tqdm import tqdm
from pathlib import Path
from torchvision import transforms
import torch
import cv2
import monai
import math
import SimpleITK as sitk
import shutil
import argparse
import dicom2nifti
import nibabel as nib
import nrrd
from einops import rearrange, repeat, reduce
import scipy.io
class Process_Wrapper():
def __init__(self, jsonl_dir):
self.jsonl_dir = jsonl_dir
def preprocess_ACDC(self, root_path='/mnt/hwfile/medai/zhaoziheng/SAM/SAM/ACDC/database'):
"""
https://www.creatis.insa-lyon.fr/Challenge/acdc/databases.html
masks_path: root_path/training/patientxxx/patientxxx_framexx_gt.nii.gz
images_path: root_path/training/patientxxx/patientxxx_framexx.nii.gz
"""
dataset = 'ACDC'
labels = ['left ventricle cavity', 'right ventricle cavity', 'myocardium']
modality = 'MRI'
data = []
mask_ls = Path(root_path).glob('**/*_gt.nii.gz')
for mask in mask_ls:
image = str(mask).replace('_gt.nii.gz', '.nii.gz')
split = 'train' if 'train' in image else 'test'
patient_id = image.split('/')[-1] # patientxxx_framexx.nii.gz
data.append({
'image':image,
'mask':str(mask),
'label':labels,
'modality':modality,
'dataset':dataset,
'official_split':split,
'patient_id':patient_id
})
Path(self.jsonl_dir).mkdir(exist_ok=True, parents=True)
with open(f"{self.jsonl_dir}/{dataset}.jsonl", 'w') as f:
for datum in data:
f.write(json.dumps(datum)+'\n')
def preprocess_HAN_Seg(self, root_path='/mnt/hwfile/medai/zhaoziheng/SAM/SAM/HAN_Seg/HaN-Seg/set_1'):
"""
https://han-seg2023.grand-challenge.org
images_path: root_path/case_xx/case_xx_IMG_CT.nrrd
masks_path: root_path/case_xx/case_xx_OAR_xxx.seg.nrrd
3D. segmentation on CT scans of 42 patients, annotating 30 organs-at-risks, labels are translated to OAR description
each OAR annotation is stored in an individual file, we preprocess them to dervie masks with multi-channels
nrrd -> nii.gz
NOTE: The dataset also contains MRI-T1 scans, but the shape of them DO NOT match that of the seg annotation
"""
dataset = 'HAN_Seg'
descriptive_labels = [
'Arytenoid',
'Brainstem',
'Buccal Mucosa',
'Left Carotid artery',
'Right Carotid artery',
'Cervical esophagus',
'Left Cochlea',
'Right Cochlea',
'Cricopharyngeal inlet',
'Left Anterior eyeball',
'Right Anterior eyeball',
'Left Posterior eyeball',
'Right Posterior eyeball',
'Left Lacrimal gland',
'Right Lacrimal gland',
'Larynx - glottis',
'Larynx - supraglottic',
'Lips',
'Mandible',
'Optic chiasm',
'Left Optic nerve',
'Right Optic nerve',
'Oral cavity',
'Left Parotid gland',
'Right Parotid gland',
'Pituitary gland',
'Spinal cord',
'Left Submandibular gland',
'Right Submandibular gland',
'Thyroid'
]
labels =[
'Arytenoid',
'Brainstem',
'BuccalMucosa',
'A_Carotid_L',
'A_Carotid_R',
'Esophagus_S',
'Cochlea_L',
'Cochlea_R',
'Cricopharyngeus',
'Eye_AL',
'Eye_AR',
'Eye_PL',
'Eye_PR',
'Glnd_Lacrimal_L',
'Glnd_Lacrimal_R',
'Glottis',
'Larynx_SG',
'Lips',
'Bone_Mandible',
'OpticChiasm',
'OpticNrv_L',
'OpticNrv_R',
'Cavity_Oral',
'Parotid_L',
'Parotid_R',
'Pituitary',
'SpinalCord',
'Glnd_Submand_L',
'Glnd_Submand_R',
'Glnd_Thyroid'
]
modality = 'CT'
data = []
for dir in tqdm(os.listdir(root_path)):
if dir == 'case_19': # case_19 unmatched image and mask
continue
if 'case' in dir:
mask_paths = {}
for f in os.listdir(os.path.join(root_path, dir)):
if f.endswith('IMG_CT.nii.gz'):
image_path = os.path.join(root_path, dir, f)
elif 'OAR' in f:
label = f.split('.seg.nrrd')[0].split('OAR_')[-1]
mask_paths[label] = os.path.join(root_path, dir, f)
# convert nrrd to nii.gz
# img = sitk.ReadImage(image_path)
# sitk.WriteImage(img, image_path.replace('nrrd', 'nii.gz'))
image_nib = nib.load(image_path.replace('nrrd', 'nii.gz'))
image_np = image_nib.get_fdata()
mask = []
for label in tqdm(labels):
if label not in mask_paths:
mask.append(np.zeros_like(image_np))
else:
np_mask, _ = nrrd.read(mask_paths[label])
mask.append(np_mask) # [1, 1024, 1024, 197]
mask = np.stack(mask, axis=0) # NHWD
nii_mask = nib.Nifti1Image(mask, image_nib.affine, image_nib.header)
nib.save(nii_mask, os.path.join(root_path, dir, 'label.nii.gz'))
print(f"save to {os.path.join(root_path, dir, 'label.nii.gz')}")
data.append({
'image':image_path.replace('nrrd', 'nii.gz'),
'mask':os.path.join(root_path, dir, 'label.nii.gz'),
'label':descriptive_labels,
'modality':modality,
'dataset':dataset,
'official_split':'unknown',
'patient_id':dir,
})
Path(self.jsonl_dir).mkdir(exist_ok=True, parents=True)
with open(f"{self.jsonl_dir}/{dataset}.jsonl", 'w') as f:
for datum in data:
f.write(json.dumps(datum)+'\n')
def preprocess_CHAOS_CT(self, root_path='/mnt/hwfile/medai/zhaoziheng/SAM/SAM/CHAOS/Train_Sets/CT'):
"""
https://chaos.grand-challenge.org
Segmentation of liver from computed tomography (CT) data sets.
.dcm -> nii.gz;
20 training scans.
images_path: root_path/xx/DICOM_anon/xxxx.dcm
masks_path: root_path/xx/Ground/liver_GT_xxxx.png
"""
dataset = 'CHAOS_CT'
labels = ['liver']
data = []
monai_loader = monai.transforms.LoadImage(image_only=True)
for case in tqdm(os.listdir(root_path)): # 1
# convert image to nifti
dicom2nifti.convert_directory(os.path.join(root_path, case, 'DICOM_anon'), os.path.join(root_path, case), compression=True)
print(f"save {os.path.join(root_path, case, 'DICOM_anon')} to {os.path.join(root_path, case)}")
for file_name in os.listdir(os.path.join(root_path, case)):
if '.nii.gz' in file_name and file_name != 'label.nii.gz':
image_path = os.path.join(root_path, case, file_name)
image_nib = nib.load(image_path)
masks = []
mask_paths = os.listdir(os.path.join(root_path, case, 'Ground'))
mask_paths = sorted(mask_paths)
for p in mask_paths:
mask = monai_loader(os.path.join(root_path, case, 'Ground', p))
masks.append(mask)
masks = np.stack(masks, axis=0) # (D, 256, 256)
masks = np.flip(np.flip(masks, axis=0), axis=-1)
masks = repeat(masks, 'd h w -> c h w d', c=1)
# convert mask to nifti as well
concat_mask_nib = nib.Nifti1Image(masks, image_nib.affine, image_nib.header)
nib.save(concat_mask_nib, os.path.join(root_path, case, 'label.nii.gz'))
print(f"save to {os.path.join(root_path, case, 'label.nii.gz')}")
data.append({
'image':image_path,
'mask':os.path.join(root_path, case, 'label.nii.gz'),
'label':labels,
'modality':'CT',
'dataset':dataset,
'official_split':'train',
'patient_id':case,
})
Path(self.jsonl_dir).mkdir(exist_ok=True, parents=True)
with open(f"{self.jsonl_dir}/{dataset}.jsonl", 'w') as f:
for datum in data:
f.write(json.dumps(datum)+'\n')
def preprocess_CHAOS_MRI(self, root_path='/mnt/hwfile/medai/zhaoziheng/SAM/SAM/CHAOS/Train_Sets/MR'):
"""
https://chaos.grand-challenge.org
.dcm -> nii.gz;
40 MRI scans.
T1_in_images_path: root_path/xx/T1DUAL/DICOM_anon/OutPhase/xxx.dcm
T1_out_images_path: root_path/xx/T1DUAL/DICOM_anon/InPhase/xxx.dcm
T1_masks_path: root_path/xx/T1DUAL/Ground/xxx.png
T2_images_path: root_path/xx/T2SPIR/DICOM_anon/xxx.dcm
T2_masks_path: root_path/xx/T2SPIR/Ground/xxx.png
Segmentation of four abdominal organs (i.e. liver, spleen, right and left kidneys)
from T1-DUAL(inPhase and outPhase are registered. Therefore, their ground truth is the same.) and T2-SPIR MRI data.
--Labeles of the four abdomen organs in the ground data are represented by four different pixel values ranges:
Liver: 63 (55<<<70)
Right kidney: 126 (110<<<135)
Left kidney: 189 (175<<<200)
Spleen: 252 (240<<<255)
"""
def mri_relabel(mask):
mask = mask.squeeze().float() # [D, H, W]
spleen = torch.where(mask>240, 1.0, 0.0).float()
l_kidney = torch.where(mask>175, mask, torch.tensor(1000.)).float()
l_kidney = torch.where(l_kidney<=200, 1.0, 0.0).float()
r_kidney = torch.where(mask>110, mask, torch.tensor(1000.)).float()
r_kidney = torch.where(r_kidney<=135, 1.0, 0.0).float()
liver = torch.where(mask>55, mask, torch.tensor(1000.)).float()
liver = torch.where(liver<=70, 1.0, 0.0).float()
return torch.stack([liver, r_kidney, l_kidney, spleen], dim=1) # [D, 4, H, W]
dataset = 'CHAOS_MRI'
labels = ['liver', 'right kidney', 'left kidney', 'spleen']
data = []
monai_loader = monai.transforms.LoadImage(image_only=True)
for case in tqdm(os.listdir(root_path)): # 1
dicom2nifti.convert_directory(os.path.join(root_path, case, 'T1DUAL/DICOM_anon/OutPhase'), os.path.join(root_path, case, 'T1DUAL/DICOM_anon/OutPhase'), compression=True)
print(f"save {os.path.join(root_path, case, 'T1DUAL/DICOM_anon/OutPhase')} to {os.path.join(root_path, case, 'T1DUAL/DICOM_anon/OutPhase')}")
for file_name in os.listdir(os.path.join(root_path, case, 'T1DUAL/DICOM_anon/OutPhase')):
if '.nii.gz' in file_name:
out_image_path = os.path.join(root_path, case, 'T1DUAL/DICOM_anon/OutPhase', file_name)
dicom2nifti.convert_directory(os.path.join(root_path, case, 'T1DUAL/DICOM_anon/InPhase'), os.path.join(root_path, case, 'T1DUAL/DICOM_anon/InPhase'), compression=True)
print(f"save {os.path.join(root_path, case, 'T1DUAL/DICOM_anon/InPhase')} to {os.path.join(root_path, case, 'T1DUAL/DICOM_anon/InPhase')}")
for file_name in os.listdir(os.path.join(root_path, case, 'T1DUAL/DICOM_anon/InPhase')):
if '.nii.gz' in file_name:
in_image_path = os.path.join(root_path, case, 'T1DUAL/DICOM_anon/InPhase', file_name)
image_nib = nib.load(in_image_path)
mask_paths = os.listdir(os.path.join(root_path, case, 'T1DUAL/Ground'))
mask_paths = sorted(mask_paths)
masks = []
for p in mask_paths:
mask = monai_loader(os.path.join(root_path, case, 'T1DUAL/Ground', p))
masks.append(mask)
masks = np.stack(masks, axis=0) # (D, 256, 256)
masks = mri_relabel(torch.tensor(masks)).numpy() # (D, 4, 256, 256)
masks = rearrange(masks, 'd c h w -> c h w d')
masks = np.flip(masks, axis=2)
concat_mask_nib = nib.Nifti1Image(masks, image_nib.affine, image_nib.header)
nib.save(concat_mask_nib, os.path.join(root_path, case, 't1_label.nii.gz'))
print(f"save to {os.path.join(root_path, case, 't1_label.nii.gz')}")
data.append({
'image':out_image_path,
'mask':os.path.join(root_path, case, 't1_label.nii.gz'),
'label':labels,
'modality':'MRI T1',
'dataset':dataset,
'official_split':'train',
'patient_id':case,
})
data.append({
'image':in_image_path,
'mask':os.path.join(root_path, case, 't1_label.nii.gz'),
'label':labels,
'modality':'MRI T1',
'dataset':dataset,
'official_split':'train',
'patient_id':case,
})
dicom2nifti.convert_directory(os.path.join(root_path, case, 'T2SPIR/DICOM_anon'), os.path.join(root_path, case, 'T2SPIR/DICOM_anon'), compression=True)
print(f"save {os.path.join(root_path, case, 'T2SPIR/DICOM_anon')} to {os.path.join(root_path, case, 'T2SPIR/DICOM_anon')}")
for file_name in os.listdir(os.path.join(root_path, case, 'T2SPIR/DICOM_anon')):
if '.nii.gz' in file_name:
t2_image_path = os.path.join(root_path, case, 'T2SPIR/DICOM_anon', file_name)
image_nib = nib.load(t2_image_path)
mask_paths = os.listdir(os.path.join(root_path, case, 'T2SPIR/Ground'))
mask_paths = sorted(mask_paths)
masks = []
for p in mask_paths:
mask = monai_loader(os.path.join(root_path, case, 'T2SPIR/Ground', p))
masks.append(mask)
masks = np.stack(masks, axis=0) # (D, 256, 256)
masks = mri_relabel(torch.tensor(masks)).numpy() # (D, 4, 256, 256)
masks = rearrange(masks, 'd c h w -> c h w d')
masks = np.flip(masks, axis=2)
concat_mask_nib = nib.Nifti1Image(masks, image_nib.affine, image_nib.header)
nib.save(concat_mask_nib, os.path.join(root_path, case, 't2_label.nii.gz'))
print(f"save to {os.path.join(root_path, case, 't2_label.nii.gz')}")
data.append({
'image':t2_image_path,
'mask':os.path.join(root_path, case, 't2_label.nii.gz'),
'label':labels,
'modality':'MRI T2',
'dataset':dataset,
'official_split':'train',
'patient_id':case,
})
Path(self.jsonl_dir).mkdir(exist_ok=True, parents=True)
with open(f"{self.jsonl_dir}/{dataset}.jsonl", 'w') as f:
for datum in data:
f.write(json.dumps(datum)+'\n')
def preprocess_AbdomenCT1K(self, root_path='/mnt/hwfile/medai/zhaoziheng/SAM/SAM/AbdomenCT-1K'):
"""
https://github.com/JunMa11/AbdomenCT-1K#50-cases-with-13-annotated-organs-download-zenodo
.
├── Images
│ ├── Case_00001_0000.nii.gz
... ...
│ └── Case_01062_0000.nii.gz
├── Masks
│ ├── Case_00001.nii.gz
... ...
│ └── Case_01062.nii.gz
"""
dataset = 'AbdomenCT1K'
labels = ['liver', 'kidney', 'spleen', 'pancreas']
modality = 'CT'
data = []
for case in tqdm(os.listdir(os.path.join(root_path, 'Masks'))): # Case_00001.nii.gz
mask_path = os.path.join(root_path, 'Masks', case)
image_path = os.path.join(root_path, 'Images', case[:-7]+'_0000.nii.gz')
data.append({
'image':image_path,
'mask':mask_path,
'label':labels,
'modality':modality,
'dataset':dataset,
'official_split':'unknown',
'patient_id':case,
})
Path(self.jsonl_dir).mkdir(exist_ok=True, parents=True)
with open(f"{self.jsonl_dir}/{dataset}.jsonl", 'w') as f:
for datum in data:
f.write(json.dumps(datum)+'\n')
def preprocess_ISLES2022(self, root_path='/mnt/hwfile/medai/zhaoziheng/SAM/SAM/ISLES22/ISLES'):
"""
https://isles22.grand-challenge.org
ISLES/dataset
├── derivatives
| ├── sub-strokecase0001
| | └──ses-0001
| | └── sub-strokecase0001_ses-0001_msk.nii.gz (seg path)
| |
| ├── sub-strokecase0002
| | └──ses-0002
| | └── sub-strokecase0002_ses-0001_msk.nii.gz
| └── ... ...
|
└── rawdata
├── sub-strokecase0001
| └──ses-0001
| ├── sub-strokecase0001_ses-0001_adc.nii.gz (img path)
| ├── sub-strokecase0001_ses-0001_dwi.nii.gz (img path)
| └── sub-strokecase0001_ses-0001_flair.nii.gz (not consistent with segmentation annotation)
|
├── sub-strokecase0002
| └──ses-0001
| ├── sub-strokecase0001_ses-0001_adc.nii.gz
| ├── sub-strokecase0001_ses-0001_dwi.nii.gz
| └── sub-strokecase0001_ses-0001_flair.nii.gz
└── ... ...
"""
dataset = 'ISLES2022'
labels = ['stroke']
data = []
for case in os.listdir(os.path.join(root_path, 'dataset/rawdata')):
if 'sub-strokecase' not in case: # sub-strokecasexxx_ses-xxxx_adc.nii.gz
continue
for m, modality in zip(['adc', 'dwi'], ['MRI ADC', 'MRI DWI']):
img_path = os.path.join(root_path, 'dataset/rawdata', case, 'ses-0001', case+'_ses-0001_'+m+'.nii.gz')
msk_path = os.path.join(root_path, 'dataset/derivatives', case, 'ses-0001', case+'_ses-0001_msk.nii.gz')
data.append({
'image':img_path,
'mask':msk_path,
'label':labels,
'modality':modality,
'dataset':dataset,
'official_split':'unknown',
'patient_id':case,
})
Path(self.jsonl_dir).mkdir(exist_ok=True, parents=True)
with open(f"{self.jsonl_dir}/{dataset}.jsonl", 'w') as f:
for datum in data:
f.write(json.dumps(datum)+'\n')
def preprocess_MRSpineSeg(self, root_path='/mnt/hwfile/medai/zhaoziheng/SAM/SAM/MRSpineSeg_Challenge_SMU/train'):
"""
https://www.spinesegmentation-challenge.com/?page_id=1162
multi-class segmentation of vertebrae and intervertebral discs
img paths: root_path/MR/Casexxx.nii.gz
mask paths: root_path/Mask/mask_casexxx.nii.gz
"""
dataset = 'MRSpineSeg'
labels = [ # label value 1 to 19
'sacrum',
'lumbar vertebrae 5 (L5)',
'lumbar vertebrae 4 (L4)',
'lumbar vertebrae 3 (L3)',
'lumbar vertebrae 2 (L2)',
'lumbar vertebrae 1 (L1)',
'thoracic vertebrae 12 (T12)',
'thoracic vertebrae 11 (T11)',
'thoracic vertebrae 10 (T10)',
'thoracic vertebrae 9 (T9)',
'intervertebral discs between lumbar vertebrae 5 (L5) and sacrum',
'intervertebral discs between lumbar vertebrae 4 (L4) and lumbar vertebrae 5 (L5)',
'intervertebral discs between lumbar vertebrae 3 (L3) and lumbar vertebrae 4 (L4)',
'intervertebral discs between lumbar vertebrae 2 (L2) and lumbar vertebrae 3 (L3)',
'intervertebral discs between lumbar vertebrae 1 (L1) and lumbar vertebrae 2 (L2)',
'intervertebral discs between thoracic vertebrae 12 (T12) and lumbar vertebrae 1 (L1)',
'intervertebral discs between thoracic vertebrae 11 (T11) and thoracic vertebrae 12 (T12)',
'intervertebral discs between thoracic vertebrae 10 (T10) and thoracic vertebrae 11 (T11)',
'intervertebral discs between thoracic vertebrae 9 (T9) and thoracic vertebrae 10 (T10)'
]
modality = 'MRI'
data = []
for case in os.listdir(os.path.join(root_path, 'MR')):
case_id = case.split('Case')[-1][:-7] # Case113.nii.gz -> 113
mask_path = os.path.join(root_path, 'Mask', 'mask_case'+case_id+'.nii.gz')
data.append({
'image':os.path.join(root_path, 'MR', case),
'mask':mask_path,
'label':labels,
'modality':modality,
'dataset':dataset,
'official_split':'train',
'patient_id': case,
})
Path(self.jsonl_dir).mkdir(exist_ok=True, parents=True)
with open(f"{self.jsonl_dir}/{dataset}.jsonl", 'w') as f:
for datum in data:
f.write(json.dumps(datum)+'\n')
def preprocess_LUNA16(self, root_path='/mnt/hwfile/medai/zhaoziheng/SAM/SAM/LUNA16'):
"""
https://luna16.grand-challenge.org/Data/
subset0.zip to subset9.zip: 10 zip files which contain all CT images
(not included) annotations.csv: csv file that contains the annotations used as reference standard for the 'nodule detection' track
lung segmentation: a directory that contains the lung segmentation for CT images computed using automatic algorithms
LUNA16
├── part1
| ├── annotation.csv (annotation file)
├── subset0
| ├── 1.3.6.1.4.1.14519.5.2.1.6279.6001.109002525524522225658609808059.mhd (img paths)
| ├── 1.3.6.1.4.1.14519.5.2.1.6279.6001.109002525524522225658609808059.raw
| └── ... ...
└── ... ...
"""
dataset = 'LUNA16'
labels = ['left lung', 'right lung', 'trachea']
modality = 'CT'
data = []
# iter over scans and generate masks
for part in tqdm(range(10)):
for f in os.listdir(os.path.join(root_path, 'subset%d'%part)):
if not f.endswith('.mhd'): # 1.3.6.1.4.1.14519.5.2.1.6279.6001.109002525524522225658609808059.mhd
continue
lung_seg_path = f'{root_path}/part1/seg-lungs-LUNA16/{f}'
if not os.path.exists(lung_seg_path):
continue
# optional) trans to nii.gz
# img = sitk.ReadImage(join(root_path, 'subset%d'%part, f))
# sitk.WriteImage(img, join(root_path, 'subset%d'%part, f.replace('.mhd', '.nii.gz')))
# mask = sitk.ReadImage(lung_seg_path)
# sitk.WriteImage(mask, lung_seg_path.replace('.mhd', '.nii.gz'))
data.append({
# 'image':join(root_path, 'subset%d'%part, f.replace('.mhd', '.nii.gz')),
# 'mask':lung_seg_path.replace('.mhd', '.nii.gz'),
'image':join(root_path, 'subset%d'%part, f),
'mask':lung_seg_path,
'label':labels,
'modality':modality,
'dataset':dataset,
'official_split': 'unknown',
'patient_id': f.split('.mhd')[0]
})
Path(self.jsonl_dir).mkdir(exist_ok=True, parents=True)
with open(f"{self.jsonl_dir}/{dataset}.jsonl", 'w') as f:
for datum in data:
f.write(json.dumps(datum)+'\n')
def preprocess_MSD_Cardiac(self, root_path='/mnt/hwfile/medai/zhaoziheng/SAM/SAM/MSD/Task02_Heart'):
"""
http://medicaldecathlon.com/#tasks
Mono-modal MRI
20 3D volumes
"modality": {
"0": "MRI"
},
"labels": {
"0": "background",
"1": "left atrium"
},
img paths: root_path/imagesTr/la_001.nii.gz
mask paths: root_path/labelsTr/la_001.nii.gz
"""
dataset = 'MSD_Cardiac'
labels = ['left atrium']
modality = 'MRI'
data = []
for case in os.listdir(os.path.join(root_path, 'imagesTr')): # xxx_001.nii.gz
if case[0] == '.': # after untar, seems that every xxx.nii.gz is companied with another .xxx.nii.gz
continue
mask_path = os.path.join(root_path, 'labelsTr', case)
img_path = os.path.join(root_path, 'imagesTr', case)
data.append({
'image':img_path,
'mask':mask_path,
'label':labels,
'modality':modality,
'dataset':dataset,
'official_split':'train',
'patient_id':case,
})
Path(self.jsonl_dir).mkdir(exist_ok=True, parents=True)
with open(f"{self.jsonl_dir}/{dataset}.jsonl", 'w') as f:
for datum in data:
f.write(json.dumps(datum)+'\n')
def preprocess_MSD_Liver(self, root_path='/mnt/hwfile/medai/zhaoziheng/SAM/SAM/MSD/Task03_Liver'):
"""
http://medicaldecathlon.com/#tasks
Portal venous phase CT
131 3D volumes
"modality": {
"0": "CT"
},
"labels": {
"0": "background",
"1": "liver",
"2": "cancer"
}
img paths: root_path/imagesTr/liver_0.nii.gz
mask paths: root_path/labelsTr/liver_0.nii.gz
"""
dataset = 'MSD_Liver'
labels = ['liver', 'liver tumor']
modality = 'CT'
data = []
for case in os.listdir(os.path.join(root_path, 'imagesTr')): # xxx_001.nii.gz
if case[0] == '.': # after untar, seems that every xxx.nii.gz is companied with another .xxx.nii.gz
continue
mask_path = os.path.join(root_path, 'labelsTr', case)
img_path = os.path.join(root_path, 'imagesTr', case)
data.append({
'image':img_path,
'mask':mask_path,
'label':labels,
'modality':modality,
'dataset':dataset,
'official_split': 'train',
'patient_id':case,
})
Path(self.jsonl_dir).mkdir(exist_ok=True, parents=True)
with open(f"{self.jsonl_dir}/{dataset}.jsonl", 'w') as f:
for datum in data:
f.write(json.dumps(datum)+'\n')
def preprocess_MSD_Hippocampus(self, root_path='/mnt/hwfile/medai/zhaoziheng/SAM/SAM/MSD/Task04_Hippocampus'):
"""
http://medicaldecathlon.com/#tasks
Mono-modal MRI
394 3D volumes
"modality": {
"0": "MRI"
},
"labels": {
"0": "background",
"1": "Anterior",
"2": "Posterior"
},
img paths: root_path/imagesTr/hippocampus_001.nii.gz
mask paths: root_path/labelsTr/hippocampus_001.nii.gz
"""
dataset = 'MSD_Hippocampus'
labels = ['Anterior Hippocampus', 'Posterior Hippocampus']
modality = 'MRI'
data = []
for case in os.listdir(os.path.join(root_path, 'imagesTr')): # xxx_001.nii.gz
if case[0] == '.': # after untar, seems that every xxx.nii.gz is companied with another .xxx.nii.gz
continue
mask_path = os.path.join(root_path, 'labelsTr', case)
img_path = os.path.join(root_path, 'imagesTr', case)
data.append({
'image':img_path,
'mask':mask_path,
'label':labels,
'modality':modality,
'dataset':dataset,
'official_split': 'train',
'patient_id':case,
})
Path(self.jsonl_dir).mkdir(exist_ok=True, parents=True)
with open(f"{self.jsonl_dir}/{dataset}.jsonl", 'w') as f:
for datum in data:
f.write(json.dumps(datum)+'\n')
def preprocess_MSD_Prostate(self, root_path='/mnt/hwfile/medai/zhaoziheng/SAM/SAM/MSD/Task05_Prostate'):
"""
http://medicaldecathlon.com/#tasks
Multimodal MR (T2, ADC)
32 4D volumes
"modality": {
"0": "T2",
"1": "ADC"
},
"labels": {
"0": "background",
"1": "TZ",
"2": "PZ"
},
img paths: root_path/imagesTr/prostate_00.nii.gz
mask paths: root_path/labelsTr/prostate_00.nii.gz
"""
dataset = 'MSD_Prostate'
labels = ['transition zone of prostate', 'peripheral zone of prostate']
data = []
for case in os.listdir(os.path.join(root_path, 'imagesTr')): # xxx_001.nii.gz
if case[0] == '.': # after untar, seems that every xxx.nii.gz is companied with another .xxx.nii.gz
continue
mask_path = os.path.join(root_path, 'labelsTr', case)
for mod, modality in zip(["T2", "ADC"], ["MRI T2", "MRI ADC"]):
img_path = os.path.join(root_path, 'imagesTr', case, mod)
data.append({
'image':img_path,
'mask':mask_path,
'label':labels,
'modality':modality,
'dataset':dataset,
'official_split': 'train',
'patient_id':case,
})
Path(self.jsonl_dir).mkdir(exist_ok=True, parents=True)
with open(f"{self.jsonl_dir}/{dataset}.jsonl", 'w') as f:
for datum in data:
f.write(json.dumps(datum)+'\n')
def preprocess_MSD_Lung(self, root_path='/mnt/hwfile/medai/zhaoziheng/SAM/SAM/MSD/Task06_Lung'):
"""
http://medicaldecathlon.com/#tasks
64 3D volumes
"modality": {
"0": "CT"
},
"labels": {
"0": "background",
"1": "cancer"
},
img paths: root_path/imagesTr/lung_00.nii.gz
mask paths: root_path/labelsTr/lung_00.nii.gz
"""
dataset = 'MSD_Lung'
labels = ['lung tumor']
modality = 'CT'
data = []
for case in os.listdir(os.path.join(root_path, 'imagesTr')): # xxx_001.nii.gz
if case[0] == '.': # after untar, seems that every xxx.nii.gz is companied with another .xxx.nii.gz
continue
mask_path = os.path.join(root_path, 'labelsTr', case)
img_path = os.path.join(root_path, 'imagesTr', case)
data.append({
'image':img_path,
'mask':mask_path,
'label':labels,
'modality':modality,
'dataset':dataset,
'official_split': 'train',
'patient_id':case,
})
Path(self.jsonl_dir).mkdir(exist_ok=True, parents=True)
with open(f"{self.jsonl_dir}/{dataset}.jsonl", 'w') as f:
for datum in data:
f.write(json.dumps(datum)+'\n')
def preprocess_MSD_Pancreas(self, root_path='/mnt/hwfile/medai/zhaoziheng/SAM/SAM/MSD/Task07_Pancreas'):
"""
http://medicaldecathlon.com/#tasks
282 3D volumes
"modality": {
"0": "CT"
},
"labels": {
"0": "background",
"1": "pancreas",
"2": "cancer"
},
img paths: root_path/imagesTr/pancreas_001.nii.gz
mask paths: root_path/labelsTr/pancreas_001.nii.gz
"""
dataset = 'MSD_Pancreas'
labels = ['pancreas', 'pancreas tumor']
modality = 'CT'
data = []
for case in os.listdir(os.path.join(root_path, 'imagesTr')): # xxx_001.nii.gz
if case[0] == '.': # after untar, seems that every xxx.nii.gz is companied with another .xxx.nii.gz
continue
mask_path = os.path.join(root_path, 'labelsTr', case)
img_path = os.path.join(root_path, 'imagesTr', case)
data.append({
'image':img_path,
'mask':mask_path,
'label':labels,
'modality':modality,
'dataset':dataset,
'official_split': 'train',
'patient_id':case,
})
Path(self.jsonl_dir).mkdir(exist_ok=True, parents=True)
with open(f"{self.jsonl_dir}/{dataset}.jsonl", 'w') as f:
for datum in data:
f.write(json.dumps(datum)+'\n')
def preprocess_MSD_HepaticVessel(self, root_path='/mnt/hwfile/medai/zhaoziheng/SAM/SAM/MSD/Task08_HepaticVessel'):
"""
http://medicaldecathlon.com/#tasks
303 3D volumes
"modality": {
"0": "CT"
},
"labels": {
"0": "background",
"1": "Vessel",
"2": "Tumour"
},
img paths: root_path/imagesTr/hepaticvessel_001.nii.gz
mask paths: root_path/labelsTr/hepaticvessel_001.nii.gz
"""
dataset = 'MSD_HepaticVessel'
labels = ['liver vessel', 'liver tumor']
modality = 'CT'
data = []
for case in os.listdir(os.path.join(root_path, 'imagesTr')): # xxx_001.nii.gz
if case[0] == '.': # after untar, seems that every xxx.nii.gz is companied with another .xxx.nii.gz
continue
mask_path = os.path.join(root_path, 'labelsTr', case)
img_path = os.path.join(root_path, 'imagesTr', case)
data.append({
'image':img_path,
'mask':mask_path,
'label':labels,
'modality':modality,
'dataset':dataset,
'official_split': 'train',
'patient_id':case,
})
Path(self.jsonl_dir).mkdir(exist_ok=True, parents=True)
with open(f"{self.jsonl_dir}/{dataset}.jsonl", 'w') as f:
for datum in data:
f.write(json.dumps(datum)+'\n')
def preprocess_MSD_Spleen(self, root_path='/mnt/hwfile/medai/zhaoziheng/SAM/SAM/MSD/Task09_Spleen'):
"""
http://medicaldecathlon.com/#tasks
41 3D volumes
"modality": {
"0": "CT"
},
"labels": {
"0": "background",
"1": "spleen"
},
img paths: root_path/imagesTr/spleen_2.nii.gz
mask paths: root_path/labelsTr/spleen_2.nii.gz
"""
dataset = 'MSD_Spleen'
labels = ['spleen']
modality = 'CT'
data = []
for case in os.listdir(os.path.join(root_path, 'imagesTr')): # xxx_001.nii.gz
if case[0] == '.': # after untar, seems that every xxx.nii.gz is companied with another .xxx.nii.gz
continue
mask_path = os.path.join(root_path, 'labelsTr', case)
img_path = os.path.join(root_path, 'imagesTr', case)
data.append({
'image':img_path,
'mask':mask_path,
'label':labels,
'modality':modality,
'dataset':dataset,
'official_split': 'train',
'patient_id':case,
})
Path(self.jsonl_dir).mkdir(exist_ok=True, parents=True)
with open(f"{self.jsonl_dir}/{dataset}.jsonl", 'w') as f:
for datum in data:
f.write(json.dumps(datum)+'\n')
def preprocess_MSD_Colon(self, root_path='/mnt/hwfile/medai/zhaoziheng/SAM/SAM/MSD/Task10_Colon'):
"""
http://medicaldecathlon.com/#tasks
126 3D volumes
"modality": {
"0": "CT"
},
"labels": {
"0": "background",
"1": "colon cancer primaries"
},
img paths: root_path/imagesTr/colon_001.nii.gz
mask paths: root_path/labelsTr/colon_001.nii.gz
"""
dataset = 'MSD_Colon'
labels = ['colon cancer']
modality = 'CT'
data = []
for case in os.listdir(os.path.join(root_path, 'imagesTr')): # xxx_001.nii.gz
if case[0] == '.': # after untar, seems that every xxx.nii.gz is companied with another .xxx.nii.gz
continue
mask_path = os.path.join(root_path, 'labelsTr', case)
img_path = os.path.join(root_path, 'imagesTr', case)
data.append({
'image':img_path,
'mask':mask_path,
'label':labels,
'modality':modality,
'dataset':dataset,
'official_split': 'train',
'patient_id':case,
})
Path(self.jsonl_dir).mkdir(exist_ok=True, parents=True)
with open(f"{self.jsonl_dir}/{dataset}.jsonl", 'w') as f:
for datum in data:
f.write(json.dumps(datum)+'\n')
def preprocess_SKI10(self, root_path='/mnt/hwfile/medai/zhaoziheng/SAM/SAM/SKI10Data'):
"""
https://ski10.grand-challenge.org
The goal of SKI10 was to compare different algorithms for cartilage and bone segmentation from knee MRI data.
Knee cartilage segmentation is a clinically relevant segmentation problem that has gained considerable importance in recent years.
Among others, it is used to quantify cartilage deterioration for the diagnosis of Osteoarthritis and to optimize surgical planning of knee implants.
The last training data set (images 61-100) includes corresponding ROI images; these specify regions of interest where cartilage segmentations will be evaluated.
Segmentations are multi-label images with the following codes:
0=background, 1=femur bone, 2=femur cartilage, 3=tibia bone, 4=tibia cartilage.
img paths: root_path/training(validation)/image-xxx.mhd
mask paths: root_path/training(validation)/labels-xxx.mhd
"""
dataset = 'SKI10'
labels = ['femur bone', 'femur cartilage', 'tibia bone', 'tibia cartilage']
modality = 'MRI'
data = []