parseDicom.py 9.8 KB

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