slicer

This module sets up root logging and loads the Slicer library modules into its namespace.

Warning

These following attributes are only set in the Python environment embedded in the Slicer main application SlicerApp-real (launched by the Slicer executable):

This means that they are not set in the Python environment of python-real (launched by the PythonSlicer executable).

slicer.app

This is set to the singleton instance of qSlicerApplication:

>>> slicer.app
qSlicerApplication (qSlicerApplication at: 0x7ffd066a07a0)

Warning

This attribute is only set in the Python environment embedded in the Slicer main application.

slicer.mrmlScene

This is set to the instance of the MRML Scene:

>>> slicer.mrmlScene
<MRMLCore.vtkMRMLScene(0x2797cb0) at 0x7fbfedb82520>

>>> slicer.mrmlScene == slicer.app.mrmlScene()
True

Warning

This attribute is only set in the Python environment embedded in the Slicer main application.

slicer.modules

This object provides access to all instantiated Slicer modules.

For each instantiated Slicer module, an attribute named after the lower-cased Slicer module name (slicer.module.<modulename>) is associated with the corresponding instance of qSlicerAbstractCoreModule.

For example:

>>> slicer.modules.volumes
qSlicerVolumesModule (qSlicerVolumesModule at: 0x4869000)

>>> slicer.modules.volumes.inherits("qSlicerAbstractModule")
True

>>> slicer.modules.volumes.inherits("qSlicerLoadableModule")
True

Warning

These attributes are only set in the Python environment embedded in the Slicer main application.

Additionally for all scripted modules (qSlicerScriptedLoadableModule), these additional attributes are also set:

  • the attribute <moduleName>Instance is set to the corresponding instance of ScriptedLoadableModule.

    For example:

    >>> slicer.modules.VectorToScalarVolumeInstance
    <VectorToScalarVolume.VectorToScalarVolume object at 0x7fbfc1d1aa60>
    
    >>> isinstance(slicer.modules.VectorToScalarVolumeInstance, slicer.ScriptedLoadableModule.ScriptedLoadableModule)
    True
    
  • the attribute <moduleName>Widget is set to the corresponding instance of ScriptedLoadableModuleWidget.

    For example:

    >>> slicer.util.selectModule(slicer.modules.vectortoscalarvolume)
    
    >>> slicer.modules.VectorToScalarVolumeWidget
    <VectorToScalarVolume.VectorToScalarVolumeWidget object at 0x7fbfbc055cd0>
    
    >>> isinstance(slicer.modules.VectorToScalarVolumeWidget, slicer.ScriptedLoadableModule.ScriptedLoadableModuleWidget)
    True
    

    Note

    The <moduleName>Widget attribute is:

slicer.moduleNames

This object provides access to all instantiated Slicer module names.

The object attributes are the Slicer modules names, the associated value is the module name.

For example:

>>> slicer.moduleNames.Volumes
'Volumes'
>>> slicer.moduleNames.VectorToScalarVolume
'VectorToScalarVolume'

Warning

These attributes are only set in the Python environment embedded in the Slicer main application.

slicer.cli

This module is a place holder for convenient functions allowing to interact with CLI.

slicer.cli.cancel(node)
slicer.cli.createNode(cliModule, parameters=None)

Creates a new vtkMRMLCommandLineModuleNode for a specific module, with optional parameters

slicer.cli.run(module, node=None, parameters=None, wait_for_completion=False, delete_temporary_files=True, update_display=True)

Runs a CLI, optionally given a node with optional parameters, returning back the node (or the new one if created) node: existing parameter node (None by default) parameters: dictionary of parameters for cli (None by default) wait_for_completion: block if True (False by default) delete_temporary_files: remove temp files created during execution (True by default) update_display: show output nodes after completion

slicer.cli.runSync(module, node=None, parameters=None, delete_temporary_files=True, update_display=True)

Run a CLI synchronously, optionally given a node with optional parameters, returning the node (or the new one if created) node: existing parameter node (None by default) parameters: dictionary of parameters for cli (None by default) delete_temporary_files: remove temp files created during execution (True by default) update_display: show output nodes after completion

slicer.cli.setNodeParameters(node, parameters)

Sets parameters for a vtkMRMLCommandLineModuleNode given a dictionary of (parameterName, parameterValue) pairs For vectors: provide a list, tuple or comma-separated string For enumerations, provide the single enumeration value For files and directories, provide a string For images, geometry, points and regions, provide a vtkMRMLNode

slicer.logic

slicer.ScriptedLoadableModule

class slicer.ScriptedLoadableModule.ScriptedLoadableModule(parent)

Bases: object

Return string that can be inserted into the application help text that contains link to the module’s documentation in current Slicer version’s documentation. The text is “For more information see the online documentation.” If docPage is not specified then the link points to URL returned by slicer.app.moduleDocumentationUrl().

resourcePath(filename)

Return the absolute path of the module Resources directory.

runTest(msec=100, **kwargs)
Parameters:

msec – delay to associate with ScriptedLoadableModuleTest.delayDisplay().

class slicer.ScriptedLoadableModule.ScriptedLoadableModuleLogic(parent=None)

Bases: object

createParameterNode()

Create a new parameter node The node is of vtkMRMLScriptedModuleNode class. Module name is added as an attribute to allow filtering in node selector widgets (attribute name: ModuleName, attribute value: the module’s name). This method can be overridden in derived classes to create a default parameter node with all parameter values set to their default.

getAllParameterNodes()

Return a list of all parameter nodes for this module Multiple parameter nodes are useful for storing multiple parameter sets in a single scene.

getParameterNode()

Return the first available parameter node for this module If no parameter nodes are available for this module then a new one is created.

class slicer.ScriptedLoadableModule.ScriptedLoadableModuleTest(*args, **kwargs)

Bases: TestCase

Base class for module tester class. Setting messageDelay to something small, like 50ms allows faster development time.

delayDisplay(message, requestedDelay=None, msec=None)

Display messages to the user/tester during testing.

By default, the delay is 50ms.

The function accepts the keyword arguments requestedDelay or msec. If both are specified, the value associated with msec is used.

This method can be temporarily overridden to allow tests running with longer or shorter message display time.

Displaying a dialog and waiting does two things: 1) it lets the event loop catch up to the state of the test so that rendering and widget updates have all taken place before the test continues and 2) it shows the user/developer/tester the state of the test so that we’ll know when it breaks.

Note: Information that might be useful (but not important enough to show to the user) can be logged using logging.info() function (printed to console and application log) or logging.debug() function (printed to application log only). Error messages should be logged by logging.error() function and displayed to user by slicer.util.errorDisplay function.

runTest()

Run a default selection of tests here.

takeScreenshot(name, description, type=-1)

Take a screenshot of the selected viewport and store as and annotation snapshot node. Convenience method for automated testing.

If self.enableScreenshots is False then only a message is displayed but screenshot is not stored. Screenshots are scaled by self.screenshotScaleFactor.

Parameters:
  • name – snapshot node name

  • description – description of the node

  • type – which viewport to capture. If not specified then captures the entire window. Valid values: slicer.qMRMLScreenShotDialog.FullLayout, slicer.qMRMLScreenShotDialog.ThreeD, slicer.qMRMLScreenShotDialog.Red, slicer.qMRMLScreenShotDialog.Yellow, slicer.qMRMLScreenShotDialog.Green.

class slicer.ScriptedLoadableModule.ScriptedLoadableModuleWidget(parent=None)

Bases: object

cleanup()

Override this function to implement module widget specific cleanup.

It is invoked when the signal qSlicerModuleManager::moduleAboutToBeUnloaded(QString) corresponding to the current module is emitted and just before a module is effectively unloaded.

