loadDicom.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. import slicer
  2. import os
  3. import subprocess
  4. import re
  5. import dicom
  6. dicomModify=os.getenv("HOME")
  7. if not dicomModify==None:
  8. dicomModify+="/software/install/"
  9. dicomModify+="dicomModify/bin/dicomModify"
  10. class loadDicom(slicer.ScriptedLoadableModule.ScriptedLoadableModule):
  11. def __init__(self,parent):
  12. slicer.ScriptedLoadableModule.ScriptedLoadableModule.__init__(self, parent)
  13. self.className="loadDicom"
  14. self.parent.title="loadDicom"
  15. self.parent.categories = ["Examples"]
  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. class loadDicomWidget(slicer.ScriptedLoadableModule.ScriptedLoadableModuleWidget):
  25. """Uses ScriptedLoadableModuleWidget base class, available at:
  26. https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
  27. """
  28. def setup(self):
  29. slicer.ScriptedLoadableModule.ScriptedLoadableModuleWidget.setup(self)
  30. class loadDicomLogic(slicer.ScriptedLoadableModule.ScriptedLoadableModuleLogic):
  31. def __init__(self,parent):
  32. slicer.ScriptedLoadableModule.ScriptedLoadableModuleLogic.__init__(self, parent)
  33. self.tag={
  34. 'studyDate': {'tag':"0008,0020",'VR':'DA'},
  35. 'studyTime': {'tag':"0008,0030",'VR':'TM'},
  36. 'seriesTime': {'tag':"0008,0031",'VR':'TM'},
  37. 'modality': {'tag':"0008,0060",'VR':'CS'},
  38. 'presentationIntentType': {'tag':"0008,0068",'VR':'CS'},
  39. 'manufacturer': {'tag':"0008,0070",'VR':'LO'},
  40. 'studyDescription': {'tag':"0008,1030",'VR':'LO'},
  41. 'seriesDescription': {'tag':"0008,103e",'VR':'LO'},
  42. 'patientName': {'tag':"0010,0010",'VR':'PN'},
  43. 'patientId': {'tag':"0010,0020",'VR':'LO'},
  44. 'patientBirthDate': {'tag':"0010,0030",'VR':'DA'},
  45. 'patientSex': {'tag':"0010,0040",'VR':'CS'},
  46. 'patientAge': {'tag':"0010,1010",'VR':'AS'},
  47. 'patientComments': {'tag':"0010,4000",'VR':'LT'},
  48. 'sequenceName': {'tag':"0018,0024",'VR':'SH'},
  49. 'kVP': {'tag':"0018,0060",'VR':'DS'},
  50. 'percentPhaseFieldOfView': {'tag':"0018,0094",'VR':'DS'},
  51. 'xRayTubeCurrent': {'tag':"0018,1151",'VR':'IS'},
  52. 'exposure': {'tag':"0018,1152",'VR':'IS'},
  53. 'imagerPixelSpacing': {'tag':"0018,1164",'VR':'DS'},
  54. 'bodyPartThickness': {'tag':"0018,11a0",'VR':'DS'},
  55. 'compressionForce': {'tag':"0018,11a2",'VR':'DS'},
  56. 'viewPosition': {'tag':"0018,5101",'VR':'CS'},
  57. 'fieldOfViewHorizontalFlip': {'tag':"0018,7034",'VR':'CS'},
  58. 'studyInstanceUid': {'tag':"0020,000d",'VR':'UI'},
  59. 'seriesInstanceUid': {'tag':"0020,000e",'VR':'UI'},
  60. 'studyId': {'tag':"0020,0010",'VR':'SH'},
  61. 'seriesNumber': {'tag':"0020,0011",'VR':'IS'},
  62. 'instanceNumber': {'tag':"0020,0013",'VR':'IS'},
  63. 'frameOfReferenceInstanceUid': {'tag':"0020,0052",'VR':'UI'},
  64. 'imageLaterality': {'tag':"0020,0062",'VR':'CS'},
  65. 'imagesInAcquisition': {'tag':"0020,1002",'VR':'IS'},
  66. 'photometricInterpretation': {'tag':"0028,0004",'VR':'CS'}
  67. }
  68. self.tagPyDicom={
  69. 'studyDate': 0x00080020,
  70. 'studyTime': 0x00080030,
  71. 'modality': 0x00080060,
  72. 'presentationIntentType': 0x00080068,
  73. 'manufacturer': 0x00080070,
  74. 'studyDescription': 0x00081030,
  75. 'seriesDescription': 0x0008103e,
  76. 'patientName': 0x00100010,
  77. 'patientId': 0x00100020,
  78. 'patientBirthDate': 0x00100030,
  79. 'patientSex': 0x00100040,
  80. 'patientComments': 0x00104000,
  81. 'sequenceName': 0x00180024,
  82. 'kVP': 0x00180060,
  83. 'percentPhaseFieldOfView': 0x00180094,
  84. 'xRayTubeCurrent': 0x00181151,
  85. 'exposure': 0x00181152,
  86. 'imagerPixelSpacing': 0x00181164,
  87. 'bodyPartThickness': 0x001811a0,
  88. 'compressionForce': 0x001811a2,
  89. 'viewPosition': 0x00185101,
  90. 'studyInstanceUid': 0x0020000d,
  91. 'seriesInstanceUid': 0x0020000e,
  92. 'studyId': 0x00200010,
  93. 'seriesNumber': 0x00200011,
  94. 'instanceNumber': 0x00200013,
  95. 'frameOfReferenceInstanceUid': 0x00200052
  96. }
  97. #new_dict_items={
  98. # 0x001811a0: ('DS','BodyPartThickness','Body Part Thickness')
  99. #}
  100. #dicom.datadict.add_dict_entries(new_dict_items)
  101. def getHex(self,key):
  102. #convert string to hex key;
  103. fv=key.split(",")
  104. return int(fv[0],16)*0x10000+int(fv[1],16)
  105. def load(self,sNet,dir,doRemove=True):
  106. print("Loading dir {}").format(dir)
  107. dicomFiles=sNet.listRelativeDir(dir)
  108. #filelist=[os.path.join(dir,f) for f in os.listdir(dir)]
  109. filelist=[]
  110. for f in dicomFiles:
  111. localPath=sNet.DownloadFileToCache(f)
  112. f0=localPath
  113. f1=f0+"1"
  114. if not dicomModify==None:
  115. subprocess.call(dicomModify+" "+f0+" "+f1+" && mv "+f1+" "+f0+";", shell=True)
  116. filelist.append(localPath)
  117. try:
  118. loadables=self.volumePlugin.examineForImport([filelist])
  119. except AttributeError:
  120. self.volumePlugin=slicer.modules.dicomPlugins['DICOMScalarVolumePlugin']()
  121. loadables=self.volumePlugin.examineForImport([filelist])
  122. for loadable in loadables:
  123. #TODO check if it makes sense to load a particular loadable
  124. fileBuffer = open(loadable.files[0])
  125. plan=dicom.read_file(fileBuffer)
  126. if loadable.name.find('imageOrientationPatient')>-1:
  127. continue
  128. volumeNode=self.volumePlugin.load(loadable)
  129. if volumeNode != None:
  130. vName='Series'+plan[0x00200011].value
  131. volumeNode.SetName(vName)
  132. try:
  133. loadableRTs=self.RTPlugin.examineForImport([filelist])
  134. except:
  135. self.RTPlugin=plugin=slicer.modules.dicomPlugins['DicomRtImportExportPlugin']()
  136. loadableRTs=self.RTPlugin.examineForImport([filelist])
  137. for loadable in loadableRTs:
  138. segmentationNode=self.RTPlugin.load(loadable)
  139. #if segmentationNode!= None:
  140. # segmentationNode.SetName('SegmentationBR')
  141. if not doRemove:
  142. return
  143. for f in filelist:
  144. os.remove(f)
  145. def applyFilter(self,loadable,filter,nodeMetadata):
  146. filterOK=True
  147. fileBuffer = open(loadable.files[0])
  148. try:
  149. plan = dicom.read_file(fileBuffer)
  150. except:
  151. return False
  152. for key in filter:
  153. #try:
  154. # fileValue=plan[self.tag[key]].value
  155. #except KeyError:
  156. # fileValue=None
  157. fileValue=dicomValue(loadable.files[0],self.tag[key]['tag'])
  158. if filter[key]=="SeriesLabel":
  159. nodeMetadata['seriesLabel']=fileValue
  160. continue
  161. if not filter[key]==None:
  162. if not fileValue==filter[key]:
  163. print("File {} failed for tag {}: {}/{}").format(
  164. loadable.files[0],key,fileValue,filter[key])
  165. filterOK=False
  166. break
  167. nodeMetadata[key]=fileValue
  168. return filterOK
  169. def loadVolumes(self,sNet,dir,filter,doRemove=True):
  170. #returns all series from the directory, each as a separate node in a node list
  171. #filter is a dictionary of speciifed dicom values, if filter(key)=None, that values
  172. #get set, if it isn't, the file gets checked for a match
  173. print("Loading dir {}").format(dir)
  174. dicomFiles=sNet.listRelativeDir(dir)
  175. #filelist=[os.path.join(dir,f) for f in os.listdir(dir)]
  176. filelist=[]
  177. for f in dicomFiles:
  178. localPath=sNet.DownloadFileToCache(f)
  179. f0=localPath
  180. f1=f0+"1"
  181. if not dicomModify==None:
  182. subprocess.call(dicomModify+" "+f0+" "+f1+" && mv "+f1+" "+f0+";", shell=True)
  183. filelist.append(localPath)
  184. try:
  185. loadables=self.volumePlugin.examineForImport([filelist])
  186. except AttributeError:
  187. self.volumePlugin=slicer.modules.dicomPlugins['DICOMScalarVolumePlugin']()
  188. loadables=self.volumePlugin.examineForImport([filelist])
  189. volumeNodes=[]
  190. print("Number of loadables:{}").format(len(loadables))
  191. for loadable in loadables:
  192. #TODO check if it makes sense to load a particular loadable
  193. print "Loading {} number of files: {}".format(loadable.name,len(loadable.files))
  194. for f in loadable.files:
  195. print "\t {}".format(f)
  196. #perform checks
  197. nodeMetadata={}
  198. filterOK=self.applyFilter(loadable,filter,nodeMetadata)
  199. if not filterOK:
  200. #skip this loadable
  201. continue
  202. volumeNode=self.volumePlugin.load(loadable,"DCMTK")
  203. if volumeNode != None:
  204. vName='Series'+nodeMetadata['seriesLabel']
  205. volumeNode.SetName(vName)
  206. volume={'node':volumeNode,'metadata':nodeMetadata}
  207. volumeNodes.append(volume)
  208. if doRemove:
  209. for f in filelist:
  210. os.remove(f)
  211. return volumeNodes
  212. def loadSegmentations(self,net,dir,filter,doRemove=True):
  213. print("Loading dir {}").format(dir)
  214. dicomFiles=net.listRelativeDir(dir)
  215. filelist=[net.DownloadFileToCache(f) for f in dicomFiles]
  216. segmentationNodes=[]
  217. try:
  218. loadableRTs=self.RTPlugin.examineForImport([filelist])
  219. except:
  220. self.RTPlugin=plugin=slicer.modules.dicomPlugins['DicomRtImportExportPlugin']()
  221. loadableRTs=self.RTPlugin.examineForImport([filelist])
  222. for loadable in loadableRTs:
  223. nodeMetadata={}
  224. filterOK=self.applyFilter(loadable,filter,nodeMetadata)
  225. if not filterOK:
  226. continue
  227. success=self.RTPlugin.load(loadable)
  228. if not success:
  229. print("Could not load RT structure set")
  230. return
  231. segNodes=slicer.util.getNodesByClass("vtkMRMLSegmentationNode")
  232. segmentationNode=segNodes[0]
  233. #assume we loaded the first node in list
  234. if segmentationNode != None:
  235. sName='Segmentation'+nodeMetadata['seriesLabel']
  236. segmentationNode.SetName(sName)
  237. segmentation={'node':segmentationNode,'metadata':nodeMetadata}
  238. segmentationNodes.append(segmentation)
  239. if not doRemove:
  240. return segmentationNodes
  241. for f in filelist:
  242. os.remove(f)
  243. return segmentationNodes
  244. def dicomValue(file,tag):
  245. dcmdump=os.path.join(os.environ['SLICER_HOME'],"bin")
  246. dcmdump=os.path.join(dcmdump,"dcmdump")
  247. try:
  248. out=subprocess.check_output([dcmdump,'+P',tag,file])
  249. out=re.sub(r'^.*\[(.*)\].*\n$',r'\1',out)
  250. #separate out series
  251. if out.find('\\')>-1:
  252. out=out.split('\\')
  253. return out
  254. except:
  255. return None
  256. def clearNodes():
  257. nodes=[]
  258. nodes.extend(slicer.util.getNodesByClass("vtkMRMLScalarVolumeNode"))
  259. nodes.extend(slicer.util.getNodesByClass("vtkMRMLScalarVolumeDisplayNode"))
  260. nodes.extend(slicer.util.getNodesByClass("vtkMRMLSegmentationNode"))
  261. nodes.extend(slicer.util.getNodesByClass("vtkMRMLSegmentationDisplayNode"))
  262. for node in nodes:
  263. slicer.mrmlScene.RemoveNode(node)