loadDicom.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  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. 'sopInstanceUid' : {'tag':"0008,0018",'VR':'UI'},
  79. 'studyDate': {'tag':"0008,0020",'VR':'DA'},
  80. 'studyTime': {'tag':"0008,0030",'VR':'TM'},
  81. 'seriesTime': {'tag':"0008,0031",'VR':'TM'},
  82. 'modality': {'tag':"0008,0060",'VR':'CS'},
  83. 'presentationIntentType': {'tag':"0008,0068",'VR':'CS'},
  84. 'manufacturer': {'tag':"0008,0070",'VR':'LO'},
  85. 'institutionName': {'tag':"0008,0080",'VR':'LO'},
  86. 'studyDescription': {'tag':"0008,1030",'VR':'LO'},
  87. 'seriesDescription': {'tag':"0008,103e",'VR':'LO'},
  88. 'manufacturerModelName': {'tag':"0008,1090",'VR':'LO'},
  89. 'patientName': {'tag':"0010,0010",'VR':'PN'},
  90. 'patientId': {'tag':"0010,0020",'VR':'LO'},
  91. 'patientBirthDate': {'tag':"0010,0030",'VR':'DA'},
  92. 'patientSex': {'tag':"0010,0040",'VR':'CS'},
  93. 'patientAge': {'tag':"0010,1010",'VR':'AS'},
  94. 'patientComments': {'tag':"0010,4000",'VR':'LT'},
  95. 'sequenceName': {'tag':"0018,0024",'VR':'SH'},
  96. 'kVP': {'tag':"0018,0060",'VR':'DS'},
  97. 'percentPhaseFieldOfView': {'tag':"0018,0094",'VR':'DS'},
  98. 'xRayTubeCurrent': {'tag':"0018,1151",'VR':'IS'},
  99. 'exposure': {'tag':"0018,1152",'VR':'IS'},
  100. 'imagerPixelSpacing': {'tag':"0018,1164",'VR':'DS'},
  101. 'bodyPartThickness': {'tag':"0018,11a0",'VR':'DS'},
  102. 'compressionForce': {'tag':"0018,11a2",'VR':'DS'},
  103. 'viewPosition': {'tag':"0018,5101",'VR':'CS'},
  104. 'fieldOfViewHorizontalFlip': {'tag':"0018,7034",'VR':'CS'},
  105. 'studyInstanceUid': {'tag':"0020,000d",'VR':'UI'},
  106. 'seriesInstanceUid': {'tag':"0020,000e",'VR':'UI'},
  107. 'studyId': {'tag':"0020,0010",'VR':'SH'},
  108. 'seriesNumber': {'tag':"0020,0011",'VR':'IS'},
  109. 'instanceNumber': {'tag':"0020,0013",'VR':'IS'},
  110. 'frameOfReferenceInstanceUid': {'tag':"0020,0052",'seqTag':"3006,0010",'VR':'UI'},
  111. 'imageLaterality': {'tag':"0020,0062",'VR':'CS'},
  112. 'imagesInAcquisition': {'tag':"0020,1002",'VR':'IS'},
  113. 'photometricInterpretation': {'tag':"0028,0004",'VR':'CS'},
  114. 'reconstructionMethod': {'tag':"0054,1103",'VR':'LO'}
  115. }
  116. self.tagPyDicom={
  117. 'studyDate': 0x00080020,
  118. 'studyTime': 0x00080030,
  119. 'modality': 0x00080060,
  120. 'presentationIntentType': 0x00080068,
  121. 'manufacturer': 0x00080070,
  122. 'studyDescription': 0x00081030,
  123. 'seriesDescription': 0x0008103e,
  124. 'patientName': 0x00100010,
  125. 'patientId': 0x00100020,
  126. 'patientBirthDate': 0x00100030,
  127. 'patientSex': 0x00100040,
  128. 'patientComments': 0x00104000,
  129. 'sequenceName': 0x00180024,
  130. 'kVP': 0x00180060,
  131. 'percentPhaseFieldOfView': 0x00180094,
  132. 'xRayTubeCurrent': 0x00181151,
  133. 'exposure': 0x00181152,
  134. 'imagerPixelSpacing': 0x00181164,
  135. 'bodyPartThickness': 0x001811a0,
  136. 'compressionForce': 0x001811a2,
  137. 'viewPosition': 0x00185101,
  138. 'studyInstanceUid': 0x0020000d,
  139. 'seriesInstanceUid': 0x0020000e,
  140. 'studyId': 0x00200010,
  141. 'seriesNumber': 0x00200011,
  142. 'instanceNumber': 0x00200013,
  143. 'frameOfReferenceInstanceUid': 0x00200052
  144. }
  145. #new_dict_items={
  146. # 0x001811a0: ('DS','BodyPartThickness','Body Part Thickness')
  147. #}
  148. #dicom.datadict.add_dict_entries(new_dict_items)
  149. self.local=False
  150. self.useDicomModify=False
  151. def enableDicomModify(self):
  152. self.useDicomModify=True
  153. def setLocal(self,basePath):
  154. self.local=True
  155. self.basePath=basePath
  156. def getHex(self,key):
  157. #convert string to hex key;
  158. fv=key.split(",")
  159. return int(fv[0],16)*0x10000+int(fv[1],16)
  160. def load(self,sNet,dir,doRemove=True):
  161. #load directory using DICOMLib tools
  162. print("Loading dir {}").format(dir)
  163. dicomFiles=self.listdir(sNet,dir)
  164. filelist=[]
  165. for f in dicomFiles:
  166. localPath=self.getfile(sNet,f)
  167. filelist.append(localPath)
  168. if not self.useDicomModify:
  169. continue
  170. if dicomModify==None:
  171. continue
  172. f0=localPath
  173. f1=f0+"1"
  174. try:
  175. subprocess.call(\
  176. dicomModify+" "+f0+" "+f1+" && mv "+f1+" "+f0+";",
  177. shell=True)
  178. except OSError:
  179. print("dicomModify failed")
  180. try:
  181. loadables=self.volumePlugin.examineForImport([filelist])
  182. except AttributeError:
  183. self.volumePlugin=slicer.modules.dicomPlugins['DICOMScalarVolumePlugin']()
  184. loadables=self.volumePlugin.examineForImport([filelist])
  185. for loadable in loadables:
  186. #check if it makes sense to load a particular loadable
  187. if loadable.name.find('imageOrientationPatient')>-1:
  188. continue
  189. filter={}
  190. filter['seriesNumber']=None
  191. metadata={}
  192. if not self.applyFilter(loadable,filter,metadata):
  193. continue
  194. volumeNode=self.volumePlugin.load(loadable)
  195. if volumeNode != None:
  196. vName='Series'+metadata['seriesNumber']
  197. volumeNode.SetName(vName)
  198. try:
  199. loadableRTs=self.RTPlugin.examineForImport([filelist])
  200. except:
  201. self.RTPlugin=plugin=slicer.modules.dicomPlugins['DicomRtImportExportPlugin']()
  202. loadableRTs=self.RTPlugin.examineForImport([filelist])
  203. for loadable in loadableRTs:
  204. segmentationNode=self.RTPlugin.load(loadable)
  205. if not doRemove:
  206. return
  207. for f in filelist:
  208. self.removeLocal(f)
  209. def applyFilter(self,loadable,filter,nodeMetadata):
  210. #apply filter to loadable.file[0]. Return true if file matches prescribed filter and
  211. #false otherwise
  212. #filter is a directory with keys equal to pre-specified values listed above
  213. #if value associated to key equals None, that value gets set in nodeMetadata
  214. #if value is set, a match is attempted and result reported in return value
  215. #all filters should match for true output
  216. return self.applyFilterFile(loadable.files[0],filter,nodeMetadata)
  217. def applyFilterFile(self,file,filter,nodeMetadata,shell=False):
  218. #apply filter to file. Return true if file matches prescribed filter and
  219. #false otherwise
  220. #filter is a directory with keys equal to pre-specified values listed above
  221. #if value associated to key equals None, that value gets set in nodeMetadata
  222. #if value is set, a match is attempted and result reported in return value
  223. #all filters should match for true output
  224. filterOK=True
  225. for key in filter:
  226. try:
  227. fileValue=dicomValue(file,self.tag[key]['tag'],self.tag[key]['seqTag'],shell=shell)
  228. except KeyError:
  229. fileValue=dicomValue(file,self.tag[key]['tag'],shell=shell)
  230. if filter[key]=="SeriesLabel":
  231. nodeMetadata['seriesLabel']=fileValue
  232. continue
  233. if not filter[key]==None:
  234. if not fileValue==filter[key]:
  235. #print("File {} failed for tag {}: {}/{}").format(\
  236. # file,key,fileValue,filter[key])
  237. filterOK=False
  238. break
  239. nodeMetadata[key]=fileValue
  240. return filterOK
  241. def listdir(self,sNet,dir):
  242. #list remote directory
  243. if self.local:
  244. dir1=os.path.join(self.basePath,dir)
  245. dirs=os.listdir(dir1)
  246. return [os.path.join(dir1,f) for f in dirs]
  247. return sNet.listRelativeDir(dir)
  248. def getfile(self,sNet,file):
  249. #get remote file
  250. if self.local:
  251. return file
  252. return sNet.DownloadFileToCache(file)
  253. def removeLocal(self,localFile):
  254. if self.local:
  255. return
  256. os.remove(localFile)
  257. def loadVolumes(self,sNet,dir,filter,doRemove=True):
  258. #returns all series from the directory, each as a separate node in a node list
  259. #filter is a dictionary of speciifed dicom values, if filter(key)=None, that values
  260. #get set, if it isn't, the file gets checked for a match
  261. print("Loading dir {}").format(dir)
  262. dicomFiles=self.listdir(sNet,dir)
  263. #filelist=[os.path.join(dir,f) for f in os.listdir(dir)]
  264. filelist=[]
  265. for f in dicomFiles:
  266. localPath=self.getfile(sNet,f)
  267. f0=localPath
  268. f1=f0+"1"
  269. if not dicomModify==None:
  270. try:
  271. subprocess.call(dicomModify+" "+f0+" "+f1+" && mv "+f1+" "+f0+";", shell=False)
  272. except OSError:
  273. print("dicomModify failed")
  274. filelist.append(localPath)
  275. try:
  276. loadables=self.volumePlugin.examineForImport([filelist])
  277. except AttributeError:
  278. self.volumePlugin=slicer.modules.dicomPlugins['DICOMScalarVolumePlugin']()
  279. loadables=self.volumePlugin.examineForImport([filelist])
  280. volumeNodes=[]
  281. print("Number of loadables:{}").format(len(loadables))
  282. for loadable in loadables:
  283. #TODO check if it makes sense to load a particular loadable
  284. print("{}: Checking number of files: {}".format(\
  285. loadable.name,len(loadable.files)))
  286. #perform checks
  287. fileMetadata={}
  288. loadable.files[:]=[f for f in loadable.files \
  289. if self.applyFilterFile(f,filter,fileMetadata)]
  290. if len(loadable.files)<1:
  291. #skip this loadable
  292. continue
  293. print("{}: Final number of files: {}".format(\
  294. loadable.name,len(loadable.files)))
  295. nodeMetadata={}
  296. self.applyFilterFile(loadable.files[0],filter,nodeMetadata)
  297. volumeNode=self.volumePlugin.load(loadable,"DCMTK")
  298. if volumeNode != None:
  299. vName='Series'+nodeMetadata['seriesLabel']
  300. volumeNode.SetName(vName)
  301. volume={'node':volumeNode,'metadata':nodeMetadata}
  302. volumeNodes.append(volume)
  303. if self.local:
  304. return volumeNodes
  305. if doRemove:
  306. for f in filelist:
  307. self.removeLocal(f)
  308. return volumeNodes
  309. def loadSegmentations(self,net,dir,filter,doRemove=True):
  310. print("Loading dir {}").format(dir)
  311. dicomFiles=self.listdir(net,dir)
  312. filelist=[self.getfile(net,f) for f in dicomFiles]
  313. segmentationNodes=[]
  314. try:
  315. loadableRTs=self.RTPlugin.examineForImport([filelist])
  316. except:
  317. self.RTPlugin=plugin=slicer.modules.dicomPlugins['DicomRtImportExportPlugin']()
  318. loadableRTs=self.RTPlugin.examineForImport([filelist])
  319. for loadable in loadableRTs:
  320. nodeMetadata={}
  321. filterOK=self.applyFilter(loadable,filter,nodeMetadata)
  322. if not filterOK:
  323. continue
  324. success=self.RTPlugin.load(loadable)
  325. if not success:
  326. print("Could not load RT structure set")
  327. return
  328. segNodes=slicer.util.getNodesByClass("vtkMRMLSegmentationNode")
  329. segmentationNode=segNodes[0]
  330. #assume we loaded the first node in list
  331. if segmentationNode != None:
  332. sName='Segmentation'+nodeMetadata['seriesLabel']
  333. segmentationNode.SetName(sName)
  334. segmentation={'node':segmentationNode,'metadata':nodeMetadata}
  335. segmentationNodes.append(segmentation)
  336. if not doRemove:
  337. return segmentationNodes
  338. for f in filelist:
  339. self.removeLocal(f)
  340. return segmentationNodes
  341. def isDicom(file):
  342. #check if file is a dicom file
  343. try:
  344. f=open(file,'rb')
  345. except IOError:
  346. return False
  347. f.read(128)
  348. dt=f.read(4)
  349. f.close()
  350. return dt=='DICM'
  351. def dicomValue(fileName,tag,seqTag=None,shell=False):
  352. #query dicom value of file using dcmdump (DCMTK routine)
  353. #shell must be false for *nix
  354. if os.name=="posix":
  355. shell=False
  356. debug=False
  357. dcmdump=os.path.join(os.environ['SLICER_HOME'],"bin","dcmdump")
  358. try:
  359. if debug:
  360. print("Calling {}".format(dcmdump))
  361. out=subprocess.check_output([dcmdump,'+p','+P',tag,fileName],shell=shell)
  362. if debug:
  363. print("Got {}".format(out))
  364. except subprocess.CalledProcessError as e:
  365. return None
  366. if debug:
  367. print("Tag {} Line '{}'").format(tag,out)
  368. if len(out)==0:
  369. return out
  370. #parse multi-match outputs which appear as several lines
  371. lst=out.split('\n')
  372. return getTagValue(lst,tag,seqTag)
  373. def getTagValue(lst,tag,seqTag=None):
  374. #report tag value from a list lst of lines reported by dcmdump
  375. debug=False
  376. #parse output
  377. longTag="^\({}\)".format(tag)
  378. #combine sequence and actual tags to long tags
  379. if not seqTag==None:
  380. if debug:
  381. print("Tag:{} seqTag:{}").format(tag,seqTag)
  382. longTag="^\({}\).\({}\)".format(seqTag,tag)
  383. #pick the values
  384. pattern=r'^.*\[(.*)\].*$'
  385. #extract tag values
  386. rpl=[re.sub(pattern,r'\1',f) for f in lst]
  387. #logical whether the line can be matched to typical dcmdump output
  388. mtchPattern=[re.match(pattern,f) for f in lst]
  389. #find matching tags
  390. mtchTag=[re.match(longTag,f) for f in lst]
  391. #weed out non-matching lines and lines not matching longTag
  392. mtch=[None if x==None or y==None else x \
  393. for x,y in zip(mtchTag,mtchPattern)]
  394. #set values
  395. out=[x for y,x in zip(mtch,rpl) if not y==None]
  396. if len(out)==0:
  397. return ''
  398. #return first match
  399. out=out[0]
  400. if debug:
  401. print("Tag {} Parsed value {}").format(tag,out)
  402. #split output to lists if values are DICOM lists
  403. if out.find('\\')>-1:
  404. out=out.split('\\')
  405. return out
  406. def clearNodes():
  407. nodes=[]
  408. nodes.extend(slicer.util.getNodesByClass("vtkMRMLScalarVolumeNode"))
  409. nodes.extend(slicer.util.getNodesByClass("vtkMRMLScalarVolumeDisplayNode"))
  410. nodes.extend(slicer.util.getNodesByClass("vtkMRMLSegmentationNode"))
  411. nodes.extend(slicer.util.getNodesByClass("vtkMRMLSegmentationDisplayNode"))
  412. for node in nodes:
  413. slicer.mrmlScene.RemoveNode(node)