-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFreeSurferSynthStripSkullStripScripted.py
447 lines (366 loc) · 19.4 KB
/
FreeSurferSynthStripSkullStripScripted.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
import logging
import os
import vtk
import slicer
from slicer.ScriptedLoadableModule import *
from slicer.util import VTKObservationMixin
DEBUG = True
#
# FreeSurferSynthStripSkullStripScripted
#
class FreeSurferSynthStripSkullStripScripted(ScriptedLoadableModule):
"""Uses ScriptedLoadableModule base class, available at:
https://github.com/Slicer/Slicer/blob/main/Base/Python/slicer/ScriptedLoadableModule.py
"""
def __init__(self, parent):
ScriptedLoadableModule.__init__(self, parent)
self.parent.title = "FreeSurfer SynthStrip Skull Strip"
self.parent.categories = ["Segmentation"]
self.parent.dependencies = []
self.parent.contributors = ["Benjamin Zwick (ISML)"]
# TODO: update with short description of the module and a link to online module documentation
self.parent.helpText = """Skull stripping for head studies using SynthStrip from FreeSurfer.
For a detailed description of SynthStrip please refer to its documentation <a href="https://surfer.nmr.mgh.harvard.edu/docs/synthstrip">here</a>.
See more information in <a href="https://github.com/SlicerCBM/SlicerFreeSurferCommands/tree/main/FreeSurferSynthStripSkullStripScripted/README.md">module documentation</a>.
"""
# TODO: replace with organization, grant and thanks
self.parent.acknowledgementText = """
This module uses FreeSurfer's SynthStrip command.
If you use SynthStrip in your analysis, please cite:
SynthStrip: Skull-Stripping for Any Brain Image
Andrew Hoopes, Jocelyn S. Mora, Adrian V. Dalca, Bruce Fischl*, Malte Hoffmann* (*equal contribution)
NeuroImage 260, 2022, 119474
https://doi.org/10.1016/j.neuroimage.2022.119474
"""
# Additional initialization step after application startup is complete
slicer.app.connect("startupCompleted()", registerSampleData)
#
# Register sample data sets in Sample Data module
#
def registerSampleData():
"""
Add data sets to Sample Data module.
"""
# It is always recommended to provide sample data for users to make it easy to try the module,
# but if no sample data is available then this method (and associated startupCompeted signal connection) can be removed.
import SampleData
iconsPath = os.path.join(os.path.dirname(__file__), 'Resources/Icons')
# To ensure that the source code repository remains small (can be downloaded and installed quickly)
# it is recommended to store data sets that are larger than a few MB in a Github release.
# TODO: Add sample data...
#
# FreeSurferSynthStripSkullStripScriptedWidget
#
class FreeSurferSynthStripSkullStripScriptedWidget(ScriptedLoadableModuleWidget, VTKObservationMixin):
"""Uses ScriptedLoadableModuleWidget base class, available at:
https://github.com/Slicer/Slicer/blob/main/Base/Python/slicer/ScriptedLoadableModule.py
"""
def __init__(self, parent=None):
"""
Called when the user opens the module the first time and the widget is initialized.
"""
ScriptedLoadableModuleWidget.__init__(self, parent)
VTKObservationMixin.__init__(self) # needed for parameter node observation
self.logic = None
self._parameterNode = None
self._updatingGUIFromParameterNode = False
def setup(self):
"""
Called when the user opens the module the first time and the widget is initialized.
"""
ScriptedLoadableModuleWidget.setup(self)
# Load widget from .ui file (created by Qt Designer).
# Additional widgets can be instantiated manually and added to self.layout.
uiWidget = slicer.util.loadUI(self.resourcePath('UI/FreeSurferSynthStripSkullStripScripted.ui'))
self.layout.addWidget(uiWidget)
self.ui = slicer.util.childWidgetVariables(uiWidget)
# Set scene in MRML widgets. Make sure that in Qt designer the top-level qMRMLWidget's
# "mrmlSceneChanged(vtkMRMLScene*)" signal in is connected to each MRML widget's.
# "setMRMLScene(vtkMRMLScene*)" slot.
uiWidget.setMRMLScene(slicer.mrmlScene)
# Create logic class. Logic implements all computations that should be possible to run
# in batch mode, without a graphical user interface.
self.logic = FreeSurferSynthStripSkullStripScriptedLogic()
# Connections
# These connections ensure that we update parameter node when scene is closed
self.addObserver(slicer.mrmlScene, slicer.mrmlScene.StartCloseEvent, self.onSceneStartClose)
self.addObserver(slicer.mrmlScene, slicer.mrmlScene.EndCloseEvent, self.onSceneEndClose)
# These connections ensure that whenever user changes some settings on the GUI, that is saved in the MRML scene
# (in the selected parameter node).
self.ui.inputImageSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.updateParameterNodeFromGUI)
self.ui.outputImageSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.updateParameterNodeFromGUI)
self.ui.outputMaskSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.updateParameterNodeFromGUI)
self.ui.gpuCheckBox.connect("toggled(bool)", self.updateParameterNodeFromGUI)
self.ui.borderThresholdSliderWidget.connect("valueChanged(double)", self.updateParameterNodeFromGUI)
self.ui.nocsfCheckBox.connect("toggled(bool)", self.updateParameterNodeFromGUI)
# Buttons
self.ui.applyButton.connect('clicked(bool)', self.onApplyButton)
# Make sure parameter node is initialized (needed for module reload)
self.initializeParameterNode()
def cleanup(self):
"""
Called when the application closes and the module widget is destroyed.
"""
self.removeObservers()
def enter(self):
"""
Called each time the user opens this module.
"""
# Make sure parameter node exists and observed
self.initializeParameterNode()
def exit(self):
"""
Called each time the user opens a different module.
"""
# Do not react to parameter node changes (GUI wlil be updated when the user enters into the module)
self.removeObserver(self._parameterNode, vtk.vtkCommand.ModifiedEvent, self.updateGUIFromParameterNode)
def onSceneStartClose(self, caller, event):
"""
Called just before the scene is closed.
"""
# Parameter node will be reset, do not use it anymore
self.setParameterNode(None)
def onSceneEndClose(self, caller, event):
"""
Called just after the scene is closed.
"""
# If this module is shown while the scene is closed then recreate a new parameter node immediately
if self.parent.isEntered:
self.initializeParameterNode()
def initializeParameterNode(self):
"""
Ensure parameter node exists and observed.
"""
# Parameter node stores all user choices in parameter values, node selections, etc.
# so that when the scene is saved and reloaded, these settings are restored.
self.setParameterNode(self.logic.getParameterNode())
# Select default input nodes if nothing is selected yet to save a few clicks for the user
if not self._parameterNode.GetNodeReference("InputVolume"):
firstVolumeNode = slicer.mrmlScene.GetFirstNodeByClass("vtkMRMLScalarVolumeNode")
if firstVolumeNode:
self._parameterNode.SetNodeReferenceID("InputVolume", firstVolumeNode.GetID())
def setParameterNode(self, inputParameterNode):
"""
Set and observe parameter node.
Observation is needed because when the parameter node is changed then the GUI must be updated immediately.
"""
if inputParameterNode:
self.logic.setDefaultParameters(inputParameterNode)
# Unobserve previously selected parameter node and add an observer to the newly selected.
# Changes of parameter node are observed so that whenever parameters are changed by a script or any other module
# those are reflected immediately in the GUI.
if self._parameterNode is not None and self.hasObserver(self._parameterNode, vtk.vtkCommand.ModifiedEvent, self.updateGUIFromParameterNode):
self.removeObserver(self._parameterNode, vtk.vtkCommand.ModifiedEvent, self.updateGUIFromParameterNode)
self._parameterNode = inputParameterNode
if self._parameterNode is not None:
self.addObserver(self._parameterNode, vtk.vtkCommand.ModifiedEvent, self.updateGUIFromParameterNode)
# Initial GUI update
self.updateGUIFromParameterNode()
def updateGUIFromParameterNode(self, caller=None, event=None):
"""
This method is called whenever parameter node is changed.
The module GUI is updated to show the current state of the parameter node.
"""
if self._parameterNode is None or self._updatingGUIFromParameterNode:
return
# Make sure GUI changes do not call updateParameterNodeFromGUI (it could cause infinite loop)
self._updatingGUIFromParameterNode = True
# Update node selectors and sliders
self.ui.inputImageSelector.setCurrentNode(self._parameterNode.GetNodeReference("InputVolume"))
self.ui.outputImageSelector.setCurrentNode(self._parameterNode.GetNodeReference("OutputVolume"))
self.ui.outputMaskSelector.setCurrentNode(self._parameterNode.GetNodeReference("OutputMask"))
self.ui.gpuCheckBox.checked = (self._parameterNode.GetParameter("UseGPU") == "true")
self.ui.borderThresholdSliderWidget.value = float(self._parameterNode.GetParameter("BorderThreshold"))
self.ui.nocsfCheckBox.checked = (self._parameterNode.GetParameter("ExcludeCSF") == "true")
# Update buttons states and tooltips
if self._parameterNode.GetNodeReference("InputVolume"):
if self._parameterNode.GetNodeReference("OutputVolume"):
self.ui.applyButton.toolTip = "Compute output stripped image volume"
self.ui.applyButton.enabled = True
if self._parameterNode.GetNodeReference("OutputMask"):
self.ui.applyButton.toolTip = "Compute output binary brain mask volume"
self.ui.applyButton.enabled = True
if (self._parameterNode.GetNodeReference("OutputVolume") and
self._parameterNode.GetNodeReference("OutputMask")):
self.ui.applyButton.toolTip = "Compute output output image volume and binary brain mask volume"
self.ui.applyButton.enabled = True
else:
self.ui.applyButton.toolTip = "Select input and output image volume or binary brain mask volume nodes"
self.ui.applyButton.enabled = False
# All the GUI updates are done
self._updatingGUIFromParameterNode = False
def updateParameterNodeFromGUI(self, caller=None, event=None):
"""
This method is called when the user makes any change in the GUI.
The changes are saved into the parameter node (so that they are restored when the scene is saved and loaded).
"""
if self._parameterNode is None or self._updatingGUIFromParameterNode:
return
wasModified = self._parameterNode.StartModify() # Modify all properties in a single batch
self._parameterNode.SetNodeReferenceID("InputVolume", self.ui.inputImageSelector.currentNodeID)
self._parameterNode.SetNodeReferenceID("OutputVolume", self.ui.outputImageSelector.currentNodeID)
self._parameterNode.SetNodeReferenceID("OutputMask", self.ui.outputMaskSelector.currentNodeID)
self._parameterNode.SetParameter("UseGPU", "true" if self.ui.gpuCheckBox.checked else "false")
self._parameterNode.SetParameter("BorderThreshold", str(self.ui.borderThresholdSliderWidget.value))
self._parameterNode.SetParameter("ExcludeCSF", "true" if self.ui.nocsfCheckBox.checked else "false")
self._parameterNode.EndModify(wasModified)
def onApplyButton(self):
"""
Run processing when user clicks "Apply" button.
"""
with slicer.util.tryWithErrorDisplay("Failed to compute results.", waitCursor=True):
# Compute output
self.logic.process(self.ui.inputImageSelector.currentNode(),
self.ui.outputImageSelector.currentNode(),
self.ui.outputMaskSelector.currentNode(),
self.ui.gpuCheckBox.checked,
self.ui.borderThresholdSliderWidget.value,
self.ui.nocsfCheckBox.checked)
#
# FreeSurferSynthStripSkullStripScriptedLogic
#
class FreeSurferSynthStripSkullStripScriptedLogic(ScriptedLoadableModuleLogic):
"""This class should implement all the actual
computation done by your module. The interface
should be such that other python code can import
this class and make use of the functionality without
requiring an instance of the Widget.
Uses ScriptedLoadableModuleLogic base class, available at:
https://github.com/Slicer/Slicer/blob/main/Base/Python/slicer/ScriptedLoadableModule.py
"""
def __init__(self):
"""
Called when the logic class is instantiated. Can be used for initializing member variables.
"""
ScriptedLoadableModuleLogic.__init__(self)
def setDefaultParameters(self, parameterNode):
"""
Initialize parameter node with default settings.
"""
if not parameterNode.GetParameter("UseGPU"):
parameterNode.SetParameter("UseGPU", "false")
if not parameterNode.GetParameter("BorderThreshold"):
parameterNode.SetParameter("BorderThreshold", "1")
if not parameterNode.GetParameter("ExcludeCSF"):
parameterNode.SetParameter("ExcludeCSF", "false")
def process(self, inputImageNode,
outputImageNode=None, outputMaskNode=None,
useGPU=False, borderThreshold=1, excludeCSF=False):
"""
Run the processing algorithm.
Can be used without GUI widget.
# FIXME: Update documentation
:param inputVolume: volume to be thresholded
:param outputVolume: thresholding result
:param imageThreshold: values above/below this threshold will be set to 0
:param invert: if True then values above the threshold will be set to 0, otherwise values below are set to 0
:param showResult: show output volume in slice viewers
"""
if not inputImageNode:
raise ValueError("Input volume is undefined")
if not outputImageNode and not outputMaskNode:
raise ValueError("Output image or mask volume is undefined")
import time
startTime = time.time()
logging.info('Processing started')
import os
from pathlib import Path
import qt
# import subprocess
temp_dir = qt.QTemporaryDir()
temp_path = Path(temp_dir.path())
if DEBUG:
print("temp_path:", temp_path)
# Temporary image files in FreeSurfer format
temp_image = str(temp_path / 'input.mgz')
temp_out = str(temp_path / 'stripped.mgz')
temp_mask = str(temp_path / 'mask.mgz')
if DEBUG:
print(temp_image)
# Convert image to FreeSurfer format
slicer.util.exportNode(inputImageNode, temp_image)
if DEBUG:
os.listdir(temp_path)
fs_env = os.environ.copy()
if DEBUG:
print(fs_env)
# Use system Python environment
fs_env['PYTHONHOME'] = ''
if DEBUG:
print("PYTHONHOME:", fs_env['PYTHONHOME'])
print("PYTHONPATH:", fs_env['PYTHONPATH'])
print("FREESURFER_HOME:", fs_env['FREESURFER_HOME'])
args = [fs_env['FREESURFER_HOME'] + '/bin/mri_synthstrip']
args.extend(['--image', temp_image])
if outputImageNode:
args.extend(['--out', temp_out])
if outputMaskNode:
args.extend(['--mask', temp_mask])
if useGPU:
args.extend(['--gpu'])
if borderThreshold != 1:
args.extend(['--border', str(borderThreshold)])
if excludeCSF:
args.extend(['--no-csf'])
print("Command:", args)
#subprocess.check_output(args, env=fs_env)
proc = slicer.util.launchConsoleProcess(args)
slicer.util.logProcessOutput(proc)
# Create color table for brain mask (mask will have the 'tissue' label with value '1')
colorTableNode = slicer.mrmlScene.GetFirstNodeByName('GenericAnatomyColors')
# Load temporary files back into nodes
if outputImageNode:
storage = slicer.mrmlScene.AddNewNodeByClass('vtkMRMLVolumeArchetypeStorageNode')
storage.SetFileName(temp_out)
storage.ReadData(outputImageNode)
slicer.mrmlScene.RemoveNode(storage)
if outputMaskNode:
if outputMaskNode.GetTypeDisplayName() == 'LabelMapVolume':
storage = slicer.mrmlScene.AddNewNodeByClass('vtkMRMLVolumeArchetypeStorageNode')
storage.SetFileName(temp_mask)
storage.ReadData(outputMaskNode)
slicer.mrmlScene.RemoveNode(storage)
if outputMaskNode.GetDisplayNode() is None:
outputMaskNode.CreateDefaultDisplayNodes()
outputMaskNode.GetDisplayNode().SetAndObserveColorNodeID(colorTableNode.GetID())
elif outputMaskNode.GetTypeDisplayName() == 'Segmentation':
labelmap = slicer.util.loadLabelVolume(temp_mask, properties={'colorNodeID': colorTableNode.GetID()})
slicer.modules.segmentations.logic().ImportLabelmapToSegmentationNode(labelmap, outputMaskNode)
slicer.mrmlScene.RemoveNode(labelmap)
else:
raise NotImplementedError
stopTime = time.time()
logging.info(f'Processing completed in {stopTime-startTime:.2f} seconds')
#
# FreeSurferSynthStripSkullStripScriptedTest
#
class FreeSurferSynthStripSkullStripScriptedTest(ScriptedLoadableModuleTest):
"""
This is the test case for your scripted module.
Uses ScriptedLoadableModuleTest base class, available at:
https://github.com/Slicer/Slicer/blob/main/Base/Python/slicer/ScriptedLoadableModule.py
"""
def setUp(self):
""" Do whatever is needed to reset the state - typically a scene clear will be enough.
"""
slicer.mrmlScene.Clear()
def runTest(self):
"""Run as few or as many tests as needed here.
"""
self.setUp()
self.test_FreeSurferSynthStripSkullStripScripted1()
def test_FreeSurferSynthStripSkullStripScripted1(self):
""" Ideally you should have several levels of tests. At the lowest level
tests should exercise the functionality of the logic with different inputs
(both valid and invalid). At higher levels your tests should emulate the
way the user would interact with your code and confirm that it still works
the way you intended.
One of the most important features of the tests is that it should alert other
developers when their changes will have an impact on the behavior of your
module. For example, if a developer removes a feature that you depend on,
your test should break so they know that the feature is needed.
"""
self.delayDisplay("Starting the test")
# TODO: add tests...
self.delayDisplay("This test does nothing!")
self.delayDisplay('Test passed')