cardiacSPECT.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. import os
  2. import sys
  3. import unittest
  4. import vtk, qt, ctk, slicer
  5. from slicer.ScriptedLoadableModule import *
  6. import logging
  7. import vtkInterface as vi
  8. import parseDicom as pd
  9. #
  10. # cardiacSPECT
  11. #
  12. class cardiacSPECT(ScriptedLoadableModule):
  13. """Uses ScriptedLoadableModule base class, available at:
  14. https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
  15. """
  16. def __init__(self, parent):
  17. ScriptedLoadableModule.__init__(self, parent)
  18. parent.title = "Cardiac SPECT"
  19. parent.categories = ["Examples"]
  20. parent.dependencies = []
  21. parent.contributors = ["Andrej Studen (FMF/JSI)"] # replace with "Firstname Lastname (Org)"
  22. parent.helpText = """
  23. Load dynamic cardiac SPECT data to Slicer
  24. """
  25. parent.acknowledgementText = """
  26. This module was developed within the frame of the ARRS sponsored medical
  27. physics research programe to investigate quantitative measurements of cardiac
  28. function using sestamibi-like tracers
  29. """ # replace with organization, grant and thanks.
  30. self.parent.helpText += self.getDefaultModuleDocumentationLink()
  31. self.parent = parent
  32. #
  33. # cardiacSPECTWidget
  34. #
  35. class cardiacSPECTWidget(ScriptedLoadableModuleWidget):
  36. """Uses ScriptedLoadableModuleWidget base class, available at:
  37. https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
  38. """
  39. def setup(self):
  40. ScriptedLoadableModuleWidget.setup(self)
  41. # Instantiate and connect widgets ...
  42. dataButton = ctk.ctkCollapsibleButton()
  43. dataButton.text = "Data"
  44. self.layout.addWidget(dataButton)
  45. # Layout within the sample collapsible button
  46. dataFormLayout = qt.QFormLayout(dataButton)
  47. pathGuess="file://"+os.environ['HOME']+"/SPECT"
  48. self.dataPath=qt.QLineEdit(pathGuess)
  49. dataFormLayout.addRow("Data location",self.dataPath)
  50. browseButton = qt.QPushButton("Browse")
  51. browseButton.toolTip="Set file location"
  52. dataFormLayout.addRow("Change data location",browseButton)
  53. browseButton.connect('clicked(bool)',self.onBrowseButtonClicked)
  54. dataLoadButton = qt.QPushButton("Load")
  55. dataLoadButton.toolTip="Load data from DICOM"
  56. dataFormLayout.addRow("Data",dataLoadButton)
  57. dataLoadButton.connect('clicked(bool)',self.onDataLoadButtonClicked)
  58. self.dataLoadButton = dataLoadButton
  59. # Add vertical spacer
  60. self.layout.addStretch(1)
  61. #addFrameButton=qt.QPushButton("Add Frame")
  62. #addFrameButton.toolTip="Add frame to VTK"
  63. #dataFormLayout.addWidget(addFrameButton)
  64. #addFrameButton.connect('clicked(bool)',self.onAddFrameButtonClicked)
  65. #addCTButton=qt.QPushButton("Add CT")
  66. #addCTButton.toolTip="Add CT to VTK"
  67. #dataFormLayout.addWidget(addCTButton)
  68. #addCTButton.connect('clicked(bool)',self.onAddCTButtonClicked)
  69. #
  70. # Parameters Area
  71. #
  72. parametersCollapsibleButton = ctk.ctkCollapsibleButton()
  73. parametersCollapsibleButton.text = "Parameters"
  74. self.layout.addWidget(parametersCollapsibleButton)
  75. # Layout within the dummy collapsible button
  76. parametersFormLayout = qt.QFormLayout(parametersCollapsibleButton)
  77. #
  78. # check box to trigger taking screen shots for later use in tutorials
  79. #
  80. hbox1=qt.QHBoxLayout()
  81. frameLabel = qt.QLabel()
  82. frameLabel.setText("Select frame")
  83. hbox1.addWidget(frameLabel)
  84. self.time_frame_select=qt.QSlider(qt.Qt.Horizontal)
  85. self.time_frame_select.valueChanged.connect(self.onTimeFrameSelect)
  86. #self.time_frame_select.connect('valueChanged()', self.onTimeFrameSelect)
  87. self.time_frame_select.setMinimum(0)
  88. self.time_frame_select.setMaximum(0)
  89. self.time_frame_select.setValue(0)
  90. self.time_frame_select.setTickPosition(qt.QSlider.TicksBelow)
  91. self.time_frame_select.setTickInterval(5)
  92. self.time_frame_select.toolTip = "Select the time frame"
  93. hbox1.addWidget(self.time_frame_select)
  94. parametersFormLayout.addRow(hbox1)
  95. hbox2 = qt.QHBoxLayout()
  96. meanROILabel = qt.QLabel()
  97. meanROILabel.setText("MeanROI")
  98. hbox2.addWidget(meanROILabel)
  99. self.meanROIVolume = qt.QLineEdit()
  100. self.meanROIVolume.setText("testVolume15")
  101. hbox2.addWidget(self.meanROIVolume)
  102. self.meanROISegment = qt.QLineEdit()
  103. self.meanROISegment.setText("Segment_1")
  104. hbox2.addWidget(self.meanROISegment)
  105. computeMeanROI = qt.QPushButton("Compute mean ROI")
  106. computeMeanROI.connect('clicked(bool)',self.onComputeMeanROIClicked)
  107. hbox2.addWidget(computeMeanROI)
  108. self.meanROIResult = qt.QLineEdit()
  109. self.meanROIResult.setText("0")
  110. hbox2.addWidget(self.meanROIResult)
  111. parametersFormLayout.addRow(hbox2)
  112. #row 3
  113. hbox3 = qt.QHBoxLayout()
  114. drawTimePlot=qt.QPushButton("Draw ROI time plot")
  115. drawTimePlot.connect('clicked(bool)',self.onDrawTimePlotClicked)
  116. hbox3.addWidget(drawTimePlot)
  117. parametersFormLayout.addRow(hbox3)
  118. #dataFormLayout.addWidget(hbox)
  119. #row 4
  120. hbox4 = qt.QHBoxLayout()
  121. countSegments=qt.QPushButton("Count segmentation segments")
  122. countSegments.connect('clicked(bool)',self.onCountSegmentsClicked)
  123. hbox4.addWidget(countSegments)
  124. self.countSegmentsDisplay=qt.QLineEdit()
  125. self.countSegmentsDisplay.setText("0")
  126. hbox4.addWidget(self.countSegmentsDisplay)
  127. parametersFormLayout.addRow(hbox4)
  128. #
  129. # Apply Button
  130. #
  131. self.applyButton = qt.QPushButton("Apply")
  132. self.applyButton.toolTip = "Run the algorithm."
  133. self.applyButton.enabled = False
  134. parametersFormLayout.addRow(self.applyButton)
  135. # connections
  136. self.applyButton.connect('clicked(bool)', self.onApplyButton)
  137. #self.inputSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.onSelect)
  138. #self.outputSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.onSelect)
  139. # Add vertical spacer
  140. self.layout.addStretch(1)
  141. self.logic=cardiacSPECTLogic()
  142. self.resetPosition=1
  143. def cleanup(self):
  144. pass
  145. def onApplyButton(self):
  146. pass
  147. #logic = cardiacSPECTLogic()
  148. #imageThreshold = self.imageThresholdSliderWidget.value
  149. def onBrowseButtonClicked(self):
  150. startDir=self.dataPath.text
  151. inputDir=qt.QFileDialog.getExistingDirectory(None,
  152. 'Select DICOM directory',startDir)
  153. self.dataPath.setText("file://"+inputDir)
  154. def onDataLoadButtonClicked(self):
  155. self.logic.loadData(self)
  156. def onTimeFrameSelect(self):
  157. it=self.time_frame_select.value
  158. selectionNode = slicer.app.applicationLogic().GetSelectionNode()
  159. print("Propagating CT volume")
  160. node=slicer.mrmlScene.GetFirstNodeByName("testCT")
  161. selectionNode.SetReferenceActiveVolumeID(node.GetID())
  162. if self.resetPosition==1:
  163. self.resetPosition=0
  164. slicer.app.applicationLogic().PropagateVolumeSelection(1)
  165. else:
  166. slicer.app.applicationLogic().PropagateVolumeSelection(0)
  167. print("Propagating SPECT volume")
  168. nodeName='testVolume'+str(it)
  169. node=slicer.mrmlScene.GetFirstNodeByName(nodeName)
  170. selectionNode.SetSecondaryVolumeID(node.GetID())
  171. slicer.app.applicationLogic().PropagateForegroundVolumeSelection(0)
  172. node.GetDisplayNode().SetAndObserveColorNodeID('vtkMRMLColorTableNodeRed')
  173. lm = slicer.app.layoutManager()
  174. sID=['Red','Yellow','Green']
  175. for s in sID:
  176. sliceLogic = lm.sliceWidget(s).sliceLogic()
  177. compositeNode = sliceLogic.GetSliceCompositeNode()
  178. compositeNode.SetForegroundOpacity(0.5)
  179. #make sure the viewer is matched to the volume
  180. print("Done")
  181. #to access sliceLogic (slice control) use
  182. #lcol=slicer.app.layoutManager().mrmlSliceLogics() (vtkCollection)
  183. #vtkMRMLSliceLogic are named by colors (Red,Green,Blue)
  184. def onComputeMeanROIClicked(self):
  185. s=self.logic.meanROI(self.meanROIVolume.text,self.meanROISegment.text)
  186. self.meanROIResult.setText(str(s))
  187. def onDrawTimePlotClicked(self):
  188. n=self.time_frame_select.maximum
  189. ft=self.logic.frame_time
  190. #find number of segments
  191. ns = self.logic.countSegments()
  192. #add the chart node
  193. cn = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())
  194. for j in range(0,ns):
  195. segment="Segment_"+str(j+1)
  196. #add node for data
  197. dn = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
  198. a = dn.GetArray()
  199. a.SetNumberOfTuples(n)
  200. for i in range(0,n):
  201. vol="testVolume"+str(i)
  202. fx=ft[i]
  203. fy=self.logic.meanROI(vol,segment)
  204. a.SetComponent(i, 0, fx)
  205. a.SetComponent(i, 1, fy)
  206. a.SetComponent(i, 2, 0)
  207. print("({0:.2f}:{1:.2f})".format(fx,fy))
  208. cn.AddArray(segment, dn.GetID())
  209. cn.SetProperty('default', 'title', 'ROI time plot')
  210. cn.SetProperty('default', 'xAxisLabel', 'time [ms]')
  211. cn.SetProperty('default', 'yAxisLabel', 'Activity (arb)')
  212. #update the chart node
  213. cvns = slicer.mrmlScene.GetNodesByClass('vtkMRMLChartViewNode')
  214. cvns.InitTraversal()
  215. cvn = cvns.GetNextItemAsObject()
  216. cvn.SetChartNodeID(cn.GetID())
  217. def onCountSegmentsClicked(self):
  218. self.countSegmentsDisplay.setText(self.logic.countSegments())
  219. #def onAddFrameButtonClicked(self):
  220. # it=int(self.time_frame_select.text)
  221. # self.logic.addFrame(it)
  222. # def onAddCTButtonClicked(self):
  223. # self.logic.addCT()
  224. #
  225. #
  226. # cardiacSPECTLogic
  227. #
  228. class cardiacSPECTLogic(ScriptedLoadableModuleLogic):
  229. """This class should implement all the actual
  230. computation done by your module. The interface
  231. should be such that other python code can import
  232. this class and make use of the functionality without
  233. requiring an instance of the Widget.
  234. Uses ScriptedLoadableModuleLogic base class, available at:
  235. https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
  236. """
  237. def loadData(self,widget):
  238. inputDir=str(widget.dataPath.text)
  239. self.frame_data, self.frame_time, self.frame_origin, \
  240. self.frame_pixel_size, self.frame_orientation=pd.read_dynamic_SPECT(inputDir)
  241. self.ct_data,self.ct_origin,self.ct_pixel_size, \
  242. self.ct_orientation=pd.read_CT(inputDir)
  243. self.ct_orientation=vi.completeOrientation(self.ct_orientation)
  244. self.frame_orientation=vi.completeOrientation(self.frame_orientation)
  245. self.addCT()
  246. self.addFrames()
  247. widget.time_frame_select.setMaximum(self.frame_data.shape[3]-1)
  248. #additional message via qt
  249. qt.QMessageBox.information(
  250. slicer.util.mainWindow(),
  251. 'Slicer Python','Data loaded')
  252. def addNode(self,nodeName,v, origin, pixel_size, orientation, dataType):
  253. # if dataType=0 it is CT data, which gets propagated to background an is
  254. #used to fit the view field dimensions
  255. # if dataType=1, it is SPECT data, which gets propagated to foreground
  256. #and is not fit; keeping window set from CT
  257. #nodeName='testVolume'+str(it)
  258. newNode=slicer.vtkMRMLScalarVolumeNode()
  259. newNode.SetName(nodeName)
  260. #pixel_size=[0,0,0]
  261. #pixel_size=v.GetSpacing()
  262. #print(pixel_size)
  263. #origin=[0,0,0]
  264. #origin=v.GetOrigin()
  265. v.SetOrigin([0,0,0])
  266. v.SetSpacing([1,1,1])
  267. ijkToRAS = vtk.vtkMatrix4x4()
  268. #think how to do this with image orientation
  269. for i in range(0,3):
  270. for j in range(0,3):
  271. ijkToRAS.SetElement(i,j,pixel_size[i]*orientation[3*j+i])
  272. ijkToRAS.SetElement(i,3,origin[i])
  273. newNode.SetIJKToRASMatrix(ijkToRAS)
  274. newNode.SetAndObserveImageData(v)
  275. slicer.mrmlScene.AddNode(newNode)
  276. def addFrames(self):
  277. #convert data from numpy.array to vtkImageData
  278. #use time point it
  279. for it in range(0,self.frame_data.shape[3]):
  280. frame_data=self.frame_data[:,:,:,it];
  281. nodeName='testVolume'+str(it)
  282. self.addNode(nodeName,
  283. vi.numpyToVTK3D(frame_data,self.frame_origin,
  284. self.frame_pixel_size),
  285. self.frame_origin,
  286. self.frame_pixel_size,
  287. self.frame_orientation,1)
  288. def addCT(self):
  289. nodeName='testCT'
  290. self.addNode(nodeName,
  291. vi.numpyToVTK3D(self.ct_data,
  292. self.ct_origin,self.ct_pixel_size),
  293. self.ct_origin,self.ct_pixel_size,
  294. self.ct_orientation,0)
  295. def meanROI(self, volName1, segment):
  296. s=0
  297. #get the segmentation mask
  298. fNode=slicer.mrmlScene.GetNodesByClass("vtkMRMLSegmentationNode").GetItemAsObject(0)
  299. segNode=slicer.vtkMRMLSegmentationNode.SafeDownCast(fNode)
  300. #no python bindings for vtkSegmentation
  301. #if segNode.GetSegmentation().GetNumberOfSegments()==0 :
  302. # print("No segments available")
  303. # return 0
  304. mask = segNode.GetBinaryLabelmapRepresentation(segment)
  305. if mask==None:
  306. print("Segment {} not found".format(segment))
  307. return s
  308. #segNode.GetSegmentation().GetNthSegmentID(0))
  309. #get mask at (x,y,z)
  310. #mask.GetPointData().GetScalars().GetTuple1(mask.FindPoint([x,y,z]))
  311. #get the image data
  312. dataNode=slicer.mrmlScene.GetFirstNodeByName(volName1)
  313. dataImage=dataNode.GetImageData()
  314. # use IJK2RAS to get global coordinates
  315. ijkToRas = vtk.vtkMatrix4x4()
  316. dataNode.GetIJKToRASMatrix(ijkToRas)
  317. #iterate over volume pixelData
  318. n=dataImage.GetNumberOfPoints()
  319. for i in range(0,n):
  320. #get global coordinates of point i
  321. [ix,iy,iz]=dataImage.GetPoint(i)
  322. position_ijk=[ix, iy, iz, 1]
  323. #ras are global coordinates (in mm)
  324. position_ras=ijkToRas.MultiplyPoint(position_ijk)
  325. #find point in mask with the same global coordinates
  326. fr=[position_ras[0],position_ras[1],position_ras[2]]
  327. maskValue=mask.GetPointData().GetScalars().GetTuple1(mask.FindPoint(fr))
  328. if maskValue == 0:
  329. continue
  330. #use maskValue to project ROI data
  331. s+=maskValue*dataImage.GetPointData().GetScalars().GetTuple1(i)
  332. return s/n
  333. def countSegments(self):
  334. fNode=slicer.mrmlScene.GetNodesByClass("vtkMRMLSegmentationNode").GetItemAsObject(0)
  335. segNode=slicer.vtkMRMLSegmentationNode.SafeDownCast(fNode)
  336. i=1
  337. while 1:
  338. segName="Segment_"+str(i)
  339. mask = segNode.GetBinaryLabelmapRepresentation(segName)
  340. if mask==None:
  341. break
  342. i+=1
  343. return i-1
  344. class cardiacSPECTTest(ScriptedLoadableModuleTest):
  345. """
  346. This is the test case for your scripted module.
  347. Uses ScriptedLoadableModuleTest base class, available at:
  348. https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
  349. """
  350. def setUp(self):
  351. """ Do whatever is needed to reset the state - typically a scene clear will be enough.
  352. """
  353. slicer.mrmlScene.Clear(0)
  354. def runTest(self):
  355. """Run as few or as many tests as needed here.
  356. """
  357. self.setUp()
  358. self.test_cardiacSPECT1()
  359. def test_cardiacSPECT1(self):
  360. """ Ideally you should have several levels of tests. At the lowest level
  361. tests should exercise the functionality of the logic with different inputs
  362. (both valid and invalid). At higher levels your tests should emulate the
  363. way the user would interact with your code and confirm that it still works
  364. the way you intended.
  365. One of the most important features of the tests is that it should alert other
  366. developers when their changes will have an impact on the behavior of your
  367. module. For example, if a developer removes a feature that you depend on,
  368. your test should break so they know that the feature is needed.
  369. """
  370. self.delayDisplay("Starting the test")
  371. #
  372. # first, get some data
  373. #
  374. self.delayDisplay('Test passed!')