loadDicom.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. import slicer
  2. import os
  3. import subprocess
  4. import re
  5. import slicerNetwork
  6. import ctk,qt
  7. import json
  8. dicomModify=os.getenv("HOME")
  9. if not dicomModify==None:
  10. dicomModify+="/software/install/"
  11. dicomModify+="dicomModify/bin/dicomModify"
  12. class loadDicom(slicer.ScriptedLoadableModule.ScriptedLoadableModule):
  13. def __init__(self,parent):
  14. slicer.ScriptedLoadableModule.ScriptedLoadableModule.__init__(self, parent)
  15. self.className="loadDicom"
  16. self.parent.title="loadDicom"
  17. self.parent.categories = ["LabKey"]
  18. self.parent.dependencies = []
  19. self.parent.contributors = ["Andrej Studen (UL/FMF)"] # replace with "Firstname Lastname (Organization)"
  20. self.parent.helpText = """
  21. utilities for parsing dicom entries
  22. """
  23. self.parent.acknowledgementText = """
  24. Developed within the medical physics research programme of the Slovenian research agency.
  25. """ # replace with organization, grant and thanks.
  26. class loadDicomWidget(slicer.ScriptedLoadableModule.ScriptedLoadableModuleWidget):
  27. """Uses ScriptedLoadableModuleWidget base class, available at:
  28. https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
  29. """
  30. def setup(self):
  31. slicer.ScriptedLoadableModule.ScriptedLoadableModuleWidget.setup(self)
  32. self.logic=loadDicomLogic(self)
  33. self.network=slicerNetwork.labkeyURIHandler()
  34. connectionCollapsibleButton = ctk.ctkCollapsibleButton()
  35. connectionCollapsibleButton.text = "Connection"
  36. self.layout.addWidget(connectionCollapsibleButton)
  37. connectionFormLayout = qt.QFormLayout(connectionCollapsibleButton)
  38. self.loadConfigButton=qt.QPushButton("Load configuration")
  39. self.loadConfigButton.toolTip="Load configuration"
  40. self.loadConfigButton.connect('clicked(bool)',self.onLoadConfigButtonClicked)
  41. connectionFormLayout.addRow("Connection:",self.loadConfigButton)
  42. self.DICOMDirectory=qt.QLineEdit("Test/Temp/%40files/TEST/MLEM")
  43. connectionFormLayout.addRow("LabKey directory:",self.DICOMDirectory)
  44. loadDICOMButton=qt.QPushButton("Load")
  45. loadDICOMButton.toolTip="Load DICOM"
  46. loadDICOMButton.clicked.connect(self.onLoadDICOMButtonClicked)
  47. connectionFormLayout.addRow("DICOM:",loadDICOMButton)
  48. self.DICOMFilter=qt.QLineEdit('{"seriesNumber":"SeriesLabel"}')
  49. connectionFormLayout.addRow("Filter(JSON):",self.DICOMFilter)
  50. loadDICOMFilterButton=qt.QPushButton("Load with filter")
  51. loadDICOMFilterButton.toolTip="Load DICOM with filter"
  52. loadDICOMFilterButton.clicked.connect(self.onLoadDICOMFilterButtonClicked)
  53. connectionFormLayout.addRow("DICOM:",loadDICOMFilterButton)
  54. loadDICOMSegmentationFilterButton=qt.QPushButton("Load segmentation with filter")
  55. loadDICOMSegmentationFilterButton.toolTip="Load DICOM (RT contour) with filter"
  56. loadDICOMSegmentationFilterButton.clicked.connect(self.onLoadDICOMSegmentationFilterButtonClicked)
  57. connectionFormLayout.addRow("DICOM:",loadDICOMSegmentationFilterButton)
  58. def onLoadConfigButtonClicked(self):
  59. filename=qt.QFileDialog.getOpenFileName(None,'Open configuration file (JSON)',
  60. os.path.join(os.path.expanduser('~'),'.labkey'), '*.json')
  61. self.network.parseConfig(filename)
  62. self.network.initRemote()
  63. self.loadConfigButton.setText(os.path.basename(filename))
  64. def onLoadDICOMFilterButtonClicked(self):
  65. filter=json.loads(self.DICOMFilter.text)
  66. #print("Filter is {}".format(filter))
  67. self.logic.loadVolumes(self.network,self.DICOMDirectory.text,filter)
  68. def onLoadDICOMSegmentationFilterButtonClicked(self):
  69. filter=json.loads(self.DICOMFilter.text)
  70. #print("Filter is {}".format(filter))
  71. self.logic.loadSegmentations(self.network,self.DICOMDirectory.text,filter)
  72. def onLoadDICOMButtonClicked(self):
  73. self.logic.load(self.network,self.DICOMDirectory.text)
  74. class loadDicomLogic(slicer.ScriptedLoadableModule.ScriptedLoadableModuleLogic):
  75. def __init__(self,parent):
  76. slicer.ScriptedLoadableModule.ScriptedLoadableModuleLogic.__init__(self, parent)
  77. self.tag={
  78. 'studyDate': {'tag':"0008,0020",'VR':'DA'},
  79. 'studyTime': {'tag':"0008,0030",'VR':'TM'},
  80. 'seriesTime': {'tag':"0008,0031",'VR':'TM'},
  81. 'modality': {'tag':"0008,0060",'VR':'CS'},
  82. 'presentationIntentType': {'tag':"0008,0068",'VR':'CS'},
  83. 'manufacturer': {'tag':"0008,0070",'VR':'LO'},
  84. 'institutionName': {'tag':"0008,0080",'VR':'LO'},
  85. 'studyDescription': {'tag':"0008,1030",'VR':'LO'},
  86. 'seriesDescription': {'tag':"0008,103e",'VR':'LO'},
  87. 'manufacturerModelName': {'tag':"0008,1090",'VR':'LO'},
  88. 'patientName': {'tag':"0010,0010",'VR':'PN'},
  89. 'patientId': {'tag':"0010,0020",'VR':'LO'},
  90. 'patientBirthDate': {'tag':"0010,0030",'VR':'DA'},
  91. 'patientSex': {'tag':"0010,0040",'VR':'CS'},
  92. 'patientAge': {'tag':"0010,1010",'VR':'AS'},
  93. 'patientComments': {'tag':"0010,4000",'VR':'LT'},
  94. 'sequenceName': {'tag':"0018,0024",'VR':'SH'},
  95. 'kVP': {'tag':"0018,0060",'VR':'DS'},
  96. 'percentPhaseFieldOfView': {'tag':"0018,0094",'VR':'DS'},
  97. 'xRayTubeCurrent': {'tag':"0018,1151",'VR':'IS'},
  98. 'exposure': {'tag':"0018,1152",'VR':'IS'},
  99. 'imagerPixelSpacing': {'tag':"0018,1164",'VR':'DS'},
  100. 'bodyPartThickness': {'tag':"0018,11a0",'VR':'DS'},
  101. 'compressionForce': {'tag':"0018,11a2",'VR':'DS'},
  102. 'viewPosition': {'tag':"0018,5101",'VR':'CS'},
  103. 'fieldOfViewHorizontalFlip': {'tag':"0018,7034",'VR':'CS'},
  104. 'studyInstanceUid': {'tag':"0020,000d",'VR':'UI'},
  105. 'seriesInstanceUid': {'tag':"0020,000e",'VR':'UI'},
  106. 'studyId': {'tag':"0020,0010",'VR':'SH'},
  107. 'seriesNumber': {'tag':"0020,0011",'VR':'IS'},
  108. 'instanceNumber': {'tag':"0020,0013",'VR':'IS'},
  109. 'frameOfReferenceInstanceUid': {'tag':"0020,0052",'seqTag':"3006,0010",'VR':'UI'},
  110. 'imageLaterality': {'tag':"0020,0062",'VR':'CS'},
  111. 'imagesInAcquisition': {'tag':"0020,1002",'VR':'IS'},
  112. 'photometricInterpretation': {'tag':"0028,0004",'VR':'CS'},
  113. 'reconstructionMethod': {'tag':"0054,1103",'VR':'LO'}
  114. }
  115. self.tagPyDicom={
  116. 'studyDate': 0x00080020,
  117. 'studyTime': 0x00080030,
  118. 'modality': 0x00080060,
  119. 'presentationIntentType': 0x00080068,
  120. 'manufacturer': 0x00080070,
  121. 'studyDescription': 0x00081030,
  122. 'seriesDescription': 0x0008103e,
  123. 'patientName': 0x00100010,
  124. 'patientId': 0x00100020,
  125. 'patientBirthDate': 0x00100030,
  126. 'patientSex': 0x00100040,
  127. 'patientComments': 0x00104000,
  128. 'sequenceName': 0x00180024,
  129. 'kVP': 0x00180060,
  130. 'percentPhaseFieldOfView': 0x00180094,
  131. 'xRayTubeCurrent': 0x00181151,
  132. 'exposure': 0x00181152,
  133. 'imagerPixelSpacing': 0x00181164,
  134. 'bodyPartThickness': 0x001811a0,
  135. 'compressionForce': 0x001811a2,
  136. 'viewPosition': 0x00185101,
  137. 'studyInstanceUid': 0x0020000d,
  138. 'seriesInstanceUid': 0x0020000e,
  139. 'studyId': 0x00200010,
  140. 'seriesNumber': 0x00200011,
  141. 'instanceNumber': 0x00200013,
  142. 'frameOfReferenceInstanceUid': 0x00200052
  143. }
  144. #new_dict_items={
  145. # 0x001811a0: ('DS','BodyPartThickness','Body Part Thickness')
  146. #}
  147. #dicom.datadict.add_dict_entries(new_dict_items)
  148. self.local=False
  149. def setLocal(self,basePath):
  150. self.local=True
  151. self.basePath=basePath
  152. def getHex(self,key):
  153. #convert string to hex key;
  154. fv=key.split(",")
  155. return int(fv[0],16)*0x10000+int(fv[1],16)
  156. def load(self,sNet,dir,doRemove=True):
  157. #load directory using DICOMLib tools
  158. print("Loading dir {}").format(dir)
  159. dicomFiles=self.listdir(sNet,dir)
  160. filelist=[]
  161. for f in dicomFiles:
  162. localPath=self.getfile(sNet,f)
  163. f0=localPath
  164. f1=f0+"1"
  165. if not dicomModify==None:
  166. try:
  167. subprocess.call(dicomModify+" "+f0+" "+f1+" && mv "+f1+" "+f0+";", shell=True)
  168. except OSError:
  169. print("dicomModify failed")
  170. filelist.append(localPath)
  171. try:
  172. loadables=self.volumePlugin.examineForImport([filelist])
  173. except AttributeError:
  174. self.volumePlugin=slicer.modules.dicomPlugins['DICOMScalarVolumePlugin']()
  175. loadables=self.volumePlugin.examineForImport([filelist])
  176. for loadable in loadables:
  177. #check if it makes sense to load a particular loadable
  178. if loadable.name.find('imageOrientationPatient')>-1:
  179. continue
  180. filter={}
  181. filter['seriesNumber']=None
  182. metadata={}
  183. if not self.applyFilter(loadable,filter,metadata):
  184. continue
  185. volumeNode=self.volumePlugin.load(loadable)
  186. if volumeNode != None:
  187. vName='Series'+metadata['seriesNumber']
  188. volumeNode.SetName(vName)
  189. try:
  190. loadableRTs=self.RTPlugin.examineForImport([filelist])
  191. except:
  192. self.RTPlugin=plugin=slicer.modules.dicomPlugins['DicomRtImportExportPlugin']()
  193. loadableRTs=self.RTPlugin.examineForImport([filelist])
  194. for loadable in loadableRTs:
  195. segmentationNode=self.RTPlugin.load(loadable)
  196. if not doRemove:
  197. return
  198. for f in filelist:
  199. os.remove(f)
  200. def applyFilter(self,loadable,filter,nodeMetadata):
  201. #apply filter to loadable.file[0]. Return true if file matches prescribed filter and
  202. #false otherwise
  203. #filter is a directory with keys equal to pre-specified values listed above
  204. #if value associated to key equals None, that value gets set in nodeMetadata
  205. #if value is set, a match is attempted and result reported in return value
  206. #all filters should match for true output
  207. return applyFilterFile(self,loadable.files[0],filter,nodeMetadata)
  208. def applyFilterFile(self,file,filter,nodeMetadata,shell=False):
  209. #apply filter to file. Return true if file matches prescribed filter and
  210. #false otherwise
  211. #filter is a directory with keys equal to pre-specified values listed above
  212. #if value associated to key equals None, that value gets set in nodeMetadata
  213. #if value is set, a match is attempted and result reported in return value
  214. #all filters should match for true output
  215. filterOK=True
  216. for key in filter:
  217. try:
  218. fileValue=dicomValue(file,self.tag[key]['tag'],self.tag[key]['seqTag'],shell=shell)
  219. except KeyError:
  220. fileValue=dicomValue(file,self.tag[key]['tag'],shell=shell)
  221. if filter[key]=="SeriesLabel":
  222. nodeMetadata['seriesLabel']=fileValue
  223. continue
  224. if not filter[key]==None:
  225. if not fileValue==filter[key]:
  226. print("File {} failed for tag {}: {}/{}").format(
  227. file,key,fileValue,filter[key])
  228. filterOK=False
  229. break
  230. nodeMetadata[key]=fileValue
  231. return filterOK
  232. def listdir(self,sNet,dir):
  233. #list remote directory
  234. if self.local:
  235. dir1=os.path.join(self.basePath,dir)
  236. dirs=os.listdir(dir1)
  237. return [os.path.join(dir1,f) for f in dirs]
  238. return sNet.listRelativeDir(dir)
  239. def getfile(self,sNet,file):
  240. #get remote file
  241. if self.local:
  242. return file
  243. return sNet.DownloadFileToCache(file)
  244. def removeLocal(self,localFile):
  245. if self.local:
  246. return
  247. os.remove(localFile)
  248. def loadVolumes(self,sNet,dir,filter,doRemove=True):
  249. #returns all series from the directory, each as a separate node in a node list
  250. #filter is a dictionary of speciifed dicom values, if filter(key)=None, that values
  251. #get set, if it isn't, the file gets checked for a match
  252. print("Loading dir {}").format(dir)
  253. dicomFiles=self.listdir(sNet,dir)
  254. #filelist=[os.path.join(dir,f) for f in os.listdir(dir)]
  255. filelist=[]
  256. for f in dicomFiles:
  257. localPath=self.getfile(sNet,f)
  258. f0=localPath
  259. f1=f0+"1"
  260. if not dicomModify==None:
  261. try:
  262. subprocess.call(dicomModify+" "+f0+" "+f1+" && mv "+f1+" "+f0+";", shell=False)
  263. except OSError:
  264. print("dicomModify failed")
  265. filelist.append(localPath)
  266. try:
  267. loadables=self.volumePlugin.examineForImport([filelist])
  268. except AttributeError:
  269. self.volumePlugin=slicer.modules.dicomPlugins['DICOMScalarVolumePlugin']()
  270. loadables=self.volumePlugin.examineForImport([filelist])
  271. volumeNodes=[]
  272. print("Number of loadables:{}").format(len(loadables))
  273. for loadable in loadables:
  274. #TODO check if it makes sense to load a particular loadable
  275. print "Loading {} number of files: {}".format(loadable.name,len(loadable.files))
  276. for f in loadable.files:
  277. print "\t {}".format(f)
  278. #perform checks
  279. nodeMetadata={}
  280. filterOK=self.applyFilter(loadable,filter,nodeMetadata)
  281. if not filterOK:
  282. #skip this loadable
  283. continue
  284. volumeNode=self.volumePlugin.load(loadable,"DCMTK")
  285. if volumeNode != None:
  286. vName='Series'+nodeMetadata['seriesLabel']
  287. volumeNode.SetName(vName)
  288. volume={'node':volumeNode,'metadata':nodeMetadata}
  289. volumeNodes.append(volume)
  290. if self.local:
  291. return volumeNodes
  292. if doRemove:
  293. for f in filelist:
  294. os.remove(f)
  295. return volumeNodes
  296. def loadSegmentations(self,net,dir,filter,doRemove=True):
  297. print("Loading dir {}").format(dir)
  298. dicomFiles=self.listdir(net,dir)
  299. filelist=[self.getfile(net,f) for f in dicomFiles]
  300. segmentationNodes=[]
  301. try:
  302. loadableRTs=self.RTPlugin.examineForImport([filelist])
  303. except:
  304. self.RTPlugin=plugin=slicer.modules.dicomPlugins['DicomRtImportExportPlugin']()
  305. loadableRTs=self.RTPlugin.examineForImport([filelist])
  306. for loadable in loadableRTs:
  307. nodeMetadata={}
  308. filterOK=self.applyFilter(loadable,filter,nodeMetadata)
  309. if not filterOK:
  310. continue
  311. success=self.RTPlugin.load(loadable)
  312. if not success:
  313. print("Could not load RT structure set")
  314. return
  315. segNodes=slicer.util.getNodesByClass("vtkMRMLSegmentationNode")
  316. segmentationNode=segNodes[0]
  317. #assume we loaded the first node in list
  318. if segmentationNode != None:
  319. sName='Segmentation'+nodeMetadata['seriesLabel']
  320. segmentationNode.SetName(sName)
  321. segmentation={'node':segmentationNode,'metadata':nodeMetadata}
  322. segmentationNodes.append(segmentation)
  323. if self.local or not doRemove:
  324. return segmentationNodes
  325. for f in filelist:
  326. os.remove(f)
  327. return segmentationNodes
  328. def isDicom(file):
  329. #check if file is a dicom file
  330. try:
  331. f=open(file,'rb')
  332. except IOError:
  333. return False
  334. f.read(128)
  335. dt=f.read(4)
  336. f.close()
  337. return dt=='DICM'
  338. def dicomValue(file,tag,seqTag=None,shell=False):
  339. #query dicom value of file using dcmdump (DCMTK routine)
  340. dcmdump=os.path.join(os.environ['SLICER_HOME'],"bin","dcmdump")
  341. try:
  342. out=subprocess.check_output([dcmdump,'+p','+P',tag,file],shell=shell)
  343. except subprocess.CalledProcessError as e:
  344. return None
  345. debug=False
  346. if debug:
  347. print("Tag {} Line '{}'").format(tag,out)
  348. if len(out)==0:
  349. return out
  350. #parse multi-match outputs which appear as several lines
  351. lst=out.split('\n')
  352. return getTagValue(lst,tag,seqTag)
  353. def getTagValue(lst,tag,seqTag=None):
  354. #report tag value from a list lst of lines reported by dcmdump
  355. debug=False
  356. #parse output
  357. longTag="^\({}\)".format(tag)
  358. #combine sequence and actual tags to long tags
  359. if not seqTag==None:
  360. if debug:
  361. print("Tag:{} seqTag:{}").format(tag,seqTag)
  362. longTag="^\({}\).\({}\)".format(seqTag,tag)
  363. #pick the values
  364. pattern=r'^.*\[(.*)\].*$'
  365. #extract tag values
  366. rpl=[re.sub(pattern,r'\1',f) for f in lst]
  367. #logical whether the line can be matched to typical dcmdump output
  368. mtchPattern=[re.match(pattern,f) for f in lst]
  369. #find matching tags
  370. mtchTag=[re.match(longTag,f) for f in lst]
  371. #weed out non-matching lines and lines not matching longTag
  372. mtch=[None if x==None or y==None else x \
  373. for x,y in zip(mtchTag,mtchPattern)]
  374. #set values
  375. out=[x for y,x in zip(mtch,rpl) if not y==None]
  376. if len(out)==0:
  377. return ''
  378. #return first match
  379. out=out[0]
  380. if debug:
  381. print("Tag {} Parsed value {}").format(tag,out)
  382. #split output to lists if values are DICOM lists
  383. if out.find('\\')>-1:
  384. out=out.split('\\')
  385. return out
  386. def clearNodes():
  387. nodes=[]
  388. nodes.extend(slicer.util.getNodesByClass("vtkMRMLScalarVolumeNode"))
  389. nodes.extend(slicer.util.getNodesByClass("vtkMRMLScalarVolumeDisplayNode"))
  390. nodes.extend(slicer.util.getNodesByClass("vtkMRMLSegmentationNode"))
  391. nodes.extend(slicer.util.getNodesByClass("vtkMRMLSegmentationDisplayNode"))
  392. for node in nodes:
  393. slicer.mrmlScene.RemoveNode(node)