parseDicom.py 9.5 KB

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