onEditSource()
onReload()

Reload scripted module widget representation.

onReloadAndTest(**kwargs)

Reload scripted module widget representation and call ScriptedLoadableModuleTest.runTest() passing kwargs.

onTest(**kwargs)

Tests scripted module widget, can be used when reload and test doesn’t work, calls ScriptedLoadableModuleTest.runTest() passing kwargs.

resourcePath(filename)

Return the absolute path of the module Resources directory.

setup()
setupDeveloperSection()

slicer.testing

slicer.testing.exitFailure(message='')
slicer.testing.exitSuccess()
slicer.testing.runUnitTest(path, testname)

slicer.util

slicer.util.DATA_STORE_URL = 'https://github.com/Slicer/SlicerDataStore/releases/download/'

Base URL for downloading data from Slicer Data Store. Data store contains atlases, registration case library images, and various sample data sets.

Datasets can be downloaded using URL of the form DATA_STORE_URL + "SHA256/" + sha256ofDataSet

exception slicer.util.MRMLNodeNotFoundException

Bases: Exception

Exception raised when a requested MRML node was not found.

class slicer.util.MessageDialog(message, show=True, logLevel=None)

Bases: object

class slicer.util.NodeModify(node)

Bases: object

Context manager to conveniently compress mrml node modified event.

class slicer.util.RenderBlocker

Bases: object

Context manager to conveniently pause and resume view rendering. This makes sure that we are not displaying incomplete states to the user. Pausing the views can be useful to improve performance and ensure consistency by skipping all rendering calls until the current code block has completed.

Code blocks such as:

try:
  slicer.app.pauseRender()
  # Do things
finally:
  slicer.app.resumeRender()

Can be written as:

with slicer.util.RenderBlocker():
  # Do things
slicer.util.TESTING_DATA_URL = 'https://github.com/Slicer/SlicerTestingData/releases/download/'

Base URL for downloading testing data.

Datasets can be downloaded using URL of the form TESTING_DATA_URL + "SHA256/" + sha256ofDataSet

class slicer.util.VTKObservationMixin

Bases: object

property Observations
addObserver(obj, event, method, group='none', priority=0.0)
getObserver(obj, event, method, default=None)
hasObserver(obj, event, method)
observer(event, method, default=None)
removeObserver(obj, event, method)
removeObservers(method=None)
class slicer.util.WaitCursor(show=True)

Bases: object

Display a wait cursor while the code in the context manager is being run.

Parameters:

show – If show is False, no wait cursor is shown.

import time

n = 2
with slicer.util.MessageDialog(f'Sleeping for {n} seconds...'):
  with slicer.util.WaitCursor():
    time.sleep(n)
slicer.util.addParameterEditWidgetConnections(parameterEditWidgets, updateParameterNodeFromGUI)

Add connections to get notification of a widget change.

The function is useful for calling updateParameterNodeFromGUI method in scripted module widgets.

Note

Not all widget classes are supported yet. Report any missing classes at https://discourse.slicer.org.

Example:

class SurfaceToolboxWidget(ScriptedLoadableModuleWidget, VTKObservationMixin):
  ...
  def setup(self):
    ...
    self.parameterEditWidgets = [
      (self.ui.inputModelSelector, "inputModel"),
      (self.ui.outputModelSelector, "outputModel"),
      (self.ui.decimationButton, "decimation"),
      ...]
    slicer.util.addParameterEditWidgetConnections(self.parameterEditWidgets, self.updateParameterNodeFromGUI)

  def updateGUIFromParameterNode(self, caller=None, event=None):
    if self._parameterNode is None or self._updatingGUIFromParameterNode:
      return
    self._updatingGUIFromParameterNode = True
    slicer.util.updateParameterEditWidgetsFromNode(self.parameterEditWidgets, self._parameterNode)
    self._updatingGUIFromParameterNode = False

  def updateParameterNodeFromGUI(self, caller=None, event=None):
    if self._parameterNode is None or self._updatingGUIFromParameterNode:
      return
    wasModified = self._parameterNode.StartModify()  # Modify all properties in a single batch
    slicer.util.updateNodeFromParameterEditWidgets(self.parameterEditWidgets, self._parameterNode)
    self._parameterNode.EndModify(wasModified)
slicer.util.addVolumeFromArray(narray, ijkToRAS=None, name=None, nodeClassName=None)

Create a new volume node from content of a numpy array and add it to the scene.

Voxels values are deep-copied, therefore if the numpy array is modified after calling this method, voxel values in the volume node will not change.

Parameters:
  • narray – numpy array containing volume voxels.

  • ijkToRAS – 4x4 numpy array or vtk.vtkMatrix4x4 that defines mapping from IJK to RAS coordinate system (specifying origin, spacing, directions)

  • name – volume node name

  • nodeClassName – type of created volume, default: vtkMRMLScalarVolumeNode. Use vtkMRMLLabelMapVolumeNode for labelmap volume, vtkMRMLVectorVolumeNode for vector volume.

Returns:

created new volume node

Example:

# create zero-filled volume
import numpy as np
volumeNode = slicer.util.addVolumeFromArray(np.zeros((30, 40, 50)))

Example:

# create labelmap volume filled with voxel value of 120
import numpy as np
volumeNode = slicer.util.addVolumeFromArray(np.ones((30, 40, 50), 'int8') * 120,
  np.diag([0.2, 0.2, 0.5, 1.0]), nodeClassName="vtkMRMLLabelMapVolumeNode")
slicer.util.addVolumeFromITKImage(itkImage, name=None, nodeClassName=None, deepCopy=True)

Create a new volume node from content of an ITK image and add it to the scene.

By default, voxels values are deep-copied, therefore if the ITK image is modified after calling this method, voxel values in the volume node will not change.

See updateVolumeFromITKImage() to understand memory ownership.

Parameters:
  • itkImage – ITK image containing volume voxels.

  • name – volume node name

  • nodeClassName – type of created volume, default: vtkMRMLScalarVolumeNode. Use vtkMRMLLabelMapVolumeNode for labelmap volume, vtkMRMLVectorVolumeNode for vector volume.

  • deepCopy – Whether voxels values are deep-copied or not.

Returns:

created new volume node

slicer.util.array(pattern='', index=0)

Return the array you are “most likely to want” from the indexth

MRML node that matches the pattern.

Raises:

RuntimeError – if the node cannot be accessed as an array.

Warning

Meant to be used in the python console for quick debugging/testing.

More specific API should be used in scripts to be sure you get exactly what you want, such as arrayFromVolume(), arrayFromModelPoints(), and arrayFromGridTransform().

slicer.util.arrayFromGridTransform(gridTransformNode)

Return voxel array from transform node as numpy array.

Vector values are not copied. Values in the transform node can be modified by changing values in the numpy array. After all modifications has been completed, call arrayFromGridTransformModified().

Warning

Important: memory area of the returned array is managed by VTK, therefore values in the array may be changed, but the array must not be reallocated. See arrayFromVolume() for details.

slicer.util.arrayFromGridTransformModified(gridTransformNode)

Indicate that modification of a numpy array returned by arrayFromGridTransform() has been completed.

slicer.util.arrayFromMarkupsControlPointData(markupsNode, arrayName)

Return control point data array of a markups node as numpy array.

Warning

Important: memory area of the returned array is managed by VTK, therefore values in the array may be changed, but the array must not be reallocated. See arrayFromVolume() for details.

slicer.util.arrayFromMarkupsControlPointDataModified(markupsNode, arrayName)

Indicate that modification of a numpy array returned by arrayFromMarkupsControlPointData() has been completed.

