parseDicom.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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. files=[self.net.GetRelativePathFromLabkeyPath(f) for f in files]
  53. if mypath.find('file://')==0:
  54. print("Using local files")
  55. localPath=re.sub('file://','',mypath)
  56. files = [os.path.join(localPath,f) for f in os.listdir(localPath)
  57. if os.path.isfile(os.path.join(localPath, f))]
  58. return files
  59. def getfile(self,origin,f):
  60. if origin.find('labkey')==0:
  61. try:
  62. #not sure if labkey is available, but try it
  63. print("Using labkey")
  64. print("Server:{0}, file:{1}".format(self.net.GetHostName(),f))
  65. localPath=self.net.DownloadFileToCache(f)
  66. #return [self.net.readFileToBuffer(f),1]
  67. return [open(localPath,'rb'),1]
  68. except:
  69. print('Could not access labkey. Exiting')
  70. return ['NULL',0]
  71. if origin.find('file')==0:
  72. print("Using local directory")
  73. return [open(f,'rb'),1]
  74. return ['NULL',0]
  75. def readMasterFile(self,g):
  76. #this is the "master" file where data on other files can be had
  77. #here we found out the duration of the frame and their distribution through
  78. #phases and cycles
  79. try:
  80. plan = dicom.read_file(g)
  81. except:
  82. print ("{}: Not a dicom file").format(g)
  83. return False
  84. try:
  85. self.nframe=plan[0x0019,0x10a5].value;
  86. except:
  87. print ("{}: Not a master file").format(g)
  88. return False
  89. if not (type(self.nframe) is list) :
  90. print("nframe not a list")
  91. return False
  92. #nframe now holds for index i total number of frames collected up
  93. #to the end of each phase
  94. for i in range(1,len(self.nframe)):
  95. self.nframe[i]+=self.nframe[i-1]
  96. self.frame_start=plan[0x0019,0x10a7].value
  97. self.frame_stop=plan[0x0019,0x10a8].value
  98. self.frame_duration=plan[0x0019,0x10a9].value
  99. self.frame_time=np.zeros(self.nframe[-1]);
  100. self.frame_data=np.empty([1,1,1,self.nframe[-1]])
  101. self.center = [0,0,0]
  102. self.pixel_size =[0,0,0]
  103. self.frame_orientation=[0,0,0,0,0,0]
  104. return True
  105. def readNMFile(self,g):
  106. try:
  107. plan = dicom.read_file(g)
  108. except:
  109. print ("{}: Not a dicom file").format(g)
  110. return False
  111. try:
  112. pf=plan[0x0018,0x5020]
  113. except:
  114. print("Not a NM file. Exiting")
  115. return False
  116. try:
  117. phase=plan[0x0035,0x1005].value
  118. cycle=plan[0x0035,0x1004].value
  119. except:
  120. print("Missing phase/cycle values")
  121. return False
  122. #convert phase/cycle to frame index
  123. off=0
  124. if phase > 1:
  125. off=self.nframe[phase-2]
  126. ifi=off+cycle-1
  127. #from values in the master file determine frame time
  128. #(as the mid point between starting and ending the frame)
  129. self.frame_time[ifi]=0.5*(self.frame_start[ifi]+self.frame_stop[ifi]); #in ms
  130. print "({},{}) converted to {} at {} for {}".format(
  131. phase,cycle,ifi,self.frame_time[ifi],self.frame_duration[ifi])
  132. #play with pixel data
  133. if self.frame_data.shape[0] == 1:
  134. sh=np.transpose(plan.pixel_array,self.axisShift).shape;
  135. sh=list(sh)
  136. sh.append(self.nframe[-1])#add number of time slots
  137. self.frame_data=np.empty(sh)
  138. print "Setting frame_data to",sh
  139. #check & update pixel size
  140. pixel_size_read=[plan.PixelSpacing[0],plan.PixelSpacing[1],
  141. plan.SliceThickness]
  142. for i in range(0,3):
  143. if self.pixel_size[i] == 0:
  144. self.pixel_size[i] = float(pixel_size_read[i])
  145. if abs(self.pixel_size[i]-pixel_size_read[i]) > 1e-3:
  146. print 'Pixel size mismatch {.2f}/{.2f}'.format(self.pixel_size[i],
  147. pixel_size_read[i])
  148. center_read=plan.DetectorInformationSequence[0].ImagePositionPatient
  149. print "Stored center at ({0},{1},{2})".format(self.center[0],self.center[1],self.center[2])
  150. print "Read center at ({0},{1},{2})".format(center_read[0],center_read[1],center_read[2])
  151. for i in range(0,3):
  152. if self.center[i] == 0:
  153. self.center[i] = float(center_read[i])
  154. if abs(self.center[i]-center_read[i]) > 1e-3:
  155. print 'Image center mismatch {.2f}/{.2f}'.format(self.center[i],
  156. center_read[i])
  157. frame_orientation_read=plan.DetectorInformationSequence[0].ImageOrientationPatient
  158. for i in range(0,6):
  159. if self.frame_orientation[i] == 0:
  160. self.frame_orientation[i] = float(frame_orientation_read[i])
  161. if abs(self.frame_orientation[i]-frame_orientation_read[i]) > 1e-3:
  162. print 'Image orientation mismatch {.2f}/{.2f}'.format(
  163. self.frame_rotation[i], frame_orientation_read[i])
  164. self.frame_data[:,:,:,ifi]=np.transpose(plan.pixel_array,self.axisShift)
  165. return True
  166. def readCTFile(self,g):
  167. try:
  168. plan = dicom.read_file(g)
  169. except:
  170. print ("{}: Not a dicom file").format(g)
  171. return False
  172. if plan.Modality != 'CT':
  173. print ('{}: Not a CT file').format(g)
  174. return False
  175. #this doesn't work in 2019 data version
  176. #if re.match("AC",plan.SeriesDescription) == None:
  177. # print (plan.SeriesDescription)
  178. # print ('Not a AC file')
  179. # continue
  180. try:
  181. iType=plan.ImageType
  182. except:
  183. print "Image type not found"
  184. return False
  185. if iType[3].find("SPI")<0:
  186. print "Not a spiral image"
  187. return False
  188. print '.',
  189. self.ct_data.append(plan.pixel_array)
  190. self.ct_idx.append(plan.InstanceNumber)
  191. self.ct_z.append(plan.ImagePositionPatient[2])
  192. pixel_size_read=[plan.PixelSpacing[0],plan.PixelSpacing[1],
  193. plan.SliceThickness]
  194. for i in range(0,3):
  195. if self.ct_pixel_size[i] == 0:
  196. self.ct_pixel_size[i] = float(pixel_size_read[i])
  197. if abs(self.ct_pixel_size[i]-pixel_size_read[i]) > 1e-3:
  198. print 'Pixel size mismatch {.2f}/{.2f}'.format(self.ct_pixel_size[i],
  199. pixel_size_read[i])
  200. for i in range(0,2):
  201. if self.ct_center[i] == 0:
  202. self.ct_center[i] = float(plan.ImagePositionPatient[i])
  203. if abs(self.ct_center[i]-plan.ImagePositionPatient[i]) > 1e-3:
  204. print 'Image center mismatch {.2f}/{.2f}'.format(self.ct_center[i],
  205. plan.ImagePositionPatient[i])
  206. #not average, but minimum (!) why??
  207. if plan.ImagePositionPatient[2]<self.ct_center[2]:
  208. self.ct_center[2]=plan.ImagePositionPatient[2]
  209. for i in range(0,6):
  210. if self.ct_orientation[i] == 0:
  211. self.ct_orientation[i] = float(plan.ImageOrientationPatient[i])
  212. if abs(self.ct_orientation[i]-plan.ImageOrientationPatient[i]) > 1e-3:
  213. print 'Image orientation mismatch {0:.2f}/{1:.2f}'.format(self.ct_orientation[i],
  214. plan.ImageOrientationPatient[i])
  215. return True
  216. def readMasterDirectory(self,mypath):
  217. self.axisShift=(2,1,0)
  218. print("Reading master from {}").format(mypath)
  219. origin=re.sub('([^:/])://(.*)$',r'\1',mypath)
  220. relativeFiles=self.filelist(mypath)
  221. for f in relativeFiles:
  222. print '{}:'.format(f)
  223. g,ok=self.getfile(origin,f)
  224. if not(ok):
  225. return
  226. if self.readMasterFile(g):
  227. break
  228. def readNMDirectory(self,mypath):
  229. onlyfiles=self.filelist(mypath)
  230. origin=re.sub('([^:/])://(.*)$',r'\1',mypath)
  231. for f in onlyfiles:
  232. g,ok=self.getfile(origin,f)
  233. if not(ok):
  234. continue
  235. self.readNMFile(g)
  236. return [self.frame_data,self.frame_time,self.center,
  237. self.pixel_size,self.frame_orientation]
  238. def readCTDirectory(self,mypath):
  239. onlyfiles=self.filelist(mypath)
  240. origin=re.sub('([^:/])://(.*)$',r'\1',mypath)
  241. self.ct_data = []
  242. self.ct_idx = []
  243. self.ct_z = []
  244. self.ct_pixel_size = [0,0,0]
  245. self.ct_center = [0,0,0]
  246. self.ct_center[2]=1e30
  247. self.ct_orientation=[0,0,0,0,0,0]
  248. for f in onlyfiles:
  249. print '{}:'.format(f)
  250. g,ok=self.getfile(origin,f)
  251. if not(ok):
  252. return
  253. self.readCTFile(g)
  254. nz=len(self.ct_idx)
  255. #not average, again
  256. #ct_center[2]/=nz
  257. sh=self.ct_data[-1].shape
  258. sh_list=list(sh)
  259. sh_list.append(nz)
  260. data_array=np.zeros(sh_list)
  261. for k in range(0,nz):
  262. kp=int(np.round((self.ct_z[k]-self.ct_center[2])/self.ct_pixel_size[2]))
  263. data_array[:,:,kp]=np.transpose(self.ct_data[k])
  264. return data_array,self.ct_center,self.ct_pixel_size,self.ct_orientation