parseDicom.py 11 KB

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