-
Notifications
You must be signed in to change notification settings - Fork 2
/
pinnDicom.py
3144 lines (2993 loc) · 159 KB
/
pinnDicom.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 libraries below
####################################################################################################################################################
from __future__ import print_function
import operator
# import pydicom.uid
import os
import os.path
import re # used for isolated values from strings
import struct
import time # used for getting current date and time for file
from functools import reduce
from random import randint
import matplotlib.pyplot as plt
import numpy as np
import pydicom as dicom
import pydicom.uid
from dicompylercore import dicomparser, dvhcalc
from dicompylercore.dvh import DVH
from pydicom.dataset import Dataset, FileDataset
from pydicom.filebase import DicomFile
from pydicom.sequence import Sequence
from pinn2Json import pinn2Json
####################################################################################################################################################
# Global Variables
####################################################################################################################################################
RS_test = ''
RP_test = ''
RD_test = ''
ROI_COUNT = 0 # This value will represent the ROI that I'm currently looking at in file, will be incremented for each roi
SeriesUID = "NA"
StudyInstanceUID = "NA"
FrameUID = "NA"
ClassUID = "NA"
patientname = ""
dob = ""
pid = ""
imageslice = []
imageuid = []
Colors = [['255', '0', '0'], ['255', '20', '147'], ['0', '0', '255'],
['0', '255', '0'], ['125', '38', '205'], ['255', '255', '0'],
['255', '140', '0'], ['0', '100', '0'], ['0', '191', '255'],
['255', '192', '203'], ['72', '209', '204'], ['139', '69', '19'],
['255', '193', '37'], ['221', '160', '221'], ['107', '142', '35'],
['142', '35', '35'], ['245', '204', '176'], ['191', '239', '255'],
['139', '28', '98'], ['255', '99', '71'], ['255', '0', '0'],
['255', '20', '147'], ['0', '0', '255'], ['0', '255', '0'],
['125', '38', '205'], ['255', '255', '0'], ['255', '140', '0'],
['0', '100', '0'], ['0', '191', '255'], ['255', '192', '203'],
['72', '209', '204'], ['139', '69', '19'], ['255', '193', '37'],
['221', '160', '221'], ['107', '142', '35'], ['142', '35', '35'],
['245', '204', '176'], ['191', '239', '255'], ['139', '28', '98'],
['255', '99', '71'],
['255', '0', '0'], ['255', '20', '147'], ['0', '0', '255'],
['0', '255', '0'], ['125', '38', '205'], ['255', '255', '0'],
['255', '140', '0'], ['0', '100', '0'], ['0', '191', '255'],
['255', '192', '203'], ['72', '209', '204'], ['139', '69', '19'],
['255', '193', '37'], ['221', '160', '221'], ['107', '142', '35'],
['142', '35', '35'], ['245', '204', '176'], ['191', '239', '255'],
['139', '28', '98'], ['255', '99', '71'], ['255', '0', '0'],
['255', '20', '147'], ['0', '0', '255'], ['0', '255', '0'],
['125', '38', '205'], ['255', '255', '0'], ['255', '140', '0'],
['0', '100', '0'], ['0', '191', '255'], ['255', '192', '203'],
['72', '209', '204'], ['139', '69', '19'], ['255', '193', '37'],
['221', '160', '221'], ['107', '142', '35'], ['142', '35', '35'],
['245', '204', '176'], ['191', '239', '255'], ['139', '28', '98'],
['255', '99', '71'],
['255', '0', '0'], ['255', '20', '147'], ['0', '0', '255'],
['0', '255', '0'], ['125', '38', '205'], ['255', '255', '0'],
['255', '140', '0'], ['0', '100', '0'], ['0', '191', '255'],
['255', '192', '203'], ['72', '209', '204'], ['139', '69', '19'],
['255', '193', '37'], ['221', '160', '221'], ['107', '142', '35'],
['142', '35', '35'], ['245', '204', '176'], ['191', '239', '255'],
['139', '28', '98'], ['255', '99', '71'], ['255', '0', '0'],
['255', '20', '147'], ['0', '0', '255'], ['0', '255', '0'],
['125', '38', '205'], ['255', '255', '0'], ['255', '140', '0'],
['0', '100', '0'], ['0', '191', '255'], ['255', '192', '203'],
['72', '209', '204'], ['139', '69', '19'], ['255', '193', '37'],
['221', '160', '221'], ['107', '142', '35'], ['142', '35', '35'],
['245', '204', '176'], ['191', '239', '255'], ['139', '28', '98'],
['255', '99', '71'],
['255', '0', '0'], ['255', '20', '147'], ['0', '0', '255'],
['0', '255', '0'], ['125', '38', '205'], ['255', '255', '0'],
['255', '140', '0'], ['0', '100', '0'], ['0', '191', '255'],
['255', '192', '203'], ['72', '209', '204'], ['139', '69', '19'],
['255', '193', '37'], ['221', '160', '221'], ['107', '142', '35'],
['142', '35', '35'], ['245', '204', '176'], ['191', '239', '255'],
['139', '28', '98'], ['255', '99', '71'], ['255', '0', '0'],
['255', '20', '147'], ['0', '0', '255'], ['0', '255', '0'],
['125', '38', '205'], ['255', '255', '0'], ['255', '140', '0'],
['0', '100', '0'], ['0', '191', '255'], ['255', '192', '203'],
['72', '209', '204'], ['139', '69', '19'], ['255', '193', '37'],
['221', '160', '221'], ['107', '142', '35'], ['142', '35', '35'],
['245', '204', '176'], ['191', '239', '255'], ['139', '28', '98'],
['255', '99', '71']]
# red, pink, blue, green, purple, yellow, orange, dark green, sky blue, light pink, Turquois, brown, gold,lightpurple, olive, brick, peach?, light blue, maroon, tomato
patient_sex = ""
study_date = ""
study_time = ""
model = ""
physician = ""
sid = ""
isocenter = []
ctcenter = []
descrip = ""
plancount = 0
plannamelist = []
planids = []
randval = randint(0, 999)
currentdate = time.strftime("%Y%m%d")
currenttime = time.strftime("%H%M%S")
doserefpt = []
patient_position = ""
xshift = 0
yshift = 0
zshift = 0
lname = ""
fname = ""
patientfolder = ""
structsopinstuid = ''
structseriesinstuid = ''
plansopinstuid = ''
planseriesinstuid = ''
doseseriesuid = ''
doseinstuid = ''
planfilename = ''
dosexdim = 0
doseydim = 0
dosezdim = 0
doseoriginx = ""
doseoriginy = ""
doseoriginz = ""
beamdosefiles = []
pixspacingx = ""
pixspacingy = ""
pixspacingz = ""
posrefind = ""
image_orientation = []
imagesetnumber = ""
point_names = []
point_values = []
numfracs = ""
flag_nobinaryfile = False
flag_noimages = False
GTransferSyntaxUID = '1.2.840.10008.1.2'
no_setup_file = False
no_beams = False
gImplementationClassUID = '1.2.826.0.1.3680043.8.498.75006884747854523615841001'
Manufacturer = "Pinnacle Philips"
PDD6MV = 0.665 # for varian 600CD in TJ
PDD10MV = 0.6683 # Also temporary, need to get actual PDD value
PDD15MV = 0.7658
# THis is temporary, this value is not correct just using as place holder for now
PDD16MV = 0.7658
softwarev = ""
slicethick = 0
x_dim = 0
y_dim = 0
z_dim = 0
xpixdim = 0
ypixdim = 0
#listofversions = []
####################################################################################################################################################
# Function: main
# This main function is what should be called to run program
# The name of the patient folder should be passed into the function for it to be run.
# This folder should be stored under Inputf directory (line 102)
####################################################################################################################################################
def readpatient(temppatientfolder, inputfolder, outputfolder):
global RS_test
global RD_test
global RP_test
global ROI_COUNT
global structfilename
global SeriesUID
global StudyInstanceUID
global FrameUID
global ClassUID
global patientname
global dob
global pid
global imageslice
global imageuid
global Colors
global patient_sex
global study_date
global study_time
global model
global physician
global sid
global isocenter
global ctcenter
global descrip
global plancount
global plannamelist
global planids
global randval
global currentdate
global currenttime
global doserefpt
global patient_position
global xshift
global yshift
global lname
global fname
global Inputf
global Outputf
global patientfolder
global structsopinstuid
global structseriesinstuid
global plansopinstuid
global planseriesinstuid
global doseinstuid
global doseseriesuid
global planfilename
global flag_noimages
global no_setup_file
global no_beams
global softwarev
initglobalvars() # First step of the main function is to call the initglobalvars variable
# to reset everything in case this function is being used in a loop. (see allpatientloop.py)
#print("Input Patient Folder:")
#patientfolder = raw_input("> ")
# temppatientfolder="Patient_9419"
patientfolder = temppatientfolder
Inputf = inputfolder
Outputf = outputfolder
print("Pinnacle tar folder path: " + Inputf)
print("Current Patient: " + patientfolder)
if not os.path.exists(Outputf + "%s" % (patientfolder)):
# Create folder for exported DICOM files if it does not already exist
os.makedirs(Outputf + "%s" % (patientfolder))
print("Output location: " + Outputf)
structsopinstuid = pydicom.uid.generate_uid()
structds = createstructds() # creating dataset for structure file
# for j in range(0, 5000):
# morewastingtime = j
structseriesinstuid = pydicom.uid.generate_uid()
structds.ReferencedStudySequence = Sequence()
structds = initds(structds)
structds = readpatientinfo(structds)
readImageInfo() # Gets UID information for image files
# initializes values like uids, creation time, manufacturer, values that are not patient dependent
structds = initds(structds)
# for i in range(0, 5000):
# timewaster = i
plansopinstuid = pydicom.uid.generate_uid()
convertimages() # This function makes the image files usable (matches patient info that will go into other DICOM files). If image files do not exist this function calls createimagefiles function
if flag_noimages:
return
planseriesinstuid = pydicom.uid.generate_uid()
patient_position = getpatientsetup("Plan_%s" % planids[0])
if no_setup_file == True:
return
structds.ReferencedFrameOfReferenceSequence = Sequence()
ReferencedFrameofReference1 = Dataset()
structds.ReferencedFrameOfReferenceSequence.append(
ReferencedFrameofReference1)
structds.ReferencedFrameOfReferenceSequence[0].FrameofReferenceUID = FrameUID
structds.ReferencedFrameOfReferenceSequence[0].RTReferencedStudySequence = Sequence(
)
RTReferencedStudy1 = Dataset()
structds.ReferencedFrameOfReferenceSequence[0].RTReferencedStudySequence.append(
RTReferencedStudy1)
structds.ReferencedFrameOfReferenceSequence[0].RTReferencedStudySequence[
0].ReferencedSOPClassUID = '1.2.840.10008.3.1.2.3.2'
structds.ReferencedFrameOfReferenceSequence[0].RTReferencedStudySequence[
0].ReferencedSOPInstanceUID = StudyInstanceUID
structds.StudyInstanceUID = StudyInstanceUID
structds.ReferencedFrameOfReferenceSequence[0].RTReferencedStudySequence[0].RTReferencedSeriesSequence = Sequence(
)
RTReferencedSeries1 = Dataset()
structds.ReferencedFrameOfReferenceSequence[0].RTReferencedStudySequence[0].RTReferencedSeriesSequence.append(
RTReferencedSeries1)
structds.ReferencedFrameOfReferenceSequence[0].RTReferencedStudySequence[
0].RTReferencedSeriesSequence[0].SeriesInstanceUID = SeriesUID
structds.ReferencedFrameOfReferenceSequence[0].RTReferencedStudySequence[
0].RTReferencedSeriesSequence[0].ContourImageSequence = Sequence()
for i, value in enumerate(imageuid, 1):
exec("ContourImage%d = Dataset()" % i)
exec(
"structds.ReferencedFrameOfReferenceSequence[0].RTReferencedStudySequence[0].RTReferencedSeriesSequence[0].ContourImageSequence.append(ContourImage%d)" % i)
structds.ReferencedFrameOfReferenceSequence[0].RTReferencedStudySequence[0].RTReferencedSeriesSequence[
0].ContourImageSequence[i - 1].ReferencedSOPClassUID = '1.2.840.10008.5.1.4.1.1.1'
structds.ReferencedFrameOfReferenceSequence[0].RTReferencedStudySequence[0].RTReferencedSeriesSequence[
0].ContourImageSequence[i - 1].ReferencedSOPInstanceUID = imageuid[i - 1]
doseinstuid = pydicom.uid.generate_uid()
structds.ROIContourSequence = Sequence()
structds.StructureSetROISequence = Sequence()
structds.RTROIObservationsSequence = Sequence()
# if softwarev != "Pinnacle 9.0": # If pinnacle software is version 9.0 the shifts are not needed so this function can be skipped and the values for the shifts will still be set to zero
getstructshift()
structds = readpoints(structds, "Plan_%s" % planids[0])
structds = readroi(structds, "Plan_%s" % planids[0])
# find out where to get if its been approved or not
structds.ApprovalStatus = 'UNAPPROVED'
# Set the transfer syntax
structds.is_little_endian = True
structds.is_implicit_VR = True
#structfilepath=outputfolder + patientfolder + "/" + structfilename
# structds.save_as("structfilepath")
#print("Structure file being saved\n")
#structds.save_as(Outputf + "/%s/%s"%(patientfolder, structfilename))
RS_test = dicomparser.DicomParser(structds)
doseseriesuid = pydicom.uid.generate_uid()
print("creating plan data structures \n")
#############################################################################################
# loop below creates plan files for each plan in directory (based on what is in the Patient file)
for i in range(0, plancount):
planame = plannamelist[i]
plandirect = "Plan_" + planids[i]
exec("plands_%s = createplands(i)" % planids[i])
exec("plands_%s = planinit(plands_%s, planame, plandirect, i)" %
(planids[i], planids[i]))
exec("plands_%s = readtrial(plands_%s, plandirect, i)" %
(planids[i], planids[i]))
if no_beams == True:
continue
print("Setting plan file name:")
#exec("tempmetainstuid = plands_%s.file_meta.MediaStorageSOPInstanceUID"%planids[i])
tempmetainstuid = plansopinstuid + "." + str(i)
planfilename = 'RP.' + tempmetainstuid + '.dcm'
print("Plan file name: " + planfilename)
planfilepath = Outputf + patientfolder + "/" + planfilename
print(planfilepath)
# print("\n Saving plan file \n")
# exec("plands_%s.save_as(planfilepath)"%(planids[i]))
exec('RP_test = dicomparser.DicomParser(plands_%s)' % (planids[i]))
# os.rename(Outputf+'%s'% patientfolder, Outputf+'%s,%s,%s'%(lname,fname,pid))
#print("\n \n Current software versions found: \n")
# for ver in softwarev:
# print(ver)
# sturctures = RS_test.GetStructures()
# print(sturctures)
#dvh_inter = dvhcalc.get_dvh(RS_test.ds, RD_test.ds, 4,interpolation_resolution=(4/32),interpolation_segments_between_planes=2,use_structure_extents=True)
# dvh = dvhcalc.get_dvh(RS_test.ds, RD_test.ds, 4)
# print(dvh.volume, dvh.name)
# dvh.describe()
# print(dvh.bins)
# dvh.compare(dvh_inter)
# return dvh_inter
return RS_test, RD_test
####################################################################################################################################################
####################################################################################################################################################
####################################################################################################################################################
# Function: initglobalvars
# This function simply resets all of the global variables to empty values
####################################################################################################################################################
def initglobalvars():
global ROI_COUNT
global structfilename
global SeriesUID
global StudyInstanceUID
global FrameUID
global ClassUID
global patientname
global dob
global pid
global imageslice
global imageuid
global Colors
global patient_sex
global study_date
global study_time
global model
global physician
global sid
global isocenter
global ctcenter
global descrip
global plancount
global plannamelist
global planids
global randval
global currentdate
global currenttime
global doserefpt
global patient_position
global xshift
global yshift
global zshift
global lname
global fname
global patientfolder
global structsopinstuid
global structseriesinstuid
global plansopinstuid
global planseriesinstuid
global doseseriesuid
global doseinstuid
global planfilename
global dosexdim
global doseydim
global dosezdim
global doseoriginx
global doseoriginy
global doseoriginz
global beamdosefiles
global pixspacingx
global pixspacingy
global pixspacingz
global posrefind
global image_orientation
global imagesetnumber
global point_names
global point_values
global numfracs
global flag_nobinaryfile
global flag_noimages
global no_setup_file
global no_beams
global softwarev
global slicethick
global x_dim
global y_dim
global z_dim
global xpixdim
global ypixdim
ROI_COUNT = 0 # This value will represent the ROI that I'm currently looking at in file, will be incremented for each roi
SeriesUID = "NA"
StudyInstanceUID = "NA"
FrameUID = "NA"
ClassUID = "NA"
patientname = ""
dob = ""
pid = ""
imageslice = []
imageuid = []
# Colors = [['255', '0', '0'], ['255', '20', '147'], ['0', '0', '255'], ['0', '255', '0'], ['125', '38', '205'], ['255', '255', '0'], ['255', '140', '0'], ['0', '100', '0'], ['0', '191', '255'], ['255', '192', '203'], ['72', '209', '204'], ['139', '69', '19'], ['255', '193', '37'], ['221', '160', '221'], [
# '107', '142', '35'], ['142', '35', '35'], ['245', '204', '176'], ['191', '239', '255'], ['139', '28', '98'], ['255', '99', '71']] # red, pink, blue, green, purple, yellow, orange, dark green, sky blue, light pink, Turquois, brown, gold,lightpurple, olive, brick, peach?, light blue, maroon, tomato
patient_sex = ""
study_date = ""
study_time = ""
model = ""
physician = ""
sid = ""
isocenter = []
ctcenter = []
descrip = ""
plancount = 0
plannamelist = []
planids = []
randval = randint(0, 999)
currentdate = time.strftime("%Y%m%d")
currenttime = time.strftime("%H%M%S")
doserefpt = []
patient_position = ""
xshift = 0
yshift = 0
zshift = 0
lname = ""
fname = ""
patientfolder = ""
structsopinstuid = ''
structseriesinstuid = ''
plansopinstuid = ''
planseriesinstuid = ''
doseseriesuid = ''
doseinstuid = ''
planfilename = ''
dosexdim = 0
doseydim = 0
dosezdim = 0
doseoriginx = ""
doseoriginy = ""
doseoriginz = ""
beamdosefiles = []
pixspacingx = ""
pixspacingy = ""
pixspacingz = ""
posrefind = ""
image_orientation = []
imagesetnumber = ""
point_names = []
point_values = []
numfracs = ""
flag_nobinaryfile = False
flag_noimages = False
no_setup_file = False
no_beams = False
softwarev = ""
slicethick = 0
x_dim = 0
y_dim = 0
z_dim = 0
xpixdim = 0
ypixdim = 0
####################################################################################################################################################
####################################################################################################################################################
####################################################################################################################################################
# function: convertimages
# The purpose of this function is to read in the image DICOM files
# and to change the patients name to match the name of the patient
# in the pinnacle files, also fills the list values for slicelocation
# and UID. This function needs to be run, even if image files already converted
####################################################################################################################################################
def convertimages():
print("Converting image patient name, birthdate and id to match pinnacle\n")
global patientname
global pid
global dob
global FrameUID
global imageslice
global SeriesUID
global StudyInstanceUID
global imageuid
global patientfolder
global posrefind
global imagesetnumber
global image_orientation
global flag_noimages
if not os.path.exists("%s%s/ImageSet_%s.DICOM" % (Inputf, patientfolder, imagesetnumber)):
# Image set folder not found, need to ignore patient
# Will want to call a function to be written that will create image set files from the condensed pixel data file
print("Image files do not exist. Creating image files")
createimagefiles()
return
for file in os.listdir("%s%s/ImageSet_%s.DICOM" % (Inputf, patientfolder, imagesetnumber)):
if file == '11026.1.img':
continue
imageds = dicom.read_file("%s%s/ImageSet_%s.DICOM/%s" %
(Inputf, patientfolder, imagesetnumber, file), force=True)
imageds.PatientsName = patientname
imageds.PatientID = pid
imageds.PatientsBirthDate = dob
imageslice.append(imageds.SliceLocation)
imageuid.append(imageds.SOPInstanceUID)
image_orientation = imageds.ImageOrientationPatient
tempinstuid = imageds.SOPInstanceUID
posrefind = imageds.PositionReferenceIndicator
imageds.SOPInstanceUID = tempinstuid
imageds.FrameOfReferenceUID = FrameUID
imageds.StudyInstanceUID = StudyInstanceUID
imageds.SeriesInstanceUID = SeriesUID
file_meta = Dataset()
file_meta.TransferSyntaxUID = GTransferSyntaxUID
file_meta.MediaStorageSOPClassUID = '1.2.840.10008.5.1.4.1.1.2'
file_meta.MediaStorageSOPInstanceUID = tempinstuid
file_meta.ImplementationClassUID = gImplementationClassUID
imageds.file_meta = file_meta
preamble = getattr(imageds, "preamble", None)
if not preamble:
preamble = b'\x00' * 128
currfile = DicomFile(Outputf + "%s/CT.%s.dcm" %
(patientfolder, tempinstuid), 'wb')
currfile.write(preamble)
currfile.write(b'DICM')
# dicom.write_file(Outputf+"%s/CT.%s.dcm"%(patientfolder,tempinstuid), imageds, False)
print("Current image: ", file)
####################################################################################################################################################
####################################################################################################################################################
####################################################################################################################################################
# Function: createimagefiles()
# This function will create dicom image files for each slice using the condensed pixel data from file ImageSet_%s.img
####################################################################################################################################################
def createimagefiles():
global slicethick
global x_dim
global y_dim
global z_dim
global xpixdim
global ypixdim
global patientname
global pid
global dob
global FrameUID
global imageslice
global SeriesUID
global StudyInstanceUID
global imageuid
global patientfolder
global posrefind
global imagesetnumber
global image_orientation
currentpatientposition = getheaderinfo()
if os.path.isfile("%s%s/ImageSet_%s.img" % (Inputf, patientfolder, imagesetnumber)):
allframeslist = []
pixel_array = np.fromfile(
"%s%s/ImageSet_%s.img" % (Inputf, patientfolder, imagesetnumber), dtype=np.short)
for i in range(0, int(z_dim)): # will loop over every frame
frame_array = pixel_array[i * int(x_dim) *
int(y_dim):(i + 1) * int(x_dim) * int(y_dim)]
allframeslist.append(frame_array)
"""frame_array = np.array([])
temp_frame_array = pixel_array[i*int(x_dim)*int(y_dim):(i+1)*int(x_dim)*int(y_dim)]
for j in range(0, int(y_dim)):
temprow = temp_frame_array[j*int(x_dim):(j+1)*int(x_dim)][::-1]
frame_array = np.append(frame_array, temprow)
allframeslist.append(frame_array)
"""
print("Length of frames list: " + str(len(allframeslist)))
with open("%s%s/ImageSet_%s.ImageInfo" % (Inputf, patientfolder, imagesetnumber), 'rt', encoding=u'utf-8', errors='ignore') as f:
image_info = f.readlines()
curframe = 0
for i, line in enumerate(image_info, 0):
if "ImageInfo ={" in line:
sliceloc = - \
float(re.findall(r"[-+]?\d*\.\d+|\d+",
image_info[i + 1])[0]) * 10
instuid = re.findall(r'"([^"]*)"', image_info[i + 8])[0]
seriesuid = re.findall(r'"([^"]*)"', image_info[i + 4])[0]
classuid = re.findall(r'"([^"]*)"', image_info[i + 7])[0]
frameuid = re.findall(r'"([^"]*)"', image_info[i + 6])[0]
studyinstuid = re.findall(r'"([^"]*)"', image_info[i + 5])[0]
slicenum = int(re.findall(
r"[-+]?\d*\.\d+|\d+", image_info[i + 3])[0])
dateofscan, timeofscan = getdateandtime()
file_meta = Dataset()
file_meta.MediaStorageSOPClassUID = classuid
file_meta.MediaStorageSOPInstanceUID = instuid
# this value remains static since implementation for creating file is the same
file_meta.ImplementationClassUID = gImplementationClassUID
ds = FileDataset(planfilename, {},
file_meta=file_meta, preamble=b'\x00' * 128)
ds.SpecificCharacterSet = "ISO_IR 100"
ds.ImageType = ['ORIGINAL', 'PRIMARY', 'AXIAL']
ds.AccessionNumber = ''
ds.SOPClassUID = classuid
ds.SOPInstanceUID = instuid
ds.StudyDate = dateofscan
ds.SeriesDate = dateofscan
ds.AcquisitionDate = dateofscan
ds.ContentDate = dateofscan
ds.AcquisitionTime = timeofscan
ds.Modality = "CT" # Also should come from header file, but not always present
# This should come from Manufacturer in header, but for some patients it isn't set??
ds.Manufacturer = "GE MEDICAL SYSTEMS"
ds.StationName = "CT"
ds.PatientsName = patientname
ds.PatientID = pid
ds.PatientsBirthDate = dob
ds.BitsAllocated = 16
ds.BitsStored = 16
ds.HighBit = 15
ds.PixelRepresentation = 1
ds.RescaleIntercept = -1024
#ds.RescaleIntercept = 0.0
ds.RescaleSlope = 1.0
# ds.kvp = ?? This should be peak kilovoltage output of x ray generator used
ds.PatientPosition = currentpatientposition
# this is probably x_pixdim * xdim = y_pixdim * ydim
ds.DataCollectionDiameter = xpixdim * float(x_dim)
ds.SpatialResolution = 0.35 # ???????
# ds.DistanceSourceToDetector = #???
# ds.DistanceSourceToPatient = #????
ds.GantryDetectorTilt = 0.0 # ??
ds.TableHeight = -158.0 # ??
ds.RotationDirection = "CW" # ???
ds.ExposureTime = 1000 # ??
ds.XRayTubeCurrent = 398 # ??
ds.GeneratorPower = 48 # ??
ds.FocalSpots = 1.2 # ??
ds.ConvolutionKernel = "STND" # ????
ds.SliceThickness = slicethick
ds.NumberOfSlices = int(z_dim)
#ds.StudyInstanceUID = studyinstuid
#ds.SeriesInstanceUID = seriesuid
ds.FrameOfReferenceUID = FrameUID
ds.StudyInstanceUID = StudyInstanceUID
ds.SeriesInstanceUID = SeriesUID
# problem, some of these are repeated in image file so not sure what to do with that
ds.InstanceNumber = slicenum
ds.ImagePositionPatient = [-xpixdim *
float(x_dim) / 2, -ypixdim * float(y_dim) / 2, sliceloc]
if "HFS" in currentpatientposition or "FFS" in currentpatientposition:
ds.ImageOrientationPatient = [
1.0, 0.0, 0.0, 0.0, 1.0, -0.0]
elif "HFP" in currentpatientposition or "FFP" in currentpatientposition:
ds.ImageOrientationPatient = [-1.0,
0.0, 0.0, 0.0, -1.0, -0.0]
ds.PositionReferenceIndicator = "LM" # ???
ds.SliceLocation = sliceloc
ds.SamplesPerPixel = 1
ds.PhotometricInterpretation = "MONOCHROME2"
ds.Rows = int(x_dim)
ds.Columns = int(y_dim)
ds.PixelSpacing = [xpixdim, ypixdim]
#ds.PixelData = allframeslist[curframe]
#ds.PixelData = allframeslist[slicenum - 1]
ds.PixelData = allframeslist[curframe].tostring()
imageslice.append(sliceloc)
imageuid.append(instuid)
image_orientation = ds.ImageOrientationPatient
posrefind = ds.PositionReferenceIndicator
print("Creating image: " + Outputf + "%s/CT.%s.dcm" %
(patientfolder, instuid))
ds.save_as(Outputf + "%s/CT.%s.dcm" % (patientfolder, instuid))
curframe = curframe + 1
####################################################################################################################################################
####################################################################################################################################################
####################################################################################################################################################
# Function: getheaderinfo
# This function will only be called in cases where image files do not already exist
####################################################################################################################################################
def getheaderinfo():
global slicethick
global x_dim
global y_dim
global z_dim
global xpixdim
global ypixdim
temp_pos = ""
with open("%s%s/ImageSet_%s.header" % (Inputf, patientfolder, imagesetnumber), "rt", encoding=u'utf-8', errors='ignore') as f2:
for line in f2:
#print("line in header: " + line)
if "x_dim =" in line:
x_dim = (line.split(" ")[-1]
).replace(';', '').replace('\n', '')
if "y_dim =" in line:
y_dim = (line.split(" ")[-1]
).replace(';', '').replace('\n', '')
if "x_pixdim =" in line:
xpixdim = float((line.split(" ")[-1]).replace(';', '')) * 10
if "y_pixdim =" in line:
ypixdim = float((line.split(" ")[-1]).replace(';', '')) * 10
if "x_start =" in line and "index" not in line:
xstart = float((line.split(" ")[-1]).replace(';', ''))
print("xstart = ", xstart)
if "y_start =" in line:
ystart = float((line.split(" ")[-1]).replace(';', ''))
print("ystart = ", ystart)
if "z_dim =" in line:
z_dim = (line.split(" ")[-1]
).replace(';', '').replace('\n', '')
if "z_pixdim =" in line:
slicethick = float((line.split(" ")[-1]).replace(';', '')) * 10
if "z_start =" in line and "index" not in line:
zstart = float((line.split(" ")[-1]).replace(';', ''))
print("zstart = ", zstart)
if "patient_position" in line:
temp_pos = (line.split(" ")[-1]).replace("\n", "")
print("Patient_position is: " + temp_pos)
return temp_pos
####################################################################################################################################################
####################################################################################################################################################
####################################################################################################################################################
# Function: getdateandtime
# Will read ImageSet_%s.ImageSet file to get date and time of CT image aquisition, only used in cases where image files have not been created
####################################################################################################################################################
def getdateandtime():
with open("//Testfile", "rt", encoding=u'utf-8', errors='ignore') as g:
for line in g:
if "ScanTimeFromScanner" in line:
dateandtimestring = re.findall(r'"([^"]*)"', line)[0]
dateandtimelist = dateandtimestring.split(' ')
date = dateandtimelist[0].replace("-", "")
time = dateandtimelist[1].replace(":", "")
return date, time
####################################################################################################################################################
####################################################################################################################################################
####################################################################################################################################################
# function: readImageInfo
# Reads in the file ImageSet_0.ImageInfo to get uid values
# Saves the general UIDs as global variables
####################################################################################################################################################
def readImageInfo():
print("Reading image information for all image files\n")
global SeriesUID
global StudyInstanceUID
global FrameUID
global ClassUID
global patientfolder
global randval
global imagesetnumber
#print("Path to image info file: " + "%s%s/ImageSet_%s.ImageInfo"%(Inputf, patientfolder, imagesetnumber))
if not os.path.exists("%s%s/ImageSet_%s.ImageInfo" % (Inputf, patientfolder, imagesetnumber)):
#print("Leaving readImageInfo before getting info")
return
with open("%s%s/ImageSet_%s.ImageInfo" % (Inputf, patientfolder, imagesetnumber), 'rt', encoding=u'utf-8', errors='ignore') as f1:
for line in f1:
#print("For loop in readImageInfo")
if "SeriesUID" in line:
SeriesUID = re.findall(r'"([^"]*)"', line)[0]
#print("setting series uid: " + str(SeriesUID))
#SeriesUID = SeriesUID + "." + "0" + str(randval)
if "StudyInstanceUID" in line:
StudyInstanceUID = re.findall(r'"([^"]*)"', line)[0]
#print("setting study uid: " + str(StudyInstanceUID))
#StudyInstanceUID = StudyInstanceUID + "." + "0" + str(randval)
if "FrameUID" in line:
FrameUID = re.findall(r'"([^"]*)"', line)[0]
#print("setting frame uid: " + str(FrameUID))
# FrameUID = FrameUID[:-4] + "." + "0" + str(randval)
if "ClassUID" in line:
ClassUID = re.findall(r'"([^"]*)"', line)[0]
#print("setting class uid: " + str(ClassUID))
#ClassUID = ClassUID + "." + "0" + str(randval)
####################################################################################################################################################
####################################################################################################################################################
####################################################################################################################################################
# Creating a data structure to write to rt struct dicom file
# Based off example file write_new.py from C:\Python27\Lib\site-packages\dicom\examples\write_new.py
# returns data structure ds
####################################################################################################################################################
def createstructds():
print("Creating Data structure")
global structfilename
global structsopinstuid
# Populate required values for file meta information
file_meta = Dataset()
# RT Structure Set Storage
file_meta.MediaStorageSOPClassUID = '1.2.840.10008.5.1.4.1.1.481.3'
file_meta.MediaStorageSOPInstanceUID = structsopinstuid
structfilename = "RS." + structsopinstuid + ".dcm"
# this value remains static since implementation for creating file is the same
file_meta.ImplementationClassUID = gImplementationClassUID
# Create the FileDataset instance (initially no data elements, but file_meta supplied)
ds = FileDataset(structfilename, {}, file_meta=file_meta,
preamble=b'\x00' * 128)
# print(file_meta.preamble)
return ds
####################################################################################################################################################
####################################################################################################################################################
####################################################################################################################################################
# Function: getstructshift()
# Purpose: reads in values from ImageSet_0.header to get x and y shift
####################################################################################################################################################
def getstructshift():
global xshift
global yshift
global zshift
global patient_position
global imagesetnumber
with open("%s%s/ImageSet_%s.header" % (Inputf, patientfolder, imagesetnumber), "rt", encoding=u'utf-8', errors='ignore') as f2:
for line in f2:
if "x_dim =" in line:
x_dim = float((line.split(" ")[-1]).replace(';', ''))
if "y_dim =" in line:
y_dim = float((line.split(" ")[-1]).replace(';', ''))
if "x_pixdim =" in line:
xpixdim = float((line.split(" ")[-1]).replace(';', ''))
if "y_pixdim =" in line:
ypixdim = float((line.split(" ")[-1]).replace(';', ''))
if "x_start =" in line and "index" not in line:
xstart = float((line.split(" ")[-1]).replace(';', ''))
print("xstart = ", xstart)
if "y_start =" in line:
ystart = float((line.split(" ")[-1]).replace(';', ''))
if "z_dim =" in line:
z_dim = float((line.split(" ")[-1]).replace(';', ''))
if "z_pixdim =" in line:
zpixdim = float((line.split(" ")[-1]).replace(';', ''))
if "z_start =" in line and "index" not in line:
zstart = float((line.split(" ")[-1]).replace(';', ''))
if patient_position == 'HFS':
xshift = ((x_dim * xpixdim / 2) + xstart) * 10
print("X shift = ", xshift)
yshift = -((y_dim * ypixdim / 2) + ystart) * 10
print("Y shift = ", yshift)
zshift = -((z_dim * zpixdim / 2) + zstart) * 10
print("Z shift = ", zshift)
elif patient_position == 'HFP':
xshift = -((x_dim * xpixdim / 2) + xstart) * 10
print("X shift = ", xshift)
yshift = ((y_dim * ypixdim / 2) + ystart) * 10
print("Y shift = ", yshift)
zshift = -((z_dim * zpixdim / 2) + zstart) * 10
elif patient_position == 'FFP':
xshift = ((x_dim * xpixdim / 2) + xstart) * 10
print("X shift = ", xshift)
yshift = ((y_dim * ypixdim / 2) + ystart) * 10
print("Y shift = ", yshift)
zshift = ((z_dim * zpixdim / 2) + zstart) * 10
elif patient_position == 'FFS':
xshift = -((x_dim * xpixdim / 2) + xstart) * 10
print("X shift = ", xshift)
yshift = -((y_dim * ypixdim / 2) + ystart) * 10
print("Y shift = ", yshift)
zshift = ((z_dim * zpixdim / 2) + zstart) * 10
####################################################################################################################################################
####################################################################################################################################################
####################################################################################################################################################
# Function: createplands()
# creates a data structure for the rt plan file
# similar to createstructds but different UIDs
####################################################################################################################################################
def createplands(plannumber):
print("Creating plan Data Structure\n")
global planfilename
global plansopinstuid
file_meta = Dataset()
file_meta.MediaStorageSOPClassUID = '1.2.840.10008.5.1.4.1.1.481.5' # RT Plan Storage
file_meta.MediaStorageSOPInstanceUID = plansopinstuid + \
"." + str(plannumber)
# this value remains static since implementation for creating file is the same
file_meta.ImplementationClassUID = gImplementationClassUID
ds = FileDataset(planfilename, {}, file_meta=file_meta,
preamble=b'\x00' * 128)
return ds
####################################################################################################################################################
####################################################################################################################################################
####################################################################################################################################################
# Function to initialize data structure, sets Specific Character set,
# instance creation time and date, SOP Class UID, and SOP Instance UID
# also sets modality and data structure
####################################################################################################################################################
def initds(ds):
print("initializing data structure\n")
global imageuids
global SeriesUID
global StudyInstanceUID
global FrameUID
global ClassUID
global structsopinstuid
global structseriesinstuid
# not sure what I want here, going off of template dicom file
ds.SpecificCharacterSet = 'ISO_IR 100'
ds.InstanceCreationDate = time.strftime("%Y%m%d")
ds.InstanceCreationTime = time.strftime("%H%M%S")
ds.SOPClassUID = '1.2.840.10008.5.1.4.1.1.481.3'
ds.SOPInstanceUID = structsopinstuid
ds.Modality = 'RTSTRUCT'
ds.AccessionNumber = ""
ds.Manufacturer = Manufacturer # from sample dicom file, maybe should change?
# not sure where to get information for this element can find this and read in from
ds.StationName = "adacp3u7"
#ds.ManufacturersModelName = 'Pinnacle3'
ReferencedStudy1 = Dataset()
ds.ReferencedStudySequence.append(ReferencedStudy1)
# Study Component Management SOP Class (chosen from template)
ds.ReferencedStudySequence[0].ReferencedSOPClassUID = '1.2.840.10008.3.1.2.3.2'
ds.ReferencedStudySequence[0].ReferencedSOPInstanceUID = StudyInstanceUID
ds.StudyInstanceUID = StudyInstanceUID
print("Setting structure file study instance: " + str(StudyInstanceUID))
ds.SeriesInstanceUID = structseriesinstuid
return ds
####################################################################################################################################################
####################################################################################################################################################
####################################################################################################################################################
# function to read in patient info from Patient text file
####################################################################################################################################################
def readpatientinfo(ds):