slicer.util.arrayFromMarkupsControlPoints(markupsNode, world=False)

Return control point positions of a markups node as rows in a numpy array (of size Nx3).

Parameters:

world – if set to True then the control points coordinates are returned in world coordinate system (effect of parent transform to the node is applied).

The returned array is just a copy and so any modification in the array will not affect the markup node.

To modify markup control points based on a numpy array, use updateMarkupsControlPointsFromArray().

slicer.util.arrayFromMarkupsCurveData(markupsNode, arrayName, world=False)

Return curve measurement results from a markups node as a numpy array.

Parameters:
  • markupsNode – node to get the curve point data from.

  • arrayName – array name to get (for example Curvature)

  • world – if set to True then the point coordinates are returned in world coordinate system (effect of parent transform to the node is applied).

Raises:

ValueError – in case of failure

Warning

  • Not all array may be available in both node and world coordinate systems. For example, Curvature is only computed for the curve in world coordinate system.

  • The returned array is not intended to be modified, as arrays are expected to be written only by measurement objects.

slicer.util.arrayFromMarkupsCurvePoints(markupsNode, world=False)

Return interpolated curve point positions of a markups node as rows in a numpy array (of size Nx3).

Parameters:

world – if set to True then the point coordinates are returned in world coordinate system (effect of parent transform to the node is applied).

The returned array is just a copy and so any modification in the array will not affect the markup node.

slicer.util.arrayFromModelCellData(modelNode, arrayName)

Return cell data array of a model node as numpy array.

Warning

Important: memory area of the returned array is managed by VTK, therefore values in the array may be changed, but the array must not be reallocated. See arrayFromVolume() for details.

slicer.util.arrayFromModelCellDataModified(modelNode, arrayName)

Indicate that modification of a numpy array returned by arrayFromModelCellData() has been completed.

slicer.util.arrayFromModelPointData(modelNode, arrayName)

Return point data array of a model node as numpy array.

Warning

Important: memory area of the returned array is managed by VTK, therefore values in the array may be changed, but the array must not be reallocated. See arrayFromVolume() for details.

slicer.util.arrayFromModelPointDataModified(modelNode, arrayName)

Indicate that modification of a numpy array returned by arrayFromModelPointData() has been completed.

slicer.util.arrayFromModelPoints(modelNode)

Return point positions of a model node as numpy array.

Point coordinates can be modified by modifying the numpy array. After all modifications has been completed, call arrayFromModelPointsModified().

Warning

Important: memory area of the returned array is managed by VTK, therefore values in the array may be changed, but the array must not be reallocated. See arrayFromVolume() for details.

slicer.util.arrayFromModelPointsModified(modelNode)

Indicate that modification of a numpy array returned by arrayFromModelPoints() has been completed.

slicer.util.arrayFromModelPolyIds(modelNode)

Return poly id array of a model node as numpy array.

These ids are the following format: [ n(0), i(0,0), i(0,1), … i(0,n(00),…, n(j), i(j,0), … i(j,n(j))…] where n(j) is the number of vertices in polygon j and i(j,k) is the index into the vertex array for vertex k of poly j.

As described here: https://vtk.org/wp-content/uploads/2015/04/file-formats.pdf

Typically in Slicer n(j) will always be 3 because a model node’s polygons will be triangles.

Warning

Important: memory area of the returned array is managed by VTK, therefore values in the array may be changed, but the array must not be reallocated. See arrayFromVolume() for details.

slicer.util.arrayFromSegment(segmentationNode, segmentId)

Get segment as numpy array.

Warning

Important: binary labelmap representation may be shared between multiple segments.

Deprecated since version 4.13.0: Use arrayFromSegmentBinaryLabelmap to access a copy of the binary labelmap that will not modify the original labelmap.” Use arrayFromSegmentInternalBinaryLabelmap to access a modifiable internal labelmap representation that may be shared” between multiple segments.

slicer.util.arrayFromSegmentBinaryLabelmap(segmentationNode, segmentId, referenceVolumeNode=None)

Return voxel array of a segment’s binary labelmap representation as numpy array.

Parameters:
  • segmentationNode – source segmentation node.

  • segmentId – ID of the source segment. Can be determined from segment name by calling segmentationNode.GetSegmentation().GetSegmentIdBySegmentName(segmentName).

  • referenceVolumeNode – a volume node that determines geometry (origin, spacing, axis directions, extents) of the array. If not specified then the volume that was used for setting the segmentation’s geometry is used as reference volume.

Raises:

RuntimeError – in case of failure

Voxels values are copied, therefore changing the returned numpy array has no effect on the source segmentation. The modified array can be written back to the segmentation by calling updateSegmentBinaryLabelmapFromArray().

To get voxels of a segment as a modifiable numpy array, you can use arrayFromSegmentInternalBinaryLabelmap().

slicer.util.arrayFromSegmentInternalBinaryLabelmap(segmentationNode, segmentId)

Return voxel array of a segment’s binary labelmap representation as numpy array.

Voxels values are not copied. The labelmap containing the specified segment may be a shared labelmap containing multiple segments.

To get and modify the array for a single segment, calling:

segmentationNode->GetSegmentation()->SeparateSegment(segmentId)

will transfer the segment from a shared labelmap into a new layer.

Layers can be merged by calling:

segmentationNode->GetSegmentation()->CollapseBinaryLabelmaps()

If binary labelmap is the source representation then voxel values in the volume node can be modified by changing values in the numpy array. After all modifications has been completed, call:

segmentationNode.GetSegmentation().GetSegment(segmentID).Modified()

Warning

Important: memory area of the returned array is managed by VTK, therefore values in the array may be changed, but the array must not be reallocated. See arrayFromVolume() for details.

slicer.util.arrayFromTableColumn(tableNode, columnName)

Return values of a table node’s column as numpy array.

Values can be modified by modifying the numpy array. After all modifications has been completed, call arrayFromTableColumnModified().

Warning

Important: memory area of the returned array is managed by VTK, therefore values in the array may be changed, but the array must not be reallocated. See arrayFromVolume() for details.

slicer.util.arrayFromTableColumnModified(tableNode, columnName)

Indicate that modification of a numpy array returned by arrayFromTableColumn() has been completed.

slicer.util.arrayFromTransformMatrix(transformNode, toWorld=False)

Return 4x4 transformation matrix as numpy array.

Parameters:

toWorld – if set to True then the transform to world coordinate system is returned (effect of parent transform to the node is applied), otherwise transform to parent transform is returned.

Returns:

numpy array

Raises:

RuntimeError – in case of failure

The returned array is just a copy and so any modification in the array will not affect the transform node.

To set transformation matrix from a numpy array, use updateTransformMatrixFromArray().

slicer.util.arrayFromVTKMatrix(vmatrix)

Return vtkMatrix4x4 or vtkMatrix3x3 elements as numpy array.

Raises:

RuntimeError – in case of failure

The returned array is just a copy and so any modification in the array will not affect the input matrix. To set VTK matrix from a numpy array, use vtkMatrixFromArray() or updateVTKMatrixFromArray().

slicer.util.arrayFromVolume(volumeNode)

Return voxel array from volume node as numpy array.

Voxels values are not copied. Voxel values in the volume node can be modified by changing values in the numpy array. After all modifications has been completed, call arrayFromVolumeModified().

Raises:

RuntimeError – in case of failure

Warning

Memory area of the returned array is managed by VTK, therefore values in the array may be changed, but the array must not be reallocated (change array size, shallow-copy content from other array most likely causes application crash). To allow arbitrary numpy operations on a volume array:

  1. Make a deep-copy of the returned VTK-managed array using numpy.copy().

  2. Perform any computations using the copied array.

  3. Write results back to the image data using updateVolumeFromArray().

slicer.util.arrayFromVolumeModified(volumeNode)

Indicate that modification of a numpy array returned by arrayFromVolume() has been completed.

class slicer.util.chdir(path)

Bases: object

Non thread-safe context manager to change the current working directory.

Note

Available in Python 3.11 as contextlib.chdir and adapted from https://github.com/python/cpython/pull/28271

Available in CTK as ctkScopedCurrentDir C++ class

slicer.util.childWidgetVariables(widget)

Get child widgets as attributes of an object.

Each named child widget is accessible as an attribute of the returned object, with the attribute name matching the child widget name. This function provides convenient access to widgets in a loaded UI file.

Example:

uiWidget = slicer.util.loadUI(myUiFilePath)
self.ui = slicer.util.childWidgetVariables(uiWidget)
self.ui.inputSelector.setMRMLScene(slicer.mrmlScene)
self.ui.outputSelector.setMRMLScene(slicer.mrmlScene)
slicer.util.clickAndDrag(widget, button='Left', start=(10, 10), end=(10, 40), steps=20, modifiers=[])

Send synthetic mouse events to the specified widget (qMRMLSliceWidget or qMRMLThreeDView)

Parameters:
  • button – “Left”, “Middle”, “Right”, or “None” start, end : window coordinates for action

  • steps – number of steps to move in, if <2 then mouse jumps to the end position

  • modifiers – list containing zero or more of “Shift” or “Control”

Raises:

RuntimeError – in case of failure

Hint

For generating test data you can use this snippet of code:

layoutManager = slicer.app.layoutManager()
threeDView = layoutManager.threeDWidget(0).threeDView()
style = threeDView.interactorStyle()
interactor = style.GetInteractor()

def onClick(caller,event):
    print(interactor.GetEventPosition())

interactor.AddObserver(vtk.vtkCommand.LeftButtonPressEvent, onClick)
slicer.util.computeChecksum(algo, filePath)

Compute digest of filePath using algo.

Supported hashing algorithms are SHA256, SHA512, and MD5.

It internally reads the file by chunk of 8192 bytes.

Raises:
  • ValueError – if algo is unknown.

  • IOError – if filePath does not exist.

slicer.util.confirmOkCancelDisplay(text, windowTitle=None, parent=None, **kwargs)

Display a confirmation popup. Return if confirmed with OK.

When the application is running in testing mode (slicer.app.testingEnabled() == True), the popup is skipped and True (“Ok”) is returned, with a message being logged to indicate this.

slicer.util.confirmRetryCloseDisplay(text, windowTitle=None, parent=None, **kwargs)

Display an error popup asking whether to retry, logging the text at error level. Return if confirmed with Retry.

When the application is running in testing mode (slicer.app.testingEnabled() == True), the popup is skipped and False (“Close”) is returned, with a message being logged to indicate this.

slicer.util.confirmYesNoDisplay(text, windowTitle=None, parent=None, **kwargs)

Display a confirmation popup. Return if confirmed with Yes.

When the application is running in testing mode (slicer.app.testingEnabled() == True), the popup is skipped and True (“Yes”) is returned, with a message being logged to indicate this.

slicer.util.createProgressDialog(parent=None, value=0, maximum=100, labelText='', windowTitle='Processing...', **kwargs)

Display a modal QProgressDialog.

Go to QProgressDialog documentation to learn about the available keyword arguments.

Examples:

# Prevent progress dialog from automatically closing
progressbar = createProgressDialog(autoClose=False)

# Update progress value
progressbar.value = 50

# Update label text
progressbar.labelText = "processing XYZ"
slicer.util.dataframeFromMarkups(markupsNode)

Convert markups node content to pandas dataframe.

Markups content is copied. Therefore, changes in markups node do not affect the dataframe, and dataframe changes do not affect the original markups node.

slicer.util.dataframeFromTable(tableNode)

Convert table node content to pandas dataframe.

Table content is copied. Therefore, changes in table node do not affect the dataframe, and dataframe changes do not affect the original table node.

slicer.util.delayDisplay(message, autoCloseMsec=1000, parent=None, **kwargs)

Display an information message in a popup window for a short time.

If autoCloseMsec < 0 then the window is not closed until the user clicks on it

If 0 <= autoCloseMsec < 400 then only slicer.app.processEvents() is called.

If autoCloseMsec >= 400 then the window is closed after waiting for autoCloseMsec milliseconds

slicer.util.displayPythonShell(display=True)

Show the Python console while the code in the context manager is being run.

The console stays visible only if it was visible already.

Parameters:

display – If show is False, the context manager has no effect.

with slicer.util.displayPythonShell():
  slicer.util.pip_install('nibabel')
slicer.util.downloadAndExtractArchive(url, archiveFilePath, outputDir, expectedNumberOfExtractedFiles=None, numberOfTrials=3, checksum=None)

Downloads an archive from url as archiveFilePath, and extracts it to outputDir.

This combined function tests the success of the download by the extraction step, and re-downloads if extraction failed.

If specified, the checksum is used to verify that the downloaded file is the expected one. It must be specified as <algo>:<digest>. For example, SHA256:cc211f0dfd9a05ca3841ce1141b292898b2dd2d3f08286affadf823a7e58df93.

slicer.util.downloadFile(url, targetFilePath, checksum=None, reDownloadIfChecksumInvalid=True)

Download url to local storage as targetFilePath

Target file path needs to indicate the file name and extension as well

If specified, the checksum is used to verify that the downloaded file is the expected one. It must be specified as <algo>:<digest>. For example, SHA256:cc211f0dfd9a05ca3841ce1141b292898b2dd2d3f08286affadf823a7e58df93.

slicer.util.errorDisplay(text, windowTitle=None, parent=None, standardButtons=None, **kwargs)

Display an error popup.

If there is no main window, or if the application is running in testing mode (slicer.app.testingEnabled() == True), then the text is only logged (at error level).

slicer.util.exit(status=0)

Exits the application with the specified exit code.

The method does not stop the process immediately but lets pending events to be processed. If exit() is called again while processing pending events, the error code will be overwritten.

To make the application exit immediately, this code can be used.

..warning:

Forcing the application to exit may result in
improperly released files and other resources.
import sys
sys.exit(status)
slicer.util.exportNode(node, filename, properties={}, world=False)

Export ‘node’ data into ‘filename’.

If world is set to True then the node will be exported in the world coordinate system (equivalent to hardening the transform before exporting).

This method is different from saveNode in that it does not modify any existing storage node and therefore does not change the filename or filetype that is used when saving the scene.

slicer.util.extractAlgoAndDigest(checksum)

Given a checksum string formatted as <algo>:<digest> returns the tuple (algo, digest).

<algo> is expected to be SHA256, SHA512, or MD5. <digest> is expected to be the full length hexadecimal digest.

Raises:

ValueError – if checksum is incorrectly formatted.

slicer.util.extractArchive(archiveFilePath, outputDir, expectedNumberOfExtractedFiles=None)

Extract file archiveFilePath into folder outputDir.

Number of expected files unzipped may be specified in expectedNumberOfExtractedFiles. If folder contains the same number of files as expected (if specified), then it will be assumed that unzipping has been successfully done earlier.

slicer.util.findChild(widget, name)

Convenience method to access a widget by its name.

Raises:

RuntimeError – if the widget with the given name does not exist.

slicer.util.findChildren(widget=None, name='', text='', title='', className='')

Return a list of child widgets that meet all the given criteria.

If no criteria are provided, the function will return all widgets descendants. If no widget is provided, slicer.util.mainWindow() is used.

Parameters:
  • widget – parent widget where the widgets will be searched

  • name – name attribute of the widget

  • text – text attribute of the widget

  • title – title attribute of the widget

  • className – className() attribute of the widget

Returns:

list with all the widgets that meet all the given criteria.

slicer.util.forceRenderAllViews()

Force rendering of all views

slicer.util.getFilesInDirectory(directory, absolutePath=True)

Collect all files in a directory and its subdirectories in a list.

slicer.util.getFirstNodeByClassByName(className, name, scene=None)

Return the first node in the scene that matches the specified node name and node class.

slicer.util.getFirstNodeByName(name, className=None)

Get the first MRML node that name starts with the specified name.

Optionally specify a classname that must also match.

slicer.util.getModule(moduleName)

Get module object from module name.

Returns:

module object

Raises:

RuntimeError – in case of failure (no such module).

slicer.util.getModuleGui(module)

Get module widget.

Deprecated since version 4.13.0: Use the universal getModuleWidget() function instead.

slicer.util.getModuleLogic(module)

Get module logic object.

Module logic allows a module to use features offered by another module.

Parameters:

module – module name or module object

Returns:

module logic object

Raises:

RuntimeError – if the module does not have widget.

slicer.util.getModuleWidget(module)

Return module widget (user interface) object for a module.

Parameters:

module – module name or module object

Returns:

module widget object

Raises:

RuntimeError – if the module does not have widget.

slicer.util.getNewModuleGui(module)

Create new module widget.

Deprecated since version 4.13.0: Use the universal getNewModuleWidget() function instead.

slicer.util.getNewModuleWidget(module)

Create new module widget instance.

In general, not recommended, as module widget may be developed expecting that there is only a single instance of this widget. Instead, of instantiating a complete module GUI, it is recommended to create only selected widgets that are used in the module GUI.

Parameters:

module – module name or module object

Returns:

module widget object

Raises:

RuntimeError – if the module does not have widget.

slicer.util.getNode(pattern='*', index=0, scene=None)

Return the indexth node where name or id matches pattern.

By default, pattern is a wildcard and it returns the first node associated with slicer.mrmlScene.

Raises:

MRMLNodeNotFoundException – if no node is found that matches the specified pattern.

slicer.util.getNodes(pattern='*', scene=None, useLists=False)

Return a dictionary of nodes where the name or id matches the pattern.

By default, pattern is a wildcard and it returns all nodes associated with slicer.mrmlScene.

If multiple node share the same name, using useLists=False (default behavior) returns only the last node with that name. If useLists=True, it returns a dictionary of lists of nodes.

slicer.util.getNodesByClass(className, scene=None)

Return all nodes in the scene of the specified class.

slicer.util.getSubjectHierarchyItemChildren(parentItem=None, recursive=False)

Convenience method to get children of a subject hierarchy item.

Parameters:
  • parentItem (vtkIdType) – Item for which to get children for. If omitted or None then use scene item (i.e. get all items)

  • recursive (bool) – Whether the query is recursive. False by default

Returns:

List of child item IDs

slicer.util.importClassesFromDirectory(directory, dest_module_name, type_info, filematch='*')
slicer.util.importModuleObjects(from_module_name, dest_module_name, type_info)

Import object of type ‘type_info’ (str or type) from module identified by ‘from_module_name’ into the module identified by ‘dest_module_name’.

slicer.util.importQtClassesFromDirectory(directory, dest_module_name, filematch='*')
slicer.util.importVTKClassesFromDirectory(directory, dest_module_name, filematch='*')
slicer.util.infoDisplay(text, windowTitle=None, parent=None, standardButtons=None, **kwargs)

Display popup with a info message.

If there is no main window, or if the application is running in testing mode (slicer.app.testingEnabled() == True), then the text is only logged (at info level).

slicer.util.itkImageFromVolume(volumeNode)

Return ITK image from volume node.

Voxels values are not copied. Voxel values in the volume node can be modified by changing values in the ITK image. After all modifications has been completed, call itkImageFromVolumeModified().

Warning

Important: Memory area of the returned ITK image is managed by VTK (through the vtkImageData object stored in the MRML volume node), therefore values in the Voxel values in the ITK image may be changed, but the ITK image must not be reallocated.

slicer.util.itkImageFromVolumeModified(volumeNode)

Indicate that modification of a ITK image returned by itkImageFromVolume() (or associated with a volume node using updateVolumeFromITKImage()) has been completed.

slicer.util.launchConsoleProcess(args, useStartupEnvironment=True, updateEnvironment=None, cwd=None)

Launch a process. Hiding the console and captures the process output.

The console window is hidden when running on Windows.

Parameters:
  • args – executable name, followed by command-line arguments

  • useStartupEnvironment – launch the process in the original environment as the original Slicer process

  • updateEnvironment – map containing optional additional environment variables (existing variables are overwritten)

  • cwd – current working directory

Returns:

process object.

This method is typically used together with logProcessOutput() to wait for the execution to complete and display the process output in the application log:

proc = slicer.util.launchConsoleProcess(args)
slicer.util.logProcessOutput(proc)
slicer.util.loadAnnotationFiducial(filename, returnNode=False)

Load node from file.

Parameters:
  • filename – full path of the file to load.

  • returnNode – Deprecated.

Returns:

loaded node (if multiple nodes are loaded then a list of nodes). If returnNode is True then a status flag and loaded node are returned.

slicer.util.loadAnnotationROI(filename, returnNode=False)

Load node from file.

Parameters:
  • filename – full path of the file to load.

  • returnNode – Deprecated.

Returns:

loaded node (if multiple nodes are loaded then a list of nodes). If returnNode is True then a status flag and loaded node are returned.

slicer.util.loadAnnotationRuler(filename, returnNode=False)

Load node from file.

Parameters:
  • filename – full path of the file to load.

  • returnNode – Deprecated.

Returns:

loaded node (if multiple nodes are loaded then a list of nodes). If returnNode is True then a status flag and loaded node are returned.

slicer.util.loadColorTable(filename, returnNode=False)

Load node from file.

Parameters:
  • filename – full path of the file to load.

  • returnNode – Deprecated.

Returns:

loaded node (if multiple nodes are loaded then a list of nodes). If returnNode is True then a status flag and loaded node are returned.

slicer.util.loadFiberBundle(filename, returnNode=False)

Load fiber bundle node from file.

Warning

To ensure the FiberBundleFile reader is registered, the SlicerDMRI extension may need to be installed.

Parameters:
  • filename – full path of the file to load.

  • returnNode – Deprecated.

Returns:

loaded node (if multiple nodes are loaded then a list of nodes). If returnNode is True then a status flag and loaded node are returned.

Raises:

RuntimeError – in case of failure

slicer.util.loadLabelVolume(filename, properties={}, returnNode=False)

Load node from file.

Parameters:
  • filename – full path of the file to load.

  • returnNode – Deprecated.

Returns:

loaded node (if multiple nodes are loaded then a list of nodes). If returnNode is True then a status flag and loaded node are returned.

slicer.util.loadMarkups(filename)

Load node from file.

Parameters:

filename – full path of the file to load.

Returns:

loaded node (if multiple nodes are loaded then a list of nodes).

slicer.util.loadMarkupsClosedCurve(filename)

Load markups closed curve from file.

Deprecated since version 4.13.0: Use the universal loadMarkups() function instead.

slicer.util.loadMarkupsCurve(filename)

Load markups curve from file.

Deprecated since version 4.13.0: Use the universal loadMarkups() function instead.

slicer.util.loadMarkupsFiducialList(filename, returnNode=False)

Load markups fiducials from file.

Deprecated since version 4.13.0: Use the universal loadMarkups() function instead.

slicer.util.loadModel(filename, returnNode=False)

Load node from file.

Parameters:
  • filename – full path of the file to load.

  • returnNode – Deprecated.

Returns:

loaded node (if multiple nodes are loaded then a list of nodes). If returnNode is True then a status flag and loaded node are returned.

slicer.util.loadNodeFromFile(filename, filetype=None, properties={}, returnNode=False)

Load node into the scene from a file.

Parameters:
  • filename – full path of the file to load.

  • filetype – specifies the file type, which determines which IO class will load the file. If not specified then the reader with the highest confidence is used.

  • properties – map containing additional parameters for the loading.

  • returnNode – Deprecated. If set to true then the method returns status flag and node instead of signalling error by throwing an exception.

Returns:

loaded node (if multiple nodes are loaded then a list of nodes). If returnNode is True then a status flag and loaded node are returned.

Raises:

RuntimeError – in case of failure

slicer.util.loadNodesFromFile(filename, filetype=None, properties={}, returnNode=False)

Load nodes into the scene from a file.

It differs from loadNodeFromFile in that it returns loaded node(s) in an iterator.

Parameters:
  • filename – full path of the file to load.

  • filetype – specifies the file type, which determines which IO class will load the file. If not specified then the reader with the highest confidence is used.

  • properties – map containing additional parameters for the loading.

Returns:

loaded node(s) in an iterator object.

Raises:

RuntimeError – in case of failure

slicer.util.loadScalarOverlay(filename, modelNodeID, returnNode=False)

Load node from file.

Parameters:
  • filename – full path of the file to load.

  • returnNode – Deprecated.

Returns:

loaded node (if multiple nodes are loaded then a list of nodes). If returnNode is True then a status flag and loaded node are returned.

slicer.util.loadScene(filename, properties={})

Load node from file.

Parameters:
  • filename – full path of the file to load.

  • returnNode – Deprecated.

Returns:

loaded node (if multiple nodes are loaded then a list of nodes). If returnNode is True then a status flag and loaded node are returned.

slicer.util.loadSegmentation(filename, properties={}, returnNode=False)

Load node from file.

Parameters:
  • filename – full path of the file to load.

  • properties

    dict object with any of the following keys

    • name: this name will be used as node name for the loaded volume

    • autoOpacities: automatically make large segments semi-transparent to make segments inside more visible (only used when loading segmentation from image file)

    • colorNodeID: use a color node (that already in the scene) to display the image (only used when loading segmentation from image file)

  • returnNode – Deprecated.

Returns:

loaded node (if multiple nodes are loaded then a list of nodes). If returnNode is True then a status flag and loaded node are returned.

slicer.util.loadSequence(filename, properties={})

Load sequence (4D data set) from file.

Parameters:
  • filename – full path of the file to load.

  • properties – dict object with any of the following keys - name: this name will be used as node name for the loaded volume - show: display volume in slice viewers after loading is completed - colorNodeID: color node to set in the proxy nodes’s display node

Returns:

loaded sequence node.

slicer.util.loadShaderProperty(filename, returnNode=False)

Load node from file.

Parameters:
  • filename – full path of the file to load.

  • returnNode – Deprecated.

Returns:

loaded node (if multiple nodes are loaded then a list of nodes). If returnNode is True then a status flag and loaded node are returned.

slicer.util.loadTable(filename)

Load table node from file.

Parameters:

filename – full path of the file to load.

Returns:

loaded table node

slicer.util.loadText(filename)

Load node from file.

Parameters:

filename – full path of the text file to load.

Returns:

loaded text node.

slicer.util.loadTransform(filename, returnNode=False)

Load node from file.

Parameters:
  • filename – full path of the file to load.

  • returnNode – Deprecated.

Returns:

loaded node (if multiple nodes are loaded then a list of nodes). If returnNode is True then a status flag and loaded node are returned.

slicer.util.loadUI(path)

Load UI file path and return the corresponding widget.

Raises:

RuntimeError – if the UI file is not found or if no widget was instantiated.

slicer.util.loadVolume(filename, properties={}, returnNode=False)

Load node from file.

Parameters:
  • filename – full path of the file to load.

  • properties – dict object with any of the following keys - name: this name will be used as node name for the loaded volume - labelmap: interpret volume as labelmap - singleFile: ignore all other files in the directory - center: ignore image position - discardOrientation: ignore image axis directions - autoWindowLevel: compute window/level automatically - show: display volume in slice viewers after loading is completed - colorNodeID: use a color node (that already in the scene) to display the image - fileNames: list of filenames to load the volume from

  • returnNode – Deprecated.

Returns:

loaded node (if multiple nodes are loaded then a list of nodes). If returnNode is True then a status flag and loaded node are returned.

slicer.util.logProcessOutput(proc)

Continuously write process output to the application log and the Python console.

Parameters:

proc – process object.

slicer.util.longPath(path)

Make long paths work on Windows, where the maximum path length is 260 characters.

For example, the files in the DICOM database may have paths longer than this limit. Accessing these can be made safe by prefixing it with the UNC prefix (’\\?\’).

Parameters:

path (string) – Path to be made safe if too long

Return string:

Safe path

slicer.util.lookupTopLevelWidget(objectName)

Loop over all top level widget associated with ‘slicer.app’ and return the one matching ‘objectName’

Raises:

RuntimeError – if no top-level widget is found by that name

slicer.util.mainWindow()

Get main window widget (qSlicerMainWindow object)

Returns:

main window widget, or None if there is no main window

slicer.util.messageBox(text, parent=None, **kwargs)

Displays a messagebox.

ctkMessageBox is used instead of a default qMessageBox to provide “Don’t show again” checkbox.

For example:

slicer.util.messageBox("Some message", dontShowAgainSettingsKey = "MainWindow/DontShowSomeMessage")

When the application is running in testing mode (slicer.app.testingEnabled() == True), an auto-closing popup with a delay of 3s is shown using delayDisplay() and qt.QMessageBox.Ok is returned, with the text being logged to indicate this.

slicer.util.moduleNames()

Get list containing name of all successfully loaded modules.

Returns:

list of module names

slicer.util.modulePath(moduleName)

Return the path where the module was discovered and loaded from.

Parameters:

moduleName – module name

Returns:

file path of the module

slicer.util.moduleSelector()

Return module selector widget.

Returns:

module widget object

Raises:

RuntimeError – if there is no module selector (for example, the application runs without a main window).

slicer.util.openAddColorTableDialog()
slicer.util.openAddDataDialog()
slicer.util.openAddFiberBundleDialog()
slicer.util.openAddFiducialDialog()
slicer.util.openAddMarkupsDialog()
slicer.util.openAddModelDialog()
slicer.util.openAddScalarOverlayDialog()
slicer.util.openAddSegmentationDialog()
slicer.util.openAddShaderPropertyDialog()
slicer.util.openAddTransformDialog()
slicer.util.openAddVolumeDialog()
slicer.util.openSaveDataDialog()
slicer.util.pip_install(requirements)

Install python packages.

Currently, the method simply calls python -m pip install but in the future further checks, optimizations, user confirmation may be implemented, therefore it is recommended to use this method call instead of a plain pip install.

Parameters:

requirements – requirement specifier in the same format as used by pip (https://docs.python.org/3/installing/index.html). It can be either a single string or a list of command-line arguments. It may be simpler to pass command-line arguments as a list if the arguments may contain spaces (because no escaping of the strings with quotes is necessary).

Example: calling from Slicer GUI

pip_install("tensorflow keras scikit-learn ipywidgets")

Example: calling from PythonSlicer console

from slicer.util import pip_install
pip_install("tensorflow")
slicer.util.pip_uninstall(requirements)

Uninstall python packages.

Currently, the method simply calls python -m pip uninstall but in the future further checks, optimizations, user confirmation may be implemented, therefore it is recommended to use this method call instead of a plain pip uninstall.

Parameters:

requirements – requirement specifier in the same format as used by pip (https://docs.python.org/3/installing/index.html). It can be either a single string or a list of command-line arguments. It may be simpler to pass command-line arguments as a list if the arguments may contain spaces (because no escaping of the strings with quotes is necessary).

Example: calling from Slicer GUI

pip_uninstall("tensorflow keras scikit-learn ipywidgets")

Example: calling from PythonSlicer console

from slicer.util import pip_uninstall
pip_uninstall("tensorflow")
slicer.util.plot(narray, xColumnIndex=-1, columnNames=None, title=None, show=True, nodes=None)

Create a plot from a numpy array that contains two or more columns.

Parameters:
  • narray – input numpy array containing data series in columns.

  • xColumnIndex – index of column that will be used as x axis. If it is set to negative number (by default) then row index will be used as x coordinate.

  • columnNames – names of each column of the input array. If title is specified for the plot then title+columnName will be used as series name.

  • title – title of the chart. Plot node names are set based on this value.

  • nodes – plot chart, table, and list of plot series nodes. Specified in a dictionary, with keys: ‘chart’, ‘table’, ‘series’. Series contains a list of plot series nodes (one for each table column). The parameter is used both as an input and output.

Returns:

plot chart node. Plot chart node provides access to chart properties and plot series nodes.

Example 1: simple plot

# Get sample data
import numpy as np
import SampleData
volumeNode = SampleData.downloadSample("MRHead")

# Create new plot
histogram = np.histogram(arrayFromVolume(volumeNode), bins=50)
chartNode = plot(histogram, xColumnIndex = 1)

# Change some plot properties
chartNode.SetTitle("My histogram")
chartNode.GetNthPlotSeriesNode(0).SetPlotType(slicer.vtkMRMLPlotSeriesNode.PlotTypeScatterBar)

Example 2: plot with multiple updates

# Get sample data
import numpy as np
import SampleData
volumeNode = SampleData.downloadSample("MRHead")

# Create variable that will store plot nodes (chart, table, series)
plotNodes = {}

# Create new plot
histogram = np.histogram(arrayFromVolume(volumeNode), bins=80)
plot(histogram, xColumnIndex = 1, nodes = plotNodes)

# Update plot
histogram = np.histogram(arrayFromVolume(volumeNode), bins=40)
plot(histogram, xColumnIndex = 1, nodes = plotNodes)
slicer.util.pythonShell()

Get Python console widget (ctkPythonConsole object)

Raises:

RuntimeError – if not found

slicer.util.quit()
slicer.util.reloadScriptedModule(moduleName)

Generic reload method for any scripted module.

The function performs the following:

  • Ensure sys.path includes the module path and use imp.load_module to load the associated script.

  • For the current module widget representation:

    • Hide all children widgets

    • Call cleanup() function and disconnect ScriptedLoadableModuleWidget_onModuleAboutToBeUnloaded

    • Remove layout items

  • Instantiate new widget representation

  • Call setup() function

  • Update slicer.modules.<moduleName>Widget attribute

slicer.util.removeParameterEditWidgetConnections(parameterEditWidgets, updateParameterNodeFromGUI)

Remove connections created by addParameterEditWidgetConnections().

slicer.util.resetSliceViews()

Reset focal view around volumes

slicer.util.resetThreeDViews()

Reset focal view around volumes

slicer.util.restart()

Restart the application.

No confirmation popup is displayed.

slicer.util.saveNode(node, filename, properties={})

Save ‘node’ data into ‘filename’.

It is the user responsibility to provide the appropriate file extension.

User has also the possibility to overwrite the fileType internally retrieved using method ‘qSlicerCoreIOManager::fileWriterFileType(vtkObject*)’. This can be done by specifying a ‘fileType’attribute to the optional ‘properties’ dictionary.

slicer.util.saveScene(filename, properties={})

Save the current scene.

Based on the value of ‘filename’, the current scene is saved either as a MRML file, MRB file or directory.

If filename ends with ‘.mrml’, the scene is saved as a single file without associated data.

If filename ends with ‘.mrb’, the scene is saved as a MRML bundle (Zip archive with scene and data files).

In every other case, the scene is saved in the directory specified by ‘filename’. Both MRML scene file and data will be written to disk. If needed, directories and sub-directories will be created.

slicer.util.selectModule(module)

Set currently active module.

Throws a RuntimeError exception in case of failure (no such module or the application runs without a main window).

Parameters:

module – module name or object

Raises:

RuntimeError – in case of failure

slicer.util.selectedModule()

Return currently active module.

Returns:

module object

Raises:

RuntimeError – in case of failure (no such module or the application runs without a main window).

slicer.util.setApplicationLogoVisible(visible=True, scaleFactor=None, icon=None)

Customize appearance of the application logo at the top of module panel.

Parameters:
  • visible – if True then the logo is displayed, otherwise the area is left empty.

  • scaleFactor – specifies the displayed size of the icon. 1.0 means original size, larger value means larger displayed size.

  • icon – a qt.QIcon object specifying what icon to display as application logo.

If there is no main window then the function has no effect.

slicer.util.setDataProbeVisible(visible)

Show/hide Data probe at the bottom of module panel.

If there is no main window then the function has no effect.

slicer.util.setErrorLogVisible(visible)

Show/hide Error log window.

If there is no main window then the function has no effect.

slicer.util.setMenuBarsVisible(visible, ignore=None)

Show/hide all menu bars, except those listed in ignore list.

If there is no main window then the function has no effect.

slicer.util.setModuleHelpSectionVisible(visible)

Show/hide Help section at the top of module panel.

If there is no main window then the function has no effect.

slicer.util.setModulePanelTitleVisible(visible)

Show/hide module panel title bar at the top of module panel.

If the title bar is not visible then it is not possible to drag and dock the module panel to a different location.

If there is no main window then the function has no effect.

slicer.util.setPythonConsoleVisible(visible)

Show/hide Python console.

If there is no main window then the function has no effect.

slicer.util.setSliceViewerLayers(background='keep-current', foreground='keep-current', label='keep-current', foregroundOpacity=None, labelOpacity=None, fit=False, rotateToVolumePlane=False)

Set the slice views with the given nodes.

If node ID is not specified (or value is ‘keep-current’) then the layer will not be modified.

Parameters:
  • background – node or node ID to be used for the background layer

  • foreground – node or node ID to be used for the foreground layer

  • label – node or node ID to be used for the label layer

  • foregroundOpacity – opacity of the foreground layer

  • labelOpacity – opacity of the label layer

  • rotateToVolumePlane – rotate views to closest axis of the selected background, foreground, or label volume

  • fit – fit slice views to their content (position&zoom to show all visible layers)

slicer.util.setStatusBarVisible(visible)

Show/hide status bar

If there is no main window or status bar then the function has no effect.

slicer.util.setToolbarsVisible(visible, ignore=None)

Show/hide all existing toolbars, except those listed in ignore list.

If there is no main window then the function has no effect.

slicer.util.setViewControllersVisible(visible)

Show/hide view controller toolbar at the top of slice and 3D views

slicer.util.settingsValue(key, default, converter=<function <lambda>>, settings=None)

Return settings value associated with key if it exists or the provided default otherwise.

settings parameter is expected to be a valid qt.Settings object.

slicer.util.showStatusMessage(message, duration=0)

Display message in the status bar.

slicer.util.sourceDir()

Location of the Slicer source directory.

Type:

str or None

This provides the location of the Slicer source directory, if Slicer is being run from a CMake build directory. If the Slicer home directory does not contain a CMakeCache.txt (e.g. for an installed Slicer), the property will have the value None.

slicer.util.startQtDesigner(args=None)

Start Qt Designer application to allow editing UI files.

slicer.util.startupEnvironment()

Returns the environment without the Slicer specific values.

Path environment variables like PATH, LD_LIBRARY_PATH or PYTHONPATH will not contain values found in the launcher settings.

Similarly key=value environment variables also found in the launcher settings are excluded.

The function excludes both the Slicer launcher settings and the revision specific launcher settings.

Warning

If a value was associated with a key prior starting Slicer, it will not be set in the environment returned by this function.

slicer.util.tempDirectory(key='__SlicerTemp__', tempDir=None, includeDateTime=True)

Come up with a unique directory name in the temp dir and make it and return it

Note

This directory is not automatically cleaned up.

slicer.util.toBool(value)

Convert any type of value to a boolean.

The function uses the following heuristic:

  1. If the value can be converted to an integer, the integer is then converted to a boolean.

  2. If the value is a string, return True if it is equal to ‘true’. False otherwise. Note that the comparison is case insensitive.

  3. If the value is neither an integer or a string, the bool() function is applied.

>>> [toBool(x) for x in range(-2, 2)]
[True, True, False, True]
>>> [toBool(x) for x in ['-2', '-1', '0', '1', '2', 'Hello']]
[True, True, False, True, True, False]
>>> [toBool(x) for x in ['true', 'false', 'True', 'False', 'tRue', 'fAlse']]
[True, False, True, False, True, False]
>>> toBool(object())
True
>>> toBool(None)
False
slicer.util.toLatin1String(text)

Convert string to latin1 encoding.

slicer.util.toVTKString(text)

Convert unicode string into VTK string.

Deprecated since version 4.11.0: Since now VTK assumes that all strings are in UTF-8 and all strings in Slicer are UTF-8, too, conversion is no longer necessary. The method is only kept for backward compatibility and will be removed in the future.

slicer.util.tryWithErrorDisplay(message=None, show=True, waitCursor=False)

Show an error display with the error details if an exception is raised.

Parameters:
  • message – Text shown in the message box.

  • show – If show is False, the context manager has no effect.

  • waitCursor – If waitCrusor is set to True then mouse cursor is changed to wait cursor while the context manager is being run.

import random

def risky():
  if random.choice((True, False)):
    raise Exception('Error while trying to do some internal operations.')

with slicer.util.tryWithErrorDisplay("Risky operation failed."):
  risky()
slicer.util.updateMarkupsControlPointsFromArray(markupsNode, narray, world=False)

Sets control point positions in a markups node from a numpy array of size Nx3.

Parameters:

world – if set to True then the control point coordinates are expected in world coordinate system.

Raises:

RuntimeError – in case of failure

All previous content of the node is deleted.

slicer.util.updateNodeFromParameterEditWidgets(parameterEditWidgets, parameterNode)

Update vtkMRMLScriptedModuleNode from widgets.

The function is useful for implementing updateParameterNodeFromGUI.

Note

Only a few widget classes are supported now. More will be added later. Report any missing classes at https://discourse.slicer.org.

See example in addParameterEditWidgetConnections() documentation.

slicer.util.updateParameterEditWidgetsFromNode(parameterEditWidgets, parameterNode)

Update widgets from values stored in a vtkMRMLScriptedModuleNode.

The function is useful for implementing updateGUIFromParameterNode.

See example in addParameterEditWidgetConnections() documentation.

Note

Only a few widget classes are supported now. More will be added later. Report any missing classes at https://discourse.slicer.org.

slicer.util.updateSegmentBinaryLabelmapFromArray(narray, segmentationNode, segmentId, referenceVolumeNode=None)

Sets binary labelmap representation of a segment from a numpy array.

Parameters:
  • narray – voxel array, containing 0 outside the segment, 1 inside the segment.

  • segmentationNode – segmentation node that will be updated.

  • segmentId – ID of the segment that will be updated. Can be determined from segment name by calling segmentationNode.GetSegmentation().GetSegmentIdBySegmentName(segmentName).

  • referenceVolumeNode – a volume node that determines geometry (origin, spacing, axis directions, extents) of the array. If not specified then the volume that was used for setting the segmentation’s geometry is used as reference volume.

Raises:

RuntimeError – in case of failure

Warning

Voxels values are deep-copied, therefore if the numpy array is modified after calling this method, segmentation node will not change.

slicer.util.updateTableFromArray(tableNode, narrays, columnNames=None)

Set values in a table node from a numpy array.

Parameters:

columnNames – may contain a string or list of strings that will be used as column name(s).

Raises:

ValueError – in case of failure

Values are copied, therefore if the numpy array is modified after calling this method, values in the table node will not change. All previous content of the table is deleted.

Example:

import numpy as np
histogram = np.histogram(arrayFromVolume(getNode('MRHead')))
tableNode = slicer.mrmlScene.AddNewNodeByClass("vtkMRMLTableNode")
updateTableFromArray(tableNode, histogram, ["Count", "Intensity"])
slicer.util.updateTransformMatrixFromArray(transformNode, narray, toWorld=False)

Set transformation matrix from a numpy array of size 4x4 (toParent).

Parameters:

world – if set to True then the transform will be set so that transform to world matrix will be equal to narray; otherwise transform to parent will be set as narray.

Raises:

RuntimeError – in case of failure

slicer.util.updateVTKMatrixFromArray(vmatrix, narray)

Update VTK matrix values from a numpy array.

Parameters:
  • vmatrix – VTK matrix (vtkMatrix4x4 or vtkMatrix3x3) that will be update

  • narray – input numpy array

Raises:

RuntimeError – in case of failure

To set numpy array from VTK matrix, use arrayFromVTKMatrix().

slicer.util.updateVolumeFromArray(volumeNode, narray)

Sets voxels of a volume node from a numpy array.

Raises:

RuntimeError – in case of failure

Voxels values are deep-copied, therefore if the numpy array is modified after calling this method, voxel values in the volume node will not change. Dimensions and voxel type of the source numpy array does not have to match the current content of the volume node.

slicer.util.updateVolumeFromITKImage(volumeNode, itkImage, deepCopy=True)

Set voxels of a volume node from an ITK image.

By default, voxels values are deep-copied, therefore if the ITK image is modified after calling this method, voxel values in the volume node will not change.

Warning

Important: Setting deepCopy to False means that the memory area is shared between the ITK image and the vtkImageData object in the MRML volume node, therefore modifying the ITK image values requires to call itkImageFromVolumeModified().

If the ITK image is reallocated, calling this function is required.

slicer.util.vtkMatrixFromArray(narray)

Create VTK matrix from a 3x3 or 4x4 numpy array.

Parameters:

narray – input numpy array

Raises:

RuntimeError – in case of failure

The returned matrix is just a copy and so any modification in the array will not affect the output matrix. To set numpy array from VTK matrix, use arrayFromVTKMatrix().

slicer.util.warningDisplay(text, windowTitle=None, parent=None, standardButtons=None, **kwargs)

Display popup with a warning message.

If there is no main window, or if the application is running in testing mode (slicer.app.testingEnabled() == True), then the text is only logged (at warning level).