importDicom.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. import dicom
  2. import vtkInterface as vi
  3. import os
  4. import vtk, qt, ctk, slicer
  5. from slicer.ScriptedLoadableModule import *
  6. import slicerNetwork
  7. import json
  8. import loadDicom
  9. import DICOMLib
  10. class importDicom(slicer.ScriptedLoadableModule.ScriptedLoadableModule):
  11. def __init__(self,parent):
  12. slicer.ScriptedLoadableModule.ScriptedLoadableModule.__init__(self, parent)
  13. self.className="loadPatient"
  14. self.parent.title="loadPatient"
  15. self.parent.categories = ["LabKey"]
  16. self.parent.dependencies = []
  17. self.parent.contributors = ["Andrej Studen (UL/FMF)"] # replace with "Firstname Lastname (Organization)"
  18. self.parent.helpText = """
  19. utilities for parsing dicom entries
  20. """
  21. self.parent.acknowledgementText = """
  22. Developed within the medical physics research programme of the Slovenian research agency.
  23. """ # replace with organization, grant and thanks.
  24. #equivalent of loadable + labkey interface
  25. class dicomSeries():
  26. def __init__(self):
  27. self.data = []
  28. self.idx = []
  29. self.z = []
  30. self.pixel_size = [0,0,0]
  31. self.lpsOrigin = [0,0,0]
  32. self.lpsOrigin[2]=1e30
  33. self.lpsOrientation=[0,0,0,0,0,0]
  34. def getfile(self,net,relativePath):
  35. return net.readFileToBuffer(relativePath)
  36. def addFile(self,f):
  37. try:
  38. self.files.append(f)
  39. except:
  40. self.files=[f]
  41. def setLabel(self,label):
  42. self.label=label
  43. def getLabel(self):
  44. try:
  45. return self.label
  46. except:
  47. return None
  48. def setMetadata(self,key,value):
  49. try:
  50. self.metadata[key]=value
  51. except:
  52. self.metadata={key:value}
  53. def getMetadata(self):
  54. try:
  55. return self.metadata
  56. except:
  57. return {}
  58. def load(self,net):
  59. for f in self.files:
  60. print '{}:'.format(f)
  61. fileBuffer=self.getfile(net,f)
  62. self.loadFile(fileBuffer)
  63. nz=len(self.idx)
  64. sh=self.data[-1].shape
  65. sh_list=list(sh)
  66. sh_list.append(nz)
  67. data_array=np.zeros(sh_list)
  68. for k in range(0,nz):
  69. kp=int(np.round((self.z[k]-self.center[2])/self.pixel_size[2]))
  70. data_array[:,:,kp]=np.transpose(self.data[k])
  71. try:
  72. nodeName='Series'+self.label
  73. except:
  74. print('Could not set series label')
  75. nodeName='UnknownSeries'
  76. newNode=slicer.vtkMRMLScalarVolumeNode()
  77. newNode.SetName(nodeName)
  78. ijkToRAS = vtk.vtkMatrix4x4()
  79. #think how to do this with image orientation
  80. rasOrientation=[-self.lpsOrientation[i] if (i%3 < 2) else self.lpsOrientation[i]
  81. for i in range(0,len(self.lpsOrientation))]
  82. rasOrigin=[-self.lpsOrigin[i] if (i%3<2) else self.lpsOrigin[i] for i in range(0,len(self.lpsOrigin))]
  83. for i in range(0,3):
  84. for j in range(0,3):
  85. ijkToRAS.SetElement(i,j,self.pixel_size[i]*rasOrientation[3*j+i])
  86. ijkToRAS.SetElement(i,3,rasOrigin[i])
  87. newNode.SetIJKToRASMatrix(ijkToRAS)
  88. v=vtk.vtkImageData()
  89. v.GetPointData().SetScalars(
  90. vtk.util.numpy_support.numpy_to_vtk(
  91. np.ravel(self.data,order='F'),deep=True, array_type=vtk.VTK_FLOAT))
  92. v.SetOrigin(0,0,0)
  93. v.SetSpacing(1,1,1)
  94. v.SetDimensions(self.data.shape)
  95. newNode.SetAndObserveImageData(v)
  96. slicer.mrmlScene.AddNode(newNode)
  97. volume={'node':newNode,'metadata':self.metadata}
  98. return volume
  99. def loadFile(self,fileBuffer):
  100. plan=dicom.read_file(fileBuffer)
  101. self.data.append(plan.pixel_array)
  102. self.idx.append(plan.InstanceNumber)
  103. self.z.append(plan.ImagePositionPatient[2])
  104. #pixelSize
  105. pixel_size=[plan.PixelSpacing[0],plan.PixelSpacing[1],
  106. plan.SliceThickness]
  107. for i in range(0,3):
  108. if self.pixel_size[i] == 0:
  109. self.pixel_size[i] = float(pixel_size[i])
  110. if abs(self.pixel_size[i]-pixel_size[i]) > 1e-3:
  111. print 'Pixel size mismatch {.2f}/{.2f}'.format(self.pixel_size[i],
  112. pixel_size[i])
  113. #origin
  114. for i in range(0,2):
  115. if self.lpsOrigin[i] == 0:
  116. self.lpsOrigin[i] = float(plan.ImagePositionPatient[i])
  117. if abs(self.lpsOrigin[i]-plan.ImagePositionPatient[i]) > 1e-3:
  118. print 'Image center mismatch {.2f}/{.2f}'.format(self.lpsOrigin[i],
  119. plan.ImagePositionPatient[i])
  120. #not average, but minimum (!) why??
  121. if plan.ImagePositionPatient[2]<self.lpsOrigin[2]:
  122. self.lpsOrigin[2]=plan.ImagePositionPatient[2]
  123. #orientation
  124. for i in range(0,6):
  125. if self.lpsOrientation[i] == 0:
  126. self.lpsOrientation[i] = float(plan.ImageOrientationPatient[i])
  127. if abs(self.lpsOrientation[i]-plan.ImageOrientationPatient[i]) > 1e-3:
  128. print 'Image orientation mismatch {0:.2f}/{1:.2f}'.format(self.lpsOrientation[i],
  129. plan.ImageOrientationPatient[i])
  130. return True
  131. class importDicomLogic(slicer.ScriptedLoadableModule.ScriptedLoadableModuleLogic):
  132. def __init__(self,parent):
  133. slicer.ScriptedLoadableModule.ScriptedLoadableModuleLogic.__init__(self, parent)
  134. self.tag={
  135. 'studyInstanceUid':0x0020000d,
  136. 'seriesInstanceUid':0x0020000e,
  137. 'patientId':0x00100020,
  138. 'patientName':0x00100010,
  139. 'sequenceName':0x00180024,
  140. 'seriesNumber':0x00200011,
  141. 'percentPhaseFieldOfView':0x00180094,
  142. 'modality': 0x00080060,
  143. 'patientSex': 0x00100040,
  144. 'patientBirthDate': 0x00100030,
  145. 'patientComments': 0x00104000,
  146. 'studyDescription': 0x00081030,
  147. 'studyDate': 0x00080020,
  148. 'studyId': 0x00200010,
  149. 'studyTime': 0x00080030,
  150. 'frameOfReferenceInstanceUid':0x00200052}
  151. def loadVolumes(self,net,directory,filter):
  152. #mimic examineForImport
  153. seriesList=self.examineForImport(net,directory,filter)
  154. print("Got {} series").format(len(seriesList))
  155. volumes=[]
  156. for s in seriesList:
  157. try:
  158. volumes.append(s.load(net))
  159. #often fails, e.g. JPEGLossles
  160. except:
  161. loadable=DICOMLib.DICOMLoadable()
  162. loadable.name='Series'+str(s.getLabel())
  163. print("Loading for {} number of files (pre-load) {}").format(loadable.name,len(s.files))
  164. loadable.files=[net.DownloadFileToCache(f) for f in s.files]
  165. print("Loading for {} number of files (pre-sort) {}").format(loadable.name,len(loadable.files))
  166. loadable.files,distances,loadable.warning=DICOMLib.DICOMUtils.getSortedImageFiles(loadable.files,1e-3)
  167. print("Loading for {} number of files {}").format(loadable.name,len(loadable.files))
  168. try:
  169. volumeNode=self.volumePlugin.load(loadable)
  170. except:
  171. self.volumePlugin=slicer.modules.dicomPlugins['DICOMScalarVolumePlugin']()
  172. volumeNode=self.volumePlugin.load(loadable)
  173. volume={'node':volumeNode,'metadata':s.getMetadata()}
  174. volumes.append(volume)
  175. return volumes
  176. def listdir(self,net,relativeDirectory):
  177. return net.listRelativeDir(relativeDirectory)
  178. def getfile(self,net,relativePath):
  179. return net.readFileToBuffer(relativePath)
  180. def examineForImport(self,net,directory,filter):
  181. #split by series
  182. files=self.listdir(net,directory)
  183. seriesList=[]
  184. seriesList.append(dicomSeries())
  185. series=seriesList[0]
  186. for f in files:
  187. fileBuffer=self.getfile(net,f)
  188. #validate
  189. try:
  190. plan = dicom.read_file(fileBuffer)
  191. except:
  192. print ("{}: Not a dicom file")
  193. continue
  194. #determine validity first
  195. fileValid=True
  196. seriesKey=None
  197. for key in filter:
  198. if filter[key]==None:
  199. continue
  200. if filter[key]=='SeriesLabel':
  201. seriesTag=self.tag[key]
  202. continue
  203. v=plan[self.tag[key]].value
  204. if not v==filter[key]:
  205. print('Filter mismatch {}{:x}: {}/{}').format(key,self.tag[key],v,filter[key])
  206. fileValid=False
  207. if not fileValid:
  208. continue
  209. #determine serieslabel second
  210. seriesLabel=plan[seriesTag].value
  211. if series.getLabel()==seriesLabel:
  212. series.addFile(f)
  213. continue
  214. #add new series
  215. if not series.getLabel()==None:
  216. seriesList.append(dicomSeries())
  217. series=seriesList[-1]
  218. #set series parameters
  219. series.addFile(f)
  220. series.setLabel(seriesLabel)
  221. for key in filter:
  222. if not filter[key]==None:
  223. continue
  224. v=plan[self.tag[key]].value
  225. series.setMetadata(key,v)
  226. return seriesList