-
Notifications
You must be signed in to change notification settings - Fork 0
/
processDicoms_FOCI.py
1298 lines (1051 loc) · 57.9 KB
/
processDicoms_FOCI.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
#!/usr/bin/env python
import os
import os.path
import sys
import time
from sys import argv, stderr, exit
import shlex, subprocess
from numpy import *
from scipy.io import loadmat, savemat
import dicom
import vtk
import Tix
import _mssql
import pymssql
from datetime import date
from operator import itemgetter, attrgetter
from dicom.contrib.pydicom_PIL import show_PIL
import gdcm
import vtkgdcm
import vtkgdcmPython
# ******************************************************************************
print "usage: processDicoms.py patient_list.txt"
print '''
Run on mass/nonmass/foci root folder processDicoms.py based on list of
patient_list.txt(list of StudyIDs in folder mass or nonmass)
"usage:"
python ../codeProject/processDicoms.py ../bUniqueTotal_formSharmila_june21_MASS.txt
-- This script will
% Copyright (C) Cristina Gallego, University of Toronto, 2012
% June 12/12 - Added dicom_dict python comparison
% June 27/12 - Now works with more added columns afer ExamsNo on TotalFromSharmila.txt such as MRN
SQL QUERY with PYTHON to identify more information about the lesion present
% July 12 - Now works with 4D image sequence viewer (extracting series info/phase/time from dicom)
Sorts and generates folders/links of all locations of the T13D Gad Dynamic sequences by:
1) nth-time-points per Location folders
2) bilateral post-contrast Volumes when phases are not separated. (i.e when Ph1/Ph2/Ph3.. is unavailable)
% Aug 22 - Added function get_locs_for_all_phases()
3) Loopps through each one of the Ph1/Ph2/Ph3/Ph4 series and finds equal locations at 4 post-contrast timepoints in the T13D Gad Dynamic sequences by
-----------------------------------------
'''
def FileCheck(filename):
try:
fn=open(filename,"r")
fn.close()
return True
except IOError:
print "Error: DICOMDIR.txt doesn't exit, loading Series using vtkDICOMImageReader by setDirectoryName."
return False
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
def readlink(path):
return path
def get_immediate_subdirectories(mydir):
return [name for name in os.listdir(mydir)
if os.path.isdir(os.path.join(mydir, name))]
def get_only_linksindirectory(mydir):
return [name for name in os.listdir(mydir)
if os.path.islink(os.path.join(mydir, name))]
def get_only_filesindirectory(mydir):
return [name for name in os.listdir(mydir)
if os.path.isfile(os.path.join(mydir, name))]
def find(strng, ch):
index = 0
while index < len(strng):
if strng[index] == ch:
return index
index += 1
return -1
def get_display_series(abspath_SeriesID):
arranged_folders = get_immediate_subdirectories(abspath_SeriesID);
# Initialize series count
s=0;
print "Total number of series: %d" % len(arranged_folders)
print " "
print "%s %s %s %s " % ('n', 'Series#', '#Images', 'SeriesDescription')
# Iterate for each series in ExamID
for arrangedF in arranged_folders:
path_arrangedF_ID = abspath_SeriesID+'/'+arrangedF
#print path_SeriesID
# Get total number of files
listSeries_files = get_only_filesindirectory(path_arrangedF_ID)
# Use only the first slice one file and get DICOM DICTIONARY
if(listSeries_files != []):
path_filenameID = abspath_SeriesID+'/'+arrangedF+'/'+listSeries_files[0]
dicomInfo = dicom.read_file(os.path.abspath(path_filenameID))
# Get the main dataset (they are in fact two separate datasets in the DICOM standard).
# That dicom dataset is now stored in the file_meta attribute of the dataset
# Get structure of study (all files in directory consistent with studyID and patientID
studyTree = []
FileNames=listSeries_files;
if("PatientID" in dicomInfo):
PatientID = dicomInfo.PatientID
else: PatientID=''
if("SeriesNumber" in dicomInfo):
SeriesNumber = dicomInfo.SeriesNumber
else: SeriesNumber=''
if("SeriesDescription" in dicomInfo):
SeriesDescription = dicomInfo.SeriesDescription;
else: SeriesDescription=''
if("SliceLocation" in dicomInfo):
MinSliceLocation = dicomInfo.SliceLocation; # Infos to identify number of slices/volumes
else: MinSliceLocation=''
if('ImageOrientationPatient' in dicomInfo):
ImageOrientationPatient = dicomInfo.ImageOrientationPatient; # Infos to identify number of slices/volumes
else: ImageOrientationPatient=''
NumberOfVolumes = 1 # default
# iterate number of slices and get full volume (#slices, each slice loc)
slices = []
num_images=0;
for filename in listSeries_files:
num_images = num_images+1
# Print series info
print "%d %s %d %s" % (s, SeriesNumber, num_images, SeriesDescription)
# increment series number
s=s+1;
else:
print "%d %s %d %s" % (s, "NONE", 0, "NULL")
# increment series number
s=s+1;
# Go back to rootfolder
os.chdir(path_rootFolder)
return arranged_folders
def get_display(abspath_SeriesID):
arranged_folders = get_immediate_subdirectories(abspath_SeriesID);
# Initialize series count
s=0;
print " "
print "%s \t %s \t\t %s " % ('n', 'Series#', '#Images')
# Find all dicoms Series in sudyfolder (will go into including subfolders)
# Iterate
for arrangedF in arranged_folders:
#print "arrangedFolder: %s" % arrangedF
path_arrangedF_ID = abspath_SeriesID+'/'+arrangedF
#print path_arrangedF_ID
# Enter Studyfolder to process all Dicom Series of ExamID
path_arrangedF_images = get_only_filesindirectory(path_arrangedF_ID);
#print path_arrangedF_images
print "%s \t %s \t\t %s " % (s, arrangedF, len(path_arrangedF_images))
# increment series number
s=s+1;
# Go back to rootfolder
os.chdir(path_rootFolder)
return arranged_folders
def get_series(StudyID,img_folder):
# obtain subdires in the StudyID directory, correspond to ExamsID
# check for one in subdirectory tree, (e.g Mass or NonMass)
path_studyID = img_folder+StudyID
studyFolder = os.path.abspath(path_studyID)
print studyFolder
ExamsID = get_immediate_subdirectories(path_studyID);
#print ExamsID
c = 0
if(len(ExamsID)>1):
print "%s %s " % ('n', 'Series#')
for iexam in ExamsID:
print "%d %s " % (c, str(iexam))
c=c+1
choseSerie = raw_input('Enter n Series to load (0-n), or x to exit: ')
if(choseSerie != 'x'):
c = 0
for iexam in ExamsID:
if(int(choseSerie) == c):
eID = iexam
c=c+1
else:
return '', 0, '', studyFolder
print "ExamID: %s" % eID
path_ExamID = img_folder+StudyID+'/'+eID
abspath_ExamID = os.path.abspath(path_ExamID)
print abspath_ExamID
# Enter Studyfolder to process all Dicom Series of ExamID
SeriesID = get_immediate_subdirectories(path_ExamID);
#print SeriesID
# Initialize series count
s=0;
print "Total number of series: %d" % len(SeriesID)
print " "
print "%s %s %s %s " % ('n', 'Series#', '#Images', 'SeriesDescription')
# Iterate for each series in ExamID
for sID in SeriesID:
path_SeriesID = img_folder+StudyID+'/'+eID+'/'+sID
abspath_SeriesID = os.path.abspath(path_SeriesID)
# Get total number of files
listSeries_files = get_only_filesindirectory(abspath_SeriesID)
# Use only the first slice one file and get DICOM DICTIONARY
path_filenameID = img_folder+StudyID+'/'+eID+'/'+sID+'/'+listSeries_files[0]
dicomInfo = dicom.read_file(os.path.abspath(path_filenameID))
# Get the main dataset (they are in fact two separate datasets in the DICOM standard).
# That dicom dataset is now stored in the file_meta attribute of the dataset
# Get structure of study (all files in directory consistent with studyID and patientID
studyTree = []
FileNames=listSeries_files;
if("PatientID" in dicomInfo):
PatientID = dicomInfo.PatientID#
else: PatientID=''
if("SeriesNumber" in dicomInfo):
SeriesNumber = dicomInfo.SeriesNumber#
else: SeriesNumber=''
if("SeriesDescription" in dicomInfo):
SeriesDescription = dicomInfo.SeriesDescription; #
else: SeriesDescription=''
if("SliceLocation" in dicomInfo):
MinSliceLocation = dicomInfo.SliceLocation; # Infos to identify number of slices/volumes
else: MinSliceLocation=''
if('ImageOrientationPatient' in dicomInfo):
ImageOrientationPatient = dicomInfo.ImageOrientationPatient; # Infos to identify number of slices/volumes
else: ImageOrientationPatient=''
NumberOfVolumes = 1 # default
# iterate number of slices and get full volume (#slices, each slice loc)
slices = []
num_images=0;
for filename in listSeries_files:
num_images = num_images+1
# Print series info
print "%d %s %d %s" % (s, SeriesNumber, num_images, SeriesDescription)
# increment series number
s=s+1;
# Go back to rootfolder
chdirname='Z:/Cristina/MassNonmass/'
os.chdir(chdirname)
#print os.getcwd()
else:
studyFolder = os.path.abspath(path_studyID)
#print studyFolder
# Find all dicoms Series in sudyfolder (will go into including subfolders)
# Iterate
for eID in ExamsID:
print "ExamID: %s" % eID
path_ExamID = img_folder+StudyID+'/'+eID
abspath_ExamID = os.path.abspath(path_ExamID)
print abspath_ExamID
# Enter Studyfolder to process all Dicom Series of ExamID
SeriesID = get_immediate_subdirectories(path_ExamID);
#print SeriesID
# Initialize series count
s=0;
print "Total number of series: %d" % len(SeriesID)
print " "
print "%s %s %s %s " % ('n', 'Series#', '#Images', 'SeriesDescription')
# Iterate for each series in ExamID
for sID in SeriesID:
path_SeriesID = img_folder+StudyID+'/'+eID+'/'+sID
abspath_SeriesID = os.path.abspath(path_SeriesID)
#print abspath_SeriesID
# Get total number of files
listSeries_files = get_only_filesindirectory(abspath_SeriesID)
# Use only the first slice one file and get DICOM DICTIONARY
if(listSeries_files != []):
path_filenameID = img_folder+StudyID+'/'+eID+'/'+sID+'/'+listSeries_files[0]
dicomInfo = dicom.read_file(os.path.abspath(path_filenameID))
# Get the main dataset (they are in fact two separate datasets in the DICOM standard).
# That dicom dataset is now stored in the file_meta attribute of the dataset
PatientID = dicomInfo.PatientID
SeriesNumber = dicomInfo.SeriesNumber
# Get structure of study (all files in directory consistent with studyID and patientID
studyTree = []
FileNames=listSeries_files;
if("SeriesNumber" in dicomInfo):
SeriesNumber = dicomInfo.SeriesNumber
else: SeriesNumber=''
if("SeriesDescription" in dicomInfo):
SeriesDescription = dicomInfo.SeriesDescription;
else: SeriesDescription=''
if("SliceLocation" in dicomInfo):
MinSliceLocation = dicomInfo.SliceLocation; # Infos to identify number of slices/volumes
else: MinSliceLocation=''
if('ImageOrientationPatient' in dicomInfo):
ImageOrientationPatient = dicomInfo.ImageOrientationPatient; # Infos to identify number of slices/volumes
else: ImageOrientationPatient=''
NumberOfVolumes = 1 # default
# iterate number of slices and get full volume (#slices, each slice loc)
slices = []
num_images=0;
for filename in listSeries_files:
num_images = num_images+1
# Print series info
print "%d %s %d %s" % (s, SeriesNumber, num_images, SeriesDescription)
# increment series number
s=s+1;
else:
print "%d %s %d %s" % (s, "NONE", 0, "NULL")
# increment series number
s=s+1;
# Go back to rootfolder
os.chdir(path_rootFolder)
return abspath_ExamID, eID, SeriesID, studyFolder
def get_slices_at_all_locs(img_folder, abspath_SeriesID, len_listSeries_files, StudyID, eID, SeriesID, choseSerie, listSeries_files, num_series, abspath_ExamID ):
# enter folder of Series selection /examID/S_XXX
print "entering folder abspath_SeriesID"
os.chdir(abspath_SeriesID)
print abspath_SeriesID
# Obtain all datasets in current series
# iterate number of slices and get full volume (#slices, each slice loc)
slices = []
FileNms_slices = []
for n in range(len_listSeries_files):
# Use all DICOM slices on series
''' EXTRACT DICOM SLICE LOCATION '''
absp_fsID = 'Z:/Cristina/MassNonMass/'+img_folder+StudyID+'/'+eID+'/'+SeriesID[int(choseSerie)]+'/'+listSeries_files[n]
dInfo = dicom.read_file(absp_fsID)
slices.append(dInfo.SliceLocation)
FileNms_slices.append(listSeries_files[n])
FileNms_slices.append(dInfo.SliceLocation)
print '''\nPROCESS STACKS BY SLICE LOCATIONS '''
FileNms_slices_stack = reshape(FileNms_slices, [len_listSeries_files,2])
FileNms_slices_sorted = sorted(FileNms_slices_stack, key=itemgetter(1))
#print FileNms_slices_sorted
#time.sleep(5) #will sleep for 5 seconds
FileNms_slices_sorted_stack = reshape(FileNms_slices_sorted, [len_listSeries_files,2])
#print FileNms_slices_sorted_stack
#time.sleep(5) #will sleep for 5 seconds
current_slice = FileNms_slices_sorted_stack[0,1]
print current_slice
stack_byLocation = []
name_byLocation = []
scount = 0
for sliceS in FileNms_slices_sorted_stack:
# Get the num_series = 5 name_byLocations for a given Location
if( current_slice == sliceS[1]):
print "Name: %s" % sliceS[0]
#print "Slice_loc: %s" % sliceS[1]
stack_byLocation.append(sliceS[1])
name_byLocation.append(sliceS[0])
scount = scount+1
# Finish getting all series for a given Location
else:
'''-----\t NOW HAVE ALL SLICES IN A stack_byLocation '''
# Get the new Location folder
# To verify "Above lengths should be = num_series + 1" len(stack_byLocation) len(name_byLocation)'''
current_loc = stack_byLocation[0]
# Makedir of current loc
# if current loc folder doesn't exist create it
if not os.path.exists(str(current_loc)):
os.makedirs(str(current_loc))
# Get inside location directory
os.chdir(str(current_loc))
#print os.getcwd()
# Now link slices at location to folder
filename = str(name_byLocation[0])
filename = filename[0:-10]
file_ending = '.MR.dcm'
# Save the file list to read as series later
filename_series = 'DIRCONTENTS.txt'
file_series = open(filename_series, 'w')
for j in range(scount):
# list to read as series later
link_to = '../'+name_byLocation[j]
name4link_to = filename+'00'+str(j)+file_ending
print "linking file: %s to: %s" % (link_to, name4link_to)
ln_subp = subprocess.Popen(['ln', link_to, name4link_to], stdout=subprocess.PIPE)
ln_subp.wait()
file_series.write(str(name4link_to)+'\n')
file_series.close()
# Get back inside the Series directory
os.chdir(abspath_SeriesID)
print '''\n-----\tchdir out GET NEXT LOCATIONS SLICES'''
current_slice = sliceS[1]
scount = 0
stack_byLocation = []
name_byLocation = []
print current_slice
print "Name: %s" % sliceS[0]
#print "Slice_loc: %s" % sliceS[1]
stack_byLocation.append(sliceS[1])
name_byLocation.append(sliceS[0])
scount = scount+1
print "\n------------------------------------------------------------------"
print '''FINISH get_slices_at_all_locs \n'''
os.chdir(abspath_ExamID)
return
def get_slices_for_volumes(img_folder, abspath_SeriesID, len_listSeries_files, StudyID, eID, SeriesID, choseSerie, listSeries_files, num_series, abspath_ExamID ):
print "entering folder abspath_SeriesID"
os.chdir(abspath_SeriesID)
print abspath_SeriesID
# Obtain all datasets in current series
# iterate number of slices and get full volume (#slices, each slice loc)
slices = []
FileNms_slices = []
for n in range(len_listSeries_files):
# Use all DICOM slices on series
''' EXTRACT DICOM SLICE LOCATION '''
absp_fsID = 'Z:/Cristina/MassNonMass/'+img_folder+StudyID+'/'+eID+'/'+SeriesID[int(choseSerie)]+'/'+listSeries_files[n]
dInfo = dicom.read_file(absp_fsID)
slices.append(dInfo.SliceLocation)
FileNms_slices.append(listSeries_files[n])
FileNms_slices.append(dInfo.SliceLocation)
print '''\nJust get the number of diff SLICE LOCATIONS '''
FileNms_slices_stack = reshape(FileNms_slices, [len_listSeries_files,2])
FileNms_slices_sorted = sorted(FileNms_slices_stack, key=itemgetter(0))
#print FileNms_slices_sorted
#time.sleep(5) #will sleep for 5 seconds
FileNms_slices_sorted_stack = reshape(FileNms_slices_sorted, [len_listSeries_files,2])
#print FileNms_slices_sorted_stack
#time.sleep(5) #will sleep for 5 seconds
current_slice = FileNms_slices_sorted_stack[0,1]
print current_slice
num_locations = 0
stack_num_locations = []
stack_num_locations.append(current_slice)
for sliceS in FileNms_slices_sorted_stack:
# Get the num_series = 5 name_byLocations for a given Location
while( sliceS[1] not in stack_num_locations ):
print "Name: %s" % sliceS[0]
print "Slice_loc: %s" % sliceS[1]
num_locations = num_locations+1
stack_num_locations.append(sliceS[1])
# Finish getting all series for a given Location
else:
break;
print '''\nPROCESS STACKS BY SLICE LOCATIONS '''
print "Total number of locations found: %d" % num_locations
FileNms_slices_stack = reshape(FileNms_slices, [len_listSeries_files,2])
FileNms_slices_sorted = sorted(FileNms_slices_stack, key=itemgetter(1))
FileNms_slices_sorted_stack = reshape(FileNms_slices_sorted, [len_listSeries_files,2])
stack_byLocation = []
name_byLocation = []
scount = 0
# Extracting the number of slices per bilateral 3D volumes based on num_series for 280/5 = 56
numSlices_perBilat_vol = len_listSeries_files/num_series
print "------\tNumber of Slices per Bilateral Volume: %d " % numSlices_perBilat_vol
stack_byBilatVol = []
# Get the folder names based on num_series
if ( len_listSeries_files%num_series != 0):
stack_byBilatVol.append('pre-Contrast')
for k in range(1,num_series):
# Now link slices at location to folder
stack_byBilatVol.append('post_Contrast-'+str(k))
if ( len_listSeries_files%num_series == 0):
for k in range(num_series):
# Now link slices at location to folder
stack_byBilatVol.append('post_Contrast-'+str(k+1))
# Initialized BilatVol
print stack_byBilatVol
BilatVol_folder = 0
for sliceS in FileNms_slices_sorted_stack:
# Get the num_series = 5 name_byLocations for a given Location
if( scount < numSlices_perBilat_vol):
print "--\tName: %s" % sliceS[0]
print "--\tSLoc: %s" % sliceS[1]
stack_byLocation.append(sliceS[1])
name_byLocation.append(sliceS[0])
scount = scount+1
# Finish getting all series for a given Location
else:
'''-----\t NOW HAVE ALL SLICES IN A bilateral vol '''
# Get the new Location folder
print "bit vol %d" % BilatVol_folder
current_vol = stack_byBilatVol[BilatVol_folder]
# Makedir of current loc
# if current loc folder doesn't exist create it
if not os.path.exists(str(current_vol)):
os.makedirs(str(current_vol))
# Get inside location directory
os.chdir(str(current_vol))
print os.getcwd()
# Now link slices at location to folder
filename = str(name_byLocation[0])
filename = filename[0:-10]
file_ending = '.MR.dcm'
# Save the file list to read as series later
filename_series = 'DIRCONTENTS.txt'
file_series = open(filename_series, 'w')
for j in range(numSlices_perBilat_vol):
link_to = '../'+name_byLocation[j]
name4link_to = filename+'00'+str(j+1)+file_ending
print "linking file: %s to: %s" % (link_to, name4link_to)
ln_subp = subprocess.Popen(['ln', link_to, name4link_to], stdout=subprocess.PIPE)
ln_subp.wait()
file_series.write(str(name4link_to)+'\n')
file_series.close()
# Get back inside the Series directory
os.chdir(abspath_SeriesID)
print '''\n-----\tchdir out GET NEXT LOCATIONS SLICES'''
scount = 0
stack_byLocation = []
name_byLocation = []
print "--\tName: %s" % sliceS[0]
print "--\tSLoc: %s" % sliceS[1]
stack_byLocation.append(sliceS[1])
name_byLocation.append(sliceS[0])
scount = scount+1
BilatVol_folder = BilatVol_folder+1
'''-----\tFINISH THE LAST bilateral vol '''
# Get the new Location folder
print "bit vol %d" % BilatVol_folder
current_vol = stack_byBilatVol[BilatVol_folder]
# Makedir of current loc
# if current loc folder doesn't exist create it
if not os.path.exists(str(current_vol)):
os.makedirs(str(current_vol))
# Get inside location directory
os.chdir(str(current_vol))
print os.getcwd()
# Now link slices at location to folder
filename = str(name_byLocation[0])
filename = filename[0:-10]
file_ending = '.MR.dcm'
# Save the file list to read as series later
filename_series = 'DIRCONTENTS.txt'
file_series = open(filename_series, 'w')
for j in range(numSlices_perBilat_vol):
link_to = '../'+name_byLocation[j]
name4link_to = filename+'00'+str(j+1)+file_ending
print "linking file: %s to: %s" % (link_to, name4link_to)
ln_subp = subprocess.Popen(['ln', link_to, name4link_to], stdout=subprocess.PIPE)
ln_subp.wait()
file_series.write(str(name4link_to)+'\n')
file_series.close()
# Get back inside the Series directory
os.chdir(abspath_SeriesID)
print "\n------------------------------------------------------------------"
print '''FINISH get_slices_for_volumes \n'''
os.chdir(abspath_ExamID)
return
def get_locs_for_all_phases(img_folder, SeriesID, choseSerie, StudyID, eID, abspath_ExamID, len_listSeries_files, listSeries_files ):
# enter folder of Series selection /examID/S_XXX
phases_series=[]
testSID = SeriesID[int(choseSerie)]
if 'S' in str(testSID):
print testSID[1:]
chosen_phase = int(testSID[1:])
else:
chosen_phase = int(testSID)
phases_series.append(chosen_phase)
print "Printing available SeriesID"
print "%s %s " % ('i', 'Series#')
i=1
for chSer in [chosen_phase+1, chosen_phase+2, chosen_phase+3]:
for SerID in SeriesID:
if 'S' in str(SerID):
SerID = SerID[1:]
try:
DynphasesFolder = int(SerID)
except ValueError:
DynphasesFolder = 0
if ( DynphasesFolder == chSer):
print "%d %s " % (i, SerID)
phases_series.append( int(SerID) )
i=i+1
i=1
###### OBTAIN INFO ABOUT LOCATION
# Make sure you're in root ExamId dir
os.chdir(abspath_ExamID)
scountPhase = 1
# Obtain all locations in all phases_series
for phaseS in phases_series:
if 'S' in str(testSID):
phaseS = 'S'+str(phaseS)
abspath_PhaseID = abspath_ExamID+'/'+str(phaseS) # this will return last element on list (so phase1)
print abspath_PhaseID
# Get total number of files
listPhase_files = sorted(list(get_only_filesindirectory(abspath_PhaseID)))
print "Total images in phase: %d " % len(listPhase_files)
len_listPhase_files = len(listPhase_files)
slices_phase = []
FileNms_phase_slices = []
for n in range(len_listPhase_files):
# Use all DICOM slices on series
''' EXTRACT DICOM SLICE LOCATION IN PHASEs '''
abspath_PhaseLocID = abspath_PhaseID+'/'+listPhase_files[n]
dInfo_phase = dicom.read_file(abspath_PhaseLocID)
slices_phase.append(dInfo_phase.SliceLocation)
FileNms_phase_slices.append(listPhase_files[n])
FileNms_phase_slices.append(dInfo_phase.SliceLocation)
print '''\nPROCESS STACKS BY SLICE LOCATIONS '''
FileNms_phase_slices_stack = reshape(FileNms_phase_slices, [len_listPhase_files,2])
FileNms_phase_slices_sorted = sorted(FileNms_phase_slices_stack, key=itemgetter(1))
FileNms_slices_sorted_stack = reshape(FileNms_phase_slices_sorted, [len_listPhase_files,2])
# change to next phase
os.chdir(abspath_PhaseID)
current_slice = FileNms_slices_sorted_stack[0,1]
print current_slice
stack_byLocation = []
name_byLocation = []
scount = 0
for sliceS in FileNms_slices_sorted_stack:
# Get the num_series = 5 name_byLocations for a given Location
if( current_slice == sliceS[1]):
print "Name: %s" % sliceS[0]
#print "Slice_loc: %s" % sliceS[1]
stack_byLocation.append(sliceS[1])
name_byLocation.append(sliceS[0])
scount = scount+1
# Finish getting all series for a given Location
else:
'''-----\t NOW HAVE ALL SLICES IN A stack_byLocation '''
# Get the new Location folder
# To verify "Above lengths should be = num_series + 1" len(stack_byLocation) len(name_byLocation)'''
current_loc = stack_byLocation[0]
# Makedir of current loc
os.chdir(abspath_ExamID)
if not os.path.exists('DynPhases'):
os.makedirs('DynPhases')
os.chdir('DynPhases')
print os.getcwd()
# if current loc folder doesn't exist create it
if not os.path.exists(str(current_loc)):
os.makedirs(str(current_loc))
# Get inside location directory
os.chdir(str(current_loc))
# Save the file list to read as series later
filename_series = 'DIRCONTENTS.txt'
file_series = open(filename_series, 'a')
#print os.getcwd()
# Now link slices at location to folder
filename = str(name_byLocation[0])
file_ending = '.MR.dcm'
# list to read as series later
for j in range(scount):
link_to = '../../'+str(phaseS)+'/'+name_byLocation[j]
name4link_to = '00'+str(scountPhase)+file_ending
print "linking file: %s to: %s" % (link_to, name4link_to)
ln_subp = subprocess.Popen(['ln', link_to, name4link_to], stdout=subprocess.PIPE)
ln_subp.wait()
file_series.write(str(name4link_to)+'\n')
# Get back inside the Series directory
os.chdir(abspath_ExamID)
print '''\n-----\tchdir out GET NEXT LOCATIONS SLICES'''
current_slice = sliceS[1]
scount = 0
stack_byLocation = []
name_byLocation = []
print current_slice
print "Name: %s" % sliceS[0]
#print "Slice_loc: %s" % sliceS[1]
stack_byLocation.append(sliceS[1])
name_byLocation.append(sliceS[0])
scount = scount+1
scountPhase = scountPhase+1
file_series.close()
# Makedir of current loc
os.chdir(abspath_ExamID)
print "\n------------------------------------------------------------------"
print '''FINISH get_locs_for_all_phases \n'''
os.chdir('DynPhases')
return
# ******************************************************************************
epsilon = .0001
# use cell picker for interacting with the image orthogonal views.
picker = vtk.vtkCellPicker()
picker.SetTolerance(0.005)
# Create 3 orthogonal view using the ImagePlaneWidget
xImagePlaneWidget = vtk.vtkImagePlaneWidget()
yImagePlaneWidget = vtk.vtkImagePlaneWidget()
zImagePlaneWidget = vtk.vtkImagePlaneWidget()
# The 3 image plane widgets
xImagePlaneWidget.DisplayTextOn();
xImagePlaneWidget.SetPicker(picker);
xImagePlaneWidget.RestrictPlaneToVolumeOn();
xImagePlaneWidget.SetKeyPressActivationValue('x');
xImagePlaneWidget.GetPlaneProperty().SetColor(1, 0, 0);
xImagePlaneWidget.SetResliceInterpolateToNearestNeighbour();
yImagePlaneWidget.DisplayTextOn();
yImagePlaneWidget.SetPicker(picker);
yImagePlaneWidget.RestrictPlaneToVolumeOn();
yImagePlaneWidget.SetKeyPressActivationValue('y');
yImagePlaneWidget.GetPlaneProperty().SetColor(0, 1, 0);
yImagePlaneWidget.SetLookupTable(xImagePlaneWidget.GetLookupTable());
zImagePlaneWidget.DisplayTextOn();
zImagePlaneWidget.SetPicker(picker);
zImagePlaneWidget.SetKeyPressActivationValue('z');
zImagePlaneWidget.GetPlaneProperty().SetColor(0, 0, 1);
zImagePlaneWidget.SetLookupTable(xImagePlaneWidget.GetLookupTable());
zImagePlaneWidget.SetRightButtonAutoModifier(1);
# Create a renderer, render window, and render window interactor to
# display the results.
renderer1 = vtk.vtkRenderer()
renWin1 = vtk.vtkRenderWindow()
iren1 = vtk.vtkRenderWindowInteractor()
renWin1.SetSize(1000, 800);
renWin1.AddRenderer(renderer1);
iren1.SetRenderWindow(renWin1);
xImagePlaneWidget.SetInteractor( iren1 )
xImagePlaneWidget.SetSliceIndex(20)
xImagePlaneWidget.On()
yImagePlaneWidget.SetInteractor( iren1 )
yImagePlaneWidget.SetSliceIndex(20)
yImagePlaneWidget.On()
zImagePlaneWidget.SetInteractor( iren1 )
zImagePlaneWidget.SetSliceIndex(10)
zImagePlaneWidget.On()
# *****************************************************************************
# Get Root folder ( the directory of the script being run)
path_rootFolder = os.path.dirname(os.path.abspath(__file__))
#print path_rootFolder
# init vars
studyTree = []
# Get study image folder
img_folder = sys.argv[1]
# Open filename list
file_ids = open(sys.argv[2],"r")
try:
for line in file_ids:
# Get the line: Study#, DicomExam#
line = line.split()
StudyID = line[0]
ExamID = line[1]
MRN = line[2]
print "Getting studyID# DicomExam# "
print StudyID, ExamID, MRN
row=[]
# Execute mysqlconnect (SQL Query design in Project/SMIAL_Database/SQLQuery_Filtered_MRImagingVisits_kinetics_Foci.sql resutls 305 - 18 July 2012
print "Executing SQL connection..."
conn = pymssql.connect(host='SG12-BIOMATRIX', user='cristina.gallego', password='miag_1234', database='SMIAL_BCAD')
cur = conn.cursor()
cur.execute('''
SELECT Patient.Patients.MRN, Patient.Patients.StudyNumber, Radiology.RadiologyReport.DicomExamNumber, Radiology.RadiologyReport.DateOfExam,
Lesion.GeoDescription.Description, Lesion.FindingLocation.AdditionDescription, Lesion.GeoDescription.BreastSide, Lesion.FindingLocation.QuadrantID, Lesion.FindingLocation.ClockStart,
Lesion.FindingLocation.ClockEnd, Lesion.FindingLocation.MRISeries, Lesion.FindingLocation.LesionCenterPixelX, Lesion.FindingLocation.LesionCenterPixelY,
Lesion.LesionFindingType.Description AS Expr1, Pathology.PathoReport.HistopathWorstType, Pathology.PathoResultType.Description AS Expr5,
Lesion.DCEInitialEnhPhaseType.DCEInitialPhaseEnhTypeID, Lesion.DCEInitialEnhPhaseType.Description AS Expr2,
Lesion.DCEDelayEnhPhaseType.DCEDelayedPhaseEnhID, Lesion.DCEDelayEnhPhaseType.Description AS Expr3, Radiology.FociLesion.LesionFindingID,
Lesion.FociDivertingType.FociDivertingTypeID, Lesion.FociDivertingType.Description AS Expr4, Radiology.FociLesion.IsInvasiveBit
FROM Radiology.RadiologyReport INNER JOIN
Radiology.Lesions ON Radiology.RadiologyReport.RadReportID = Radiology.Lesions.RadReportID INNER JOIN
Lesion.LesionFindingType ON Radiology.Lesions.LesionFindingTypeID = Lesion.LesionFindingType.LesionFindingTypeID INNER JOIN
Lesion.GeoDescription ON Radiology.Lesions.GeoDescriptionID = Lesion.GeoDescription.GeoDescriptionID INNER JOIN
Lesion.FindingLocation ON Lesion.GeoDescription.FindingLocationID = Lesion.FindingLocation.FindingLocationID AND
Lesion.GeoDescription.FindingLocationID = Lesion.FindingLocation.FindingLocationID INNER JOIN
Visit.ImagingVisits ON Radiology.RadiologyReport.ImagingVisitID = Visit.ImagingVisits.ImagingVisitID INNER JOIN
Patient.Patients ON Visit.ImagingVisits.StudyPatID = Patient.Patients.StudyPatID AND Visit.ImagingVisits.StudyPatID = Patient.Patients.StudyPatID AND
Visit.ImagingVisits.StudyPatID = Patient.Patients.StudyPatID AND Visit.ImagingVisits.StudyPatID = Patient.Patients.StudyPatID AND
Visit.ImagingVisits.StudyPatID = Patient.Patients.StudyPatID INNER JOIN
Pathology.PathoReport ON Visit.ImagingVisits.ImagingVisitID = Pathology.PathoReport.ImagingVisitID AND
Visit.ImagingVisits.ImagingVisitID = Pathology.PathoReport.ImagingVisitID AND Visit.ImagingVisits.ImagingVisitID = Pathology.PathoReport.ImagingVisitID AND
Visit.ImagingVisits.ImagingVisitID = Pathology.PathoReport.ImagingVisitID AND Visit.ImagingVisits.ImagingVisitID = Pathology.PathoReport.ImagingVisitID INNER JOIN
Pathology.PathoResultType ON Pathology.PathoReport.PathoResultTypeID = Pathology.PathoResultType.PathoResultTypeID AND
Pathology.PathoReport.PathoResultTypeID = Pathology.PathoResultType.PathoResultTypeID AND
Pathology.PathoReport.PathoResultTypeID = Pathology.PathoResultType.PathoResultTypeID AND
Pathology.PathoReport.PathoResultTypeID = Pathology.PathoResultType.PathoResultTypeID AND
Pathology.PathoReport.PathoResultTypeID = Pathology.PathoResultType.PathoResultTypeID AND
Pathology.PathoReport.PathoResultTypeID = Pathology.PathoResultType.PathoResultTypeID INNER JOIN
Visit.ImagingVisitType ON Visit.ImagingVisits.ImagingVisitTypeID = Visit.ImagingVisitType.ImagingVisitTypeID INNER JOIN
Visit.VisitReasonType ON Visit.ImagingVisits.VisitReasonTypeID = Visit.VisitReasonType.VisitReasonTypeID INNER JOIN
Radiology.FociLesion ON Radiology.Lesions.LesionFindingID = Radiology.FociLesion.LesionFindingID AND
Radiology.Lesions.LesionFindingID = Radiology.FociLesion.LesionFindingID AND Radiology.Lesions.LesionFindingID = Radiology.FociLesion.LesionFindingID AND
Radiology.Lesions.LesionFindingID = Radiology.FociLesion.LesionFindingID INNER JOIN
Lesion.DCEDelayEnhPhaseType ON Radiology.FociLesion.DCEDelayedPhaseEnhID = Lesion.DCEDelayEnhPhaseType.DCEDelayedPhaseEnhID AND
Radiology.FociLesion.DCEDelayedPhaseEnhID = Lesion.DCEDelayEnhPhaseType.DCEDelayedPhaseEnhID AND
Radiology.FociLesion.DCEDelayedPhaseEnhID = Lesion.DCEDelayEnhPhaseType.DCEDelayedPhaseEnhID AND
Radiology.FociLesion.DCEDelayedPhaseEnhID = Lesion.DCEDelayEnhPhaseType.DCEDelayedPhaseEnhID AND
Radiology.FociLesion.DCEDelayedPhaseEnhID = Lesion.DCEDelayEnhPhaseType.DCEDelayedPhaseEnhID AND
Radiology.FociLesion.DCEDelayedPhaseEnhID = Lesion.DCEDelayEnhPhaseType.DCEDelayedPhaseEnhID AND
Radiology.FociLesion.DCEDelayedPhaseEnhID = Lesion.DCEDelayEnhPhaseType.DCEDelayedPhaseEnhID AND
Radiology.FociLesion.DCEDelayedPhaseEnhID = Lesion.DCEDelayEnhPhaseType.DCEDelayedPhaseEnhID AND
Radiology.FociLesion.DCEDelayedPhaseEnhID = Lesion.DCEDelayEnhPhaseType.DCEDelayedPhaseEnhID AND
Radiology.FociLesion.DCEDelayedPhaseEnhID = Lesion.DCEDelayEnhPhaseType.DCEDelayedPhaseEnhID INNER JOIN
Lesion.DCEInitialEnhPhaseType ON Radiology.FociLesion.DCEInitialPhaseEnhTypeID = Lesion.DCEInitialEnhPhaseType.DCEInitialPhaseEnhTypeID AND
Radiology.FociLesion.DCEInitialPhaseEnhTypeID = Lesion.DCEInitialEnhPhaseType.DCEInitialPhaseEnhTypeID AND
Radiology.FociLesion.DCEInitialPhaseEnhTypeID = Lesion.DCEInitialEnhPhaseType.DCEInitialPhaseEnhTypeID AND
Radiology.FociLesion.DCEInitialPhaseEnhTypeID = Lesion.DCEInitialEnhPhaseType.DCEInitialPhaseEnhTypeID AND
Radiology.FociLesion.DCEInitialPhaseEnhTypeID = Lesion.DCEInitialEnhPhaseType.DCEInitialPhaseEnhTypeID AND
Radiology.FociLesion.DCEInitialPhaseEnhTypeID = Lesion.DCEInitialEnhPhaseType.DCEInitialPhaseEnhTypeID AND
Radiology.FociLesion.DCEInitialPhaseEnhTypeID = Lesion.DCEInitialEnhPhaseType.DCEInitialPhaseEnhTypeID AND
Radiology.FociLesion.DCEInitialPhaseEnhTypeID = Lesion.DCEInitialEnhPhaseType.DCEInitialPhaseEnhTypeID AND
Radiology.FociLesion.DCEInitialPhaseEnhTypeID = Lesion.DCEInitialEnhPhaseType.DCEInitialPhaseEnhTypeID AND
Radiology.FociLesion.DCEInitialPhaseEnhTypeID = Lesion.DCEInitialEnhPhaseType.DCEInitialPhaseEnhTypeID INNER JOIN
Lesion.FociDivertingType ON Radiology.FociLesion.FociDistribution = Lesion.FociDivertingType.FociDivertingTypeID AND
Radiology.FociLesion.FociDistribution = Lesion.FociDivertingType.FociDivertingTypeID AND
Radiology.FociLesion.FociDistribution = Lesion.FociDivertingType.FociDivertingTypeID AND
Radiology.FociLesion.FociDistribution = Lesion.FociDivertingType.FociDivertingTypeID AND
Radiology.FociLesion.FociDistribution = Lesion.FociDivertingType.FociDivertingTypeID AND
Radiology.FociLesion.FociDistribution = Lesion.FociDivertingType.FociDivertingTypeID AND
Radiology.FociLesion.FociDistribution = Lesion.FociDivertingType.FociDivertingTypeID AND
Radiology.FociLesion.FociDistribution = Lesion.FociDivertingType.FociDivertingTypeID AND
Radiology.FociLesion.FociDistribution = Lesion.FociDivertingType.FociDivertingTypeID AND
Radiology.FociLesion.FociDistribution = Lesion.FociDivertingType.FociDivertingTypeID
WHERE Radiology.RadiologyReport.DicomExamNumber=%d
''', int(ExamID))
for row in cur:
print row # "\tStudyNumber %d\t DicomExamNumber %d\t Description: %s\n AdditonalDescription: %s\n BreastSide: %s\t ClockStart: %s\t ClockEnd: %s\t MRISeries %s\t\n LesionCenterPixelX: %s\t LesionCenterPixelY: %s\t LesionFindingType.Description: %s\t\n\n" % (row[0], row[1], row[3], row[4], row[5], row[7], row[8], row[9], row[10], row[11], row[12])
print len(row)
if(row==[]):
# initialize database vector
row = [0 for x in range(26)]
print row[16]
print len(row)
conn.close()
# *****************************************************************************
# get_series and print which series to load
print " "
print "Current folder time"
chdirname='Z:/Cristina/MassNonmass/'
os.chdir(chdirname)
print os.getcwd()
[abspath_ExamID, eID, SeriesID, studyFolder] = get_series(StudyID, img_folder)
# *****************************************************************************
# ask for which series to load
print "\n----------------------------------------------------------"
choseSerie = raw_input('Enter n Series to load (0-n), or x to exit: ')
while(choseSerie!='x'):
# Enter folder
os.chdir(abspath_ExamID)
path_SeriesID = img_folder+StudyID+'/'+eID+'/'+SeriesID[int(choseSerie)]
print path_SeriesID
# abspath_SeriesID = os.path.abspath(path_SeriesID) -- doesn't work bug
abspath_SeriesID = 'Z:/Cristina/MassNonMass/'+path_SeriesID
# Get total number of files
listSeries_files = sorted(list(get_only_filesindirectory(abspath_SeriesID)))
print "Total images in series: %d " % len(listSeries_files)
len_listSeries_files = len(listSeries_files)
#time.sleep(3) #will sleep for 5 seconds
# Use only the first slice one file and get DICOM DICTIONARY
path_filenameID = img_folder+StudyID+'/'+eID+'/'+SeriesID[int(choseSerie)]+'/'+listSeries_files[0]
# os.path.abspath(path_filenameID) not working