parseDicom.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. import os
  2. import sys
  3. import dicom
  4. import numpy as np
  5. import re
  6. import slicer
  7. #rom os import listdir
  8. #from os.path import isfile, join
  9. #onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
  10. #import Tkinter as tk
  11. #from Tkinter import filedialog
  12. #root = tk.Tk()
  13. #root.withdraw()
  14. #file_path = filedialog.askopenfilename()
  15. class parseDicom:
  16. def __init__(self, parent):
  17. parent.title = "parse dicom"
  18. parent.categories = ["Examples"]
  19. parent.dependencies = []
  20. parent.contributors = ["Andrej Studen (FMF/JSI)"] # replace with "Firstname Lastname (Org)"
  21. parent.helpText = """
  22. Parse dynamic SPECT DICOM files
  23. """
  24. parent.acknowledgementText = """
  25. This module was developed within the frame of the ARRS sponsored medical
  26. physics research programe to investigate quantitative measurements of cardiac
  27. function using sestamibi-like tracers
  28. """ # replace with organization, grant and thanks.
  29. self.parent = parent
  30. def filelist(mypath):
  31. #mypath=os.environ['PWD']
  32. #list files
  33. if mypath.find('labkey://')==0:
  34. print("Using labkey")
  35. labkeyPath=re.sub('labkey://','',mypath)
  36. #not sure if labkey is available, so try it
  37. net=slicer.modules.labkeySlicerPythonExtensionWidget.network
  38. print("Found network")
  39. url=slicer.modules.labkeySlicerPythonExtensionWidget.serverURL.text
  40. print("Seting url={}".format(url))
  41. files=net.listDir(str(url),labkeyPath)
  42. print files
  43. if mypath.find('file://')==0:
  44. print("Using local files")
  45. localPath=re.sub('file://','',mypath)
  46. files = [os.path.join(localPath,f) for f in os.listdir(localPath)
  47. if os.path.isfile(os.path.join(localPath, f))]
  48. return files
  49. def getfile(origin,f):
  50. if origin.find('labkey')==0:
  51. try:
  52. #not sure if labkey is available, but try it
  53. net=slicer.modules.labkeySlicerPythonExtensionWidget.network
  54. print("Using labkey")
  55. url=slicer.modules.labkeySlicerPythonExtensionWidget.serverURL.text
  56. print("Sever:{0}, file:{1}".format(url,f))
  57. return [net.readFile(str(url),f),1]
  58. except:
  59. print('Could not access labkey. Exiting')
  60. return ['NULL',0]
  61. if origin.find('file')==0:
  62. print("Using local directory")
  63. return [f,1]
  64. return ['NULL',0]
  65. def read_dynamic_SPECT(mypath):
  66. origin=re.sub('([^:/])://(.*)$',r'\1',mypath)
  67. onlyfiles=filelist(mypath)
  68. for f in onlyfiles:
  69. print '{}:'.format(f)
  70. g,ok=getfile(origin,f)
  71. if not(ok):
  72. return
  73. try:
  74. plan = dicom.read_file(g)
  75. except:
  76. print ("Not a dicom file")
  77. continue
  78. try:
  79. nframe=plan[0x0019,0x10a5].value;
  80. except:
  81. print ("Tag not found;")
  82. continue
  83. if not (type(nframe) is list) :
  84. print("nframe not a list")
  85. continue
  86. #this is the "master" file where data on other files can be had
  87. #here we found out the duration of the frame and their distribution through
  88. #phases and cycles
  89. print('Found master file')
  90. for i in range(1,len(nframe)):
  91. nframe[i]+=nframe[i-1]
  92. print(nframe)
  93. #nframe now holds for index i total number of frames collected up
  94. #to the end of each phase
  95. frame_start=plan[0x0019,0x10a7].value
  96. frame_stop=plan[0x0019,0x10a8].value
  97. frame_duration=plan[0x0019,0x10a9].value
  98. break
  99. #print "rep [{}] start [{}] stop [{}] duration [{}]".format(
  100. #len(rep),len(rep_start),len(rep_stop),len(rep_duration))
  101. #select AC reconstructed data
  102. frame_time=np.zeros(nframe[-1]);
  103. frame_data=np.empty([1,1,1,nframe[-1]])
  104. center = [0,0,0]
  105. pixel_size =[0,0,0]
  106. frame_orientation=[0,0,0,0,0,0]
  107. for f in onlyfiles:
  108. g,ok=getfile(origin,f)
  109. if not(ok):
  110. return
  111. try:
  112. plan = dicom.read_file(g)
  113. except:
  114. print ("Not a dicom file")
  115. continue
  116. try:
  117. pf=plan[0x0018,0x5020]
  118. except:
  119. print ("Tag not found")
  120. continue
  121. try:
  122. phase=plan[0x0035,0x1005].value
  123. cycle=plan[0x0035,0x1004].value
  124. except:
  125. print ("Phase/Cycle tag not found")
  126. continue
  127. #convert phase/cycle to frame index
  128. off=0
  129. if phase > 1:
  130. off=nframe[phase-2]
  131. ifi=off+cycle-1
  132. #from values in the master file determine frame time
  133. #(as the mid point between starting and ending the frame)
  134. frame_time[ifi]=0.5*(frame_start[ifi]+frame_stop[ifi]); #in ms
  135. print "({},{}) converted to {} at {} for {}".format(
  136. phase,cycle,ifi,frame_time[ifi],frame_duration[ifi])
  137. #play with pixel data
  138. if frame_data.shape[0] == 1:
  139. sh=plan.pixel_array.shape;
  140. sh=list(sh)
  141. sh.append(nframe[-1])
  142. frame_data=np.empty(sh)
  143. print "Setting frame_data to",sh
  144. #check & update pixel size
  145. pixel_size_read=[plan.PixelSpacing[0],plan.PixelSpacing[1],
  146. plan.SliceThickness]
  147. for i in range(0,3):
  148. if pixel_size[i] == 0:
  149. pixel_size[i] = float(pixel_size_read[i])
  150. if abs(pixel_size[i]-pixel_size_read[i]) > 1e-3:
  151. print 'Pixel size mismatch {.2f}/{.2f}'.format(pixel_size[i],
  152. pixel_size_read[i])
  153. center_read=plan.DetectorInformationSequence[0].ImagePositionPatient
  154. for i in range(0,3):
  155. if center[i] == 0:
  156. center[i] = float(center_read[i])
  157. if abs(center[i]-center_read[i]) > 1e-3:
  158. print 'Image center mismatch {.2f}/{.2f}'.format(center[i],
  159. center_read[i])
  160. frame_orientation_read=plan.DetectorInformationSequence[0].ImageOrientationPatient
  161. for i in range(0,6):
  162. if frame_orientation[i] == 0:
  163. frame_orientation[i] = float(frame_orientation_read[i])
  164. if abs(frame_orientation[i]-frame_orientation_read[i]) > 1e-3:
  165. print 'Image orientation mismatch {.2f}/{.2f}'.format(
  166. frame_rotation[i], frame_orientation_read[i])
  167. frame_data[:,:,:,ifi]=plan.pixel_array
  168. #print('Orientation: ({0:.2f},{1:.2f},{2:.2f}),({3:.2f},{4:.2f},{5:.2f})').format( \
  169. # frame_orientation[0],frame_orientation[1],frame_orientation[2], \
  170. # frame_orientation[3],frame_orientation[4],frame_orientation[5])
  171. return [frame_data,frame_time,center,pixel_size,frame_orientation]
  172. def read_CT(mypath):
  173. onlyfiles=filelist(mypath)
  174. origin=re.sub('([^:/])://(.*)$',r'\1',mypath)
  175. ct_data = []
  176. ct_idx = []
  177. ct_pixel_size = [0,0,0]
  178. ct_center = [0,0,0]
  179. ct_center[2]=1e30
  180. ct_orientation=[0,0,0,0,0,0]
  181. for f in onlyfiles:
  182. print '{}:'.format(f)
  183. g,ok=getfile(origin,f)
  184. if not(ok):
  185. return
  186. try:
  187. plan = dicom.read_file(g)
  188. except:
  189. print ("Not a dicom file")
  190. continue
  191. if plan.Modality != 'CT':
  192. print ('Not a CT file')
  193. continue
  194. if re.match("AC",plan.SeriesDescription) == None:
  195. print (plan.SeriesDescription)
  196. print ('Not a AC file')
  197. continue
  198. #a slice of pure CT
  199. print '.',
  200. ct_data.append(plan.pixel_array)
  201. ct_idx.append(plan.InstanceNumber)
  202. #ct_center.append(plan.ImagePositionPatient)
  203. pixel_size_read=[plan.PixelSpacing[0],plan.PixelSpacing[1],
  204. plan.SliceThickness]
  205. for i in range(0,3):
  206. if ct_pixel_size[i] == 0:
  207. ct_pixel_size[i] = float(pixel_size_read[i])
  208. if abs(ct_pixel_size[i]-pixel_size_read[i]) > 1e-3:
  209. print 'Pixel size mismatch {.2f}/{.2f}'.format(ct_pixel_size[i],
  210. pixel_size_read[i])
  211. for i in range(0,2):
  212. if ct_center[i] == 0:
  213. ct_center[i] = float(plan.ImagePositionPatient[i])
  214. if abs(ct_center[i]-plan.ImagePositionPatient[i]) > 1e-3:
  215. print 'Image center mismatch {.2f}/{.2f}'.format(ct_center[i],
  216. plan.ImagePositionPatient[i])
  217. #not average, but minimum (!)
  218. if plan.ImagePositionPatient[2]<ct_center[2]:
  219. ct_center[2]=plan.ImagePositionPatient[2]
  220. for i in range(0,6):
  221. if ct_orientation[i] == 0:
  222. ct_orientation[i] = float(plan.ImageOrientationPatient[i])
  223. if abs(ct_orientation[i]-plan.ImageOrientationPatient[i]) > 1e-3:
  224. print 'Image orientation mismatch {0:.2f}/{1:.2f}'.format(ct_orientation[i],
  225. plan.ImageOrientationPatient[i])
  226. print
  227. nz=len(ct_idx)
  228. #not average, again
  229. #ct_center[2]/=nz
  230. sh=ct_data[-1].shape
  231. sh_list=list(sh)
  232. sh_list.append(nz)
  233. data_array=np.zeros(sh_list)
  234. for k in range(0,nz):
  235. data_array[:,:,ct_idx[k]-1]=ct_data[k]
  236. return data_array,ct_center,ct_pixel_size,ct_orientation