parseDicom.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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. print("nframe not a list")
  48. continue
  49. #this is the "master" file where data on other files can be had
  50. #here we found out the duration of the frame and their distribution through
  51. #phases and cycles
  52. print('Found master file')
  53. for i in range(1,len(nframe)):
  54. nframe[i]+=nframe[i-1]
  55. print(nframe)
  56. #nframe now holds for index i total number of frames collected up
  57. #to the end of each phase
  58. frame_start=plan[0x0019,0x10a7].value
  59. frame_stop=plan[0x0019,0x10a8].value
  60. frame_duration=plan[0x0019,0x10a9].value
  61. break
  62. #print "rep [{}] start [{}] stop [{}] duration [{}]".format(
  63. #len(rep),len(rep_start),len(rep_stop),len(rep_duration))
  64. #select AC reconstructed data
  65. frame_time=np.zeros(nframe[-1]);
  66. frame_data=np.empty([1,1,1,nframe[-1]])
  67. center = [0,0,0]
  68. pixel_size =[0,0,0]
  69. frame_orientation=[0,0,0,0,0,0]
  70. for f in onlyfiles:
  71. try:
  72. plan = dicom.read_file(os.path.join(mypath,f))
  73. except:
  74. print ("Not a dicom file")
  75. continue
  76. try:
  77. pf=plan[0x0018,0x5020]
  78. except:
  79. print ("Tag not found")
  80. continue
  81. try:
  82. phase=plan[0x0035,0x1005].value
  83. cycle=plan[0x0035,0x1004].value
  84. except:
  85. print ("Phase/Cycle tag not found")
  86. continue
  87. #convert phase/cycle to frame index
  88. off=0
  89. if phase > 1:
  90. off=nframe[phase-2]
  91. ifi=off+cycle-1
  92. #from values in the master file determine frame time
  93. #(as the mid point between starting and ending the frame)
  94. frame_time[ifi]=0.5*(frame_start[ifi]+frame_stop[ifi]); #in ms
  95. print "({},{}) converted to {} at {} for {}".format(
  96. phase,cycle,ifi,frame_time[ifi],frame_duration[ifi])
  97. #play with pixel data
  98. if frame_data.shape[0] == 1:
  99. sh=plan.pixel_array.shape;
  100. sh=list(sh)
  101. sh.append(nframe[-1])
  102. frame_data=np.empty(sh)
  103. print "Setting frame_data to",sh
  104. #check & update pixel size
  105. pixel_size_read=[plan.PixelSpacing[0],plan.PixelSpacing[1],
  106. plan.SliceThickness]
  107. for i in range(0,3):
  108. if pixel_size[i] == 0:
  109. pixel_size[i] = float(pixel_size_read[i])
  110. if abs(pixel_size[i]-pixel_size_read[i]) > 1e-3:
  111. print 'Pixel size mismatch {.2f}/{.2f}'.format(pixel_size[i],
  112. pixel_size_read[i])
  113. center_read=plan.DetectorInformationSequence[0].ImagePositionPatient
  114. for i in range(0,3):
  115. if center[i] == 0:
  116. center[i] = float(center_read[i])
  117. if abs(center[i]-center_read[i]) > 1e-3:
  118. print 'Image center mismatch {.2f}/{.2f}'.format(center[i],
  119. center_read[i])
  120. frame_orientation_read=plan.DetectorInformationSequence[0].ImageOrientationPatient
  121. for i in range(0,6):
  122. if frame_orientation[i] == 0:
  123. frame_orientation[i] = float(frame_orientation_read[i])
  124. if abs(frame_orientation[i]-frame_orientation_read[i]) > 1e-3:
  125. print 'Image orientation mismatch {.2f}/{.2f}'.format(
  126. frame_rotation[i], frame_orientation_read[i])
  127. frame_data[:,:,:,ifi]=plan.pixel_array
  128. #print('Orientation: ({0:.2f},{1:.2f},{2:.2f}),({3:.2f},{4:.2f},{5:.2f})').format( \
  129. # frame_orientation[0],frame_orientation[1],frame_orientation[2], \
  130. # frame_orientation[3],frame_orientation[4],frame_orientation[5])
  131. return [frame_data,frame_time,center,pixel_size,frame_orientation]
  132. def read_CT(mypath):
  133. onlyfiles = [f for f in os.listdir(mypath)
  134. if os.path.isfile(os.path.join(mypath, f))]
  135. ct_data = []
  136. ct_idx = []
  137. ct_pixel_size = [0,0,0]
  138. ct_center = [0,0,0]
  139. ct_center[2]=1e30
  140. ct_orientation=[0,0,0,0,0,0]
  141. for f in onlyfiles:
  142. print '{}:'.format(f)
  143. try:
  144. plan = dicom.read_file(os.path.join(mypath,f))
  145. except:
  146. print ("Not a dicom file")
  147. continue
  148. if plan.Modality != 'CT':
  149. print ('Not a CT file')
  150. continue
  151. if re.match("AC",plan.SeriesDescription) == None:
  152. print (plan.SeriesDescription)
  153. print ('Not a AC file')
  154. continue
  155. #a slice of pure CT
  156. print '.',
  157. ct_data.append(plan.pixel_array)
  158. ct_idx.append(plan.InstanceNumber)
  159. #ct_center.append(plan.ImagePositionPatient)
  160. pixel_size_read=[plan.PixelSpacing[0],plan.PixelSpacing[1],
  161. plan.SliceThickness]
  162. for i in range(0,3):
  163. if ct_pixel_size[i] == 0:
  164. ct_pixel_size[i] = float(pixel_size_read[i])
  165. if abs(ct_pixel_size[i]-pixel_size_read[i]) > 1e-3:
  166. print 'Pixel size mismatch {.2f}/{.2f}'.format(ct_pixel_size[i],
  167. pixel_size_read[i])
  168. for i in range(0,2):
  169. if ct_center[i] == 0:
  170. ct_center[i] = float(plan.ImagePositionPatient[i])
  171. if abs(ct_center[i]-plan.ImagePositionPatient[i]) > 1e-3:
  172. print 'Image center mismatch {.2f}/{.2f}'.format(ct_center[i],
  173. plan.ImagePositionPatient[i])
  174. #not average, but minimum (!)
  175. if plan.ImagePositionPatient[2]<ct_center[2]:
  176. ct_center[2]=plan.ImagePositionPatient[2]
  177. for i in range(0,6):
  178. if ct_orientation[i] == 0:
  179. ct_orientation[i] = float(plan.ImageOrientationPatient[i])
  180. if abs(ct_orientation[i]-plan.ImageOrientationPatient[i]) > 1e-3:
  181. print 'Image orientation mismatch {0:.2f}/{1:.2f}'.format(ct_orientation[i],
  182. plan.ImageOrientationPatient[i])
  183. print
  184. nz=len(ct_idx)
  185. #not average, again
  186. #ct_center[2]/=nz
  187. sh=ct_data[-1].shape
  188. sh_list=list(sh)
  189. sh_list.append(nz)
  190. data_array=np.zeros(sh_list)
  191. for k in range(0,nz):
  192. data_array[:,:,ct_idx[k]-1]=ct_data[k]
  193. return data_array,ct_center,ct_pixel_size,ct_orientation