parseDicom.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. import os
  2. import sys
  3. import dicom
  4. import numpy as np
  5. import re
  6. #rom os import listdir
  7. #from os.path import isfile, join
  8. #onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
  9. #import Tkinter as tk
  10. #from Tkinter import filedialog
  11. #root = tk.Tk()
  12. #root.withdraw()
  13. #file_path = filedialog.askopenfilename()
  14. class parseDicom:
  15. def __init__(self, parent):
  16. parent.title = "parse dicom"
  17. parent.categories = ["Examples"]
  18. parent.dependencies = []
  19. parent.contributors = ["Andrej Studen (FMF/JSI)"] # replace with "Firstname Lastname (Org)"
  20. parent.helpText = """
  21. Parse dynamic SPECT DICOM files
  22. """
  23. parent.acknowledgementText = """
  24. This module was developed within the frame of the ARRS sponsored medical
  25. physics research programe to investigate quantitative measurements of cardiac
  26. function using sestamibi-like tracers
  27. """ # replace with organization, grant and thanks.
  28. self.parent = parent
  29. def read_dynamic_SPECT(mypath):
  30. #mypath=os.environ['PWD']
  31. #list files
  32. onlyfiles = [f for f in os.listdir(mypath)
  33. if os.path.isfile(os.path.join(mypath, f))]
  34. for f in onlyfiles:
  35. print '{}:'.format(f)
  36. try:
  37. plan = dicom.read_file(os.path.join(mypath,f))
  38. except:
  39. print ("Not a dicom file")
  40. continue
  41. try:
  42. nframe=plan[0x0019,0x10a5].value;
  43. except:
  44. print ("Tag not found;")
  45. continue
  46. if not (type(nframe) is list) :
  47. continue
  48. #this is the "master" file where data on other files can be had
  49. #here we found out the duration of the frame and their distribution through
  50. #phases and cycles
  51. for i in range(1,len(nframe)):
  52. nframe[i]+=nframe[i-1]
  53. print(nframe)
  54. #nframe now holds for index i total number of frames collected up
  55. #to the end of each phase
  56. frame_start=plan[0x0019,0x10a7].value
  57. frame_stop=plan[0x0019,0x10a8].value
  58. frame_duration=plan[0x0019,0x10a9].value
  59. #print "rep [{}] start [{}] stop [{}] duration [{}]".format(
  60. #len(rep),len(rep_start),len(rep_stop),len(rep_duration))
  61. #select AC reconstructed data
  62. frame_time=[None]*nframe[-1]
  63. frame_data=np.empty([1,1,1,nframe[-1]])
  64. for f in onlyfiles:
  65. try:
  66. plan = dicom.read_file(os.path.join(mypath,f))
  67. except:
  68. print ("Not a dicom file")
  69. continue
  70. try:
  71. pf=plan[0x0018,0x5020]
  72. except:
  73. print ("Tag not found")
  74. continue
  75. try:
  76. phase=plan[0x0035,0x1005].value
  77. cycle=plan[0x0035,0x1004].value
  78. except:
  79. print ("Phase/Cycle tag not found")
  80. continue
  81. #convert phase/cycle to frame index
  82. off=0
  83. if phase > 1:
  84. off=nframe[phase-2]
  85. ifi=off+cycle-1
  86. #from values in the master file determine frame time
  87. #(as the mid point between starting and ending the frame)
  88. frame_time[ifi]=0.5*(frame_start[ifi]+frame_stop[ifi]); #in ms
  89. print "({},{}) converted to {} at {} for {}".format(
  90. phase,cycle,ifi,frame_time[ifi],frame_duration[ifi])
  91. #play with pixel data
  92. if frame_data.shape[0] == 1:
  93. sh=plan.pixel_array.shape;
  94. sh=list(sh)
  95. sh.append(nframe[-1])
  96. frame_data=np.empty(sh)
  97. print "Setting frame_data to",sh
  98. frame_data[:,:,:,ifi]=plan.pixel_array
  99. return [frame_data,frame_time]
  100. def read_CT(mypath):
  101. onlyfiles = [f for f in os.listdir(mypath)
  102. if os.path.isfile(os.path.join(mypath, f))]
  103. ct_data = []
  104. ct_idx = []
  105. ct_pixel_size = [0,0,0]
  106. ct_center = [0,0,0]
  107. for f in onlyfiles:
  108. print '{}:'.format(f)
  109. try:
  110. plan = dicom.read_file(os.path.join(mypath,f))
  111. except:
  112. print ("Not a dicom file")
  113. continue
  114. if plan.Modality != 'CT':
  115. print ('Not a CT file')
  116. continue
  117. if re.match("AC",plan.SeriesDescription) == None:
  118. print (plan.SeriesDescription)
  119. print ('Not a AC file')
  120. continue
  121. #a slice of pure CT
  122. ct_data.append(plan.pixel_array)
  123. ct_idx.append(plan.InstanceNumber)
  124. #ct_center.append(plan.ImagePositionPatient)
  125. pixel_size_read=[plan.PixelSpacing[0],plan.PixelSpacing[1],
  126. plan.SliceThickness]
  127. for i in range(0,3):
  128. if ct_pixel_size[i] == 0:
  129. ct_pixel_size[i] = float(pixel_size_read[i])
  130. if abs(ct_pixel_size[i]-pixel_size_read[i]) > 1e-3:
  131. print 'Pixel size mismatch {.2f}/{.2f}'.format(ct_pixel_size[i],
  132. pixel_size_read[i])
  133. for i in range(0,2):
  134. if ct_center[i] == 0:
  135. ct_center[i] = float(plan.ImagePositionPatient[i])
  136. if abs(ct_center[i]-plan.ImagePositionPatient[i]) > 1e-3:
  137. print 'Image center mismatch {.2f}/{.2f}'.format(ct_center[i],
  138. plan.ImagePositionPatient[i])
  139. #not average, but minimum (!)
  140. if plan.ImagePositionPatient[2]<ct_center[2]:
  141. ct_center[2]=plan.ImagePositionPatient[2]
  142. nz=len(ct_idx)
  143. #not average, again
  144. #ct_center[2]/=nz
  145. sh=ct_data[-1].shape
  146. sh_list=list(sh)
  147. sh_list.append(nz)
  148. data_array=np.zeros(sh_list)
  149. for k in range(0,nz):
  150. data_array[:,:,ct_idx[k]-1]=ct_data[k]
  151. return data_array,ct_center,ct_pixel_size