parseDicom.py 9.5 KB

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