2 import vtk, qt, ctk, slicer
4 from SegmentEditorEffects
import *
7 """ ThresholdEffect is an Effect implementing the global threshold 8 operation in the segment editor 10 This is also an example for scripted effects, and some methods have no 11 function. The methods that are not needed (i.e. the default implementation in 12 qSlicerSegmentEditorAbstractEffect is satisfactory) can simply be omitted. 16 AbstractScriptedSegmentEditorEffect.__init__(self, scriptedEffect)
17 scriptedEffect.name =
'Threshold' 37 import qSlicerSegmentationsEditorEffectsPythonQt
as effects
38 clonedEffect = effects.qSlicerSegmentEditorScriptedEffect(
None)
39 clonedEffect.setPythonSource(__file__.replace(
'\\',
'/'))
43 iconPath = os.path.join(os.path.dirname(__file__),
'Resources/Icons/Threshold.png')
44 if os.path.exists(iconPath):
45 return qt.QIcon(iconPath)
49 return """<html>Fill segment based on master volume intensity range<br>. Options:<p> 50 <ul style="margin: 0"> 51 <li><b>Use for masking:</b> set the selected intensity range as <dfn>Editable intensity range</dfn> and switch to Paint effect.</li> 52 <li><b>Apply:</b> set the previewed segmentation in the selected segment. Previous contents of the segment is overwritten.</li> 73 """Save current segment opacity and set it to zero 74 to temporarily hide the segment so that threshold preview 76 It also restores opacity of previously previewed segment. 77 Call restorePreviewedSegmentTransparency() to restore original 80 segmentationNode = self.scriptedEffect.parameterSetNode().GetSegmentationNode()
81 if not segmentationNode:
83 displayNode = segmentationNode.GetDisplayNode()
86 segmentID = self.scriptedEffect.parameterSetNode().GetSelectedSegmentID()
101 displayNode.SetSegmentOpacity2DFill(segmentID, 0)
102 displayNode.SetSegmentOpacity2DOutline(segmentID, 0)
105 """Restore previewed segment's opacity that was temporarily 106 made transparen by calling setCurrentSegmentTransparent().""" 107 segmentationNode = self.scriptedEffect.parameterSetNode().GetSegmentationNode()
108 if not segmentationNode:
110 displayNode = segmentationNode.GetDisplayNode()
122 self.
thresholdSliderLabel.setToolTip(
"Set the range of the background values that should be labeled.")
159 +
" Useful for iterating through all available methods.")
164 +
" Useful for iterating through all available methods.")
171 qSize = qt.QSizePolicy()
172 qSize.setHorizontalPolicy(qt.QSizePolicy.Expanding)
175 autoThresholdFrame = qt.QHBoxLayout()
181 self.scriptedEffect.addLabeledOptionsWidget(
"Automatic threshold:", autoThresholdFrame)
184 self.
useForPaintButton.setToolTip(
"Use specified intensity range for masking and switch to Paint effect.")
188 self.
applyButton.objectName = self.__class__.__name__ +
'Apply' 189 self.
applyButton.setToolTip(
"Fill selected segment in regions that are in the specified intensity range.")
190 self.scriptedEffect.addOptionsWidget(self.
applyButton)
203 return slicer.util.mainWindow().cursor
207 import vtkSegmentationCorePython
as vtkSegmentationCore
208 masterImageData = self.scriptedEffect.masterVolumeImageData()
210 lo, hi = masterImageData.GetScalarRange()
213 if (self.scriptedEffect.doubleParameter(
"MinimumThreshold") == self.scriptedEffect.doubleParameter(
"MaximumThreshold")):
215 self.scriptedEffect.setParameter(
"MinimumThreshold", lo+(hi-lo)*0.25)
216 self.scriptedEffect.setParameter(
"MaximumThreshold", hi)
228 self.scriptedEffect.setParameterDefault(
"MinimumThreshold", 0.)
229 self.scriptedEffect.setParameterDefault(
"MaximumThreshold", 0)
230 self.scriptedEffect.setParameterDefault(
"AutoThresholdMethod", METHOD_OTSU)
231 self.scriptedEffect.setParameterDefault(
"AutoThresholdMode", MODE_SET_LOWER_MAX)
235 self.
thresholdSlider.setMinimumValue(self.scriptedEffect.doubleParameter(
"MinimumThreshold"))
236 self.
thresholdSlider.setMaximumValue(self.scriptedEffect.doubleParameter(
"MaximumThreshold"))
250 self.scriptedEffect.setParameter(
"MinimumThreshold", self.
thresholdSlider.minimumValue)
251 self.scriptedEffect.setParameter(
"MaximumThreshold", self.
thresholdSlider.maximumValue)
255 self.scriptedEffect.setParameter(
"AutoThresholdMethod", autoThresholdMethod)
259 self.scriptedEffect.setParameter(
"AutoThresholdMode", autoThresholdMode)
268 parameterSetNode = self.scriptedEffect.parameterSetNode()
269 parameterSetNode.MasterVolumeIntensityMaskOn()
272 self.scriptedEffect.selectEffect(
"Paint")
290 autoThresholdMethod = self.scriptedEffect.parameter(
"AutoThresholdMethod")
291 autoThresholdMode = self.scriptedEffect.parameter(
"AutoThresholdMode")
295 if autoThresholdMethod == METHOD_HUANG:
297 elif autoThresholdMethod == METHOD_INTERMODES:
299 elif autoThresholdMethod == METHOD_ISO_DATA:
301 elif autoThresholdMethod == METHOD_KITTLER_ILLINGWORTH:
303 elif autoThresholdMethod == METHOD_LI:
305 elif autoThresholdMethod == METHOD_MAXIMUM_ENTROPY:
307 elif autoThresholdMethod == METHOD_MOMENTS:
309 elif autoThresholdMethod == METHOD_OTSU:
311 elif autoThresholdMethod == METHOD_RENYI_ENTROPY:
313 elif autoThresholdMethod == METHOD_SHANBHAG:
315 elif autoThresholdMethod == METHOD_TRIANGLE:
317 elif autoThresholdMethod == METHOD_YEN:
320 logging.error(
"Unknown AutoThresholdMethod {0}".format(autoThresholdMethod))
322 masterImageData = self.scriptedEffect.masterVolumeImageData()
328 masterVolumeMin, masterVolumeMax = masterImageData.GetScalarRange()
330 if autoThresholdMode == MODE_SET_UPPER:
331 self.scriptedEffect.setParameter(
"MaximumThreshold", computedThreshold)
332 elif autoThresholdMode == MODE_SET_LOWER:
333 self.scriptedEffect.setParameter(
"MinimumThreshold", computedThreshold)
334 elif autoThresholdMode == MODE_SET_MIN_UPPER:
335 self.scriptedEffect.setParameter(
"MinimumThreshold", masterVolumeMin)
336 self.scriptedEffect.setParameter(
"MaximumThreshold", computedThreshold)
337 elif autoThresholdMode == MODE_SET_LOWER_MAX:
338 self.scriptedEffect.setParameter(
"MinimumThreshold", computedThreshold)
339 self.scriptedEffect.setParameter(
"MaximumThreshold", masterVolumeMax)
341 logging.error(
"Unknown AutoThresholdMode {0}".format(autoThresholdMode))
346 import vtkSegmentationCorePython
as vtkSegmentationCore
347 masterImageData = self.scriptedEffect.masterVolumeImageData()
349 modifierLabelmap = self.scriptedEffect.defaultModifierLabelmap()
350 originalImageToWorldMatrix = vtk.vtkMatrix4x4()
351 modifierLabelmap.GetImageToWorldMatrix(originalImageToWorldMatrix)
353 min = self.scriptedEffect.doubleParameter(
"MinimumThreshold")
354 max = self.scriptedEffect.doubleParameter(
"MaximumThreshold")
356 self.scriptedEffect.saveStateForUndo()
359 thresh = vtk.vtkImageThreshold()
360 thresh.SetInputData(masterImageData)
361 thresh.ThresholdBetween(min, max)
363 thresh.SetOutValue(0)
364 thresh.SetOutputScalarType(modifierLabelmap.GetScalarType())
366 modifierLabelmap.DeepCopy(thresh.GetOutput())
368 logging.error(
'apply: Failed to threshold master volume!')
372 self.scriptedEffect.modifySelectedSegmentByLabelmap(modifierLabelmap, slicer.qSlicerSegmentEditorAbstractEffect.ModificationModeSet)
375 self.scriptedEffect.selectEffect(
"")
379 self.scriptedEffect.removeActor2D(sliceWidget, pipeline.actor)
386 layoutManager = slicer.app.layoutManager()
387 if layoutManager
is None:
391 for sliceViewName
in layoutManager.sliceViewNames():
392 sliceWidget = layoutManager.sliceWidget(sliceViewName)
393 if not self.scriptedEffect.segmentationDisplayableInView(sliceWidget.mrmlSliceNode()):
395 renderer = self.scriptedEffect.renderer(sliceWidget)
397 logging.error(
"setupPreviewDisplay: Failed to get renderer!")
405 self.scriptedEffect.addActor2D(sliceWidget, pipeline.actor)
410 min = self.scriptedEffect.doubleParameter(
"MinimumThreshold")
411 max = self.scriptedEffect.doubleParameter(
"MaximumThreshold")
414 segmentationNode = self.scriptedEffect.parameterSetNode().GetSegmentationNode()
415 if not segmentationNode:
418 displayNode = segmentationNode.GetDisplayNode()
419 if displayNode
is None:
420 logging.error(
"preview: Invalid segmentation display node!")
421 color = [0.5,0.5,0.5]
422 segmentID = self.scriptedEffect.parameterSetNode().GetSelectedSegmentID()
428 r,g,b = segmentationNode.GetSegmentation().GetSegment(segmentID).GetColor()
433 pipeline.lookupTable.SetTableValue(1, r, g, b, opacity)
434 sliceLogic = sliceWidget.sliceLogic()
435 backgroundLogic = sliceLogic.GetBackgroundLayer()
436 pipeline.thresholdFilter.SetInputConnection(backgroundLogic.GetReslice().GetOutputPort())
437 pipeline.thresholdFilter.ThresholdBetween(min, max)
438 pipeline.actor.VisibilityOn()
439 sliceWidget.sliceView().scheduleRender()
451 """ Visualization objects and pipeline for each slice view for threshold preview 471 self.
dummyImage.AllocateScalars(vtk.VTK_UNSIGNED_INT, 1)
474 self.
actor.VisibilityOff()
476 self.
mapper.SetColorWindow(255)
477 self.
mapper.SetColorLevel(128)
485 METHOD_HUANG =
'HUANG' 486 METHOD_INTERMODES =
'INTERMODES' 487 METHOD_ISO_DATA =
'ISO_DATA' 488 METHOD_KITTLER_ILLINGWORTH =
'KITTLER_ILLINGWORTH' 490 METHOD_MAXIMUM_ENTROPY =
'MAXIMUM_ENTROPY' 491 METHOD_MOMENTS =
'MOMENTS' 493 METHOD_RENYI_ENTROPY =
'RENYI_ENTROPY' 494 METHOD_SHANBHAG =
'SHANBHAG' 495 METHOD_TRIANGLE =
'TRIANGLE' 498 MODE_SET_UPPER =
'SET_UPPER' 499 MODE_SET_LOWER =
'SET_LOWER' 500 MODE_SET_MIN_UPPER =
'SET_MIN_UPPER' 501 MODE_SET_LOWER_MAX =
'SET_LOWER_MAX'
def updateMRMLFromGUI(self)
def onSelectNextAutoThresholdMethod(self)
def setMRMLDefaults(self)
def onThresholdValuesChanged(self, min, max)
def processViewNodeEvents(self, callerViewNode, eventId, viewWidget)
def onSelectedAutoThresholdMethod(self)
def setupOptionsFrame(self)
def clearPreviewDisplay(self)
selectPreviousAutoThresholdButton
def autoThreshold(self, autoThresholdMethod, autoThresholdMode)
def restorePreviewedSegmentTransparency(self)
def setupPreviewDisplay(self)
def __init__(self, scriptedEffect)
def masterVolumeNodeChanged(self)
def onAutoThreshold(self)
def updateGUIFromMRML(self)
selectNextAutoThresholdButton
def createCursor(self, widget)
def setCurrentSegmentTransparent(self)
autoThresholdModeSelectorComboBox
def processInteractionEvents(self, callerInteractor, eventId, viewWidget)
def onSelectPreviousAutoThresholdMethod(self)
autoThresholdMethodSelectorComboBox