cardiacSPECT.py 15 KB

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