parseDicom.py 11 KB

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