loadDicom.py 13 KB

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