importDicom.py 8.7 KB

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