slicer package

Submodules

slicer.ScriptedLoadableModule module

slicer.cli module

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 exectuion (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 module

slicer.testing module

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

slicer.util module

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.NodeModify(node)

Bases: object

Context manager to conveniently compress mrml node modified event.

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

addObserver(object, event, method, group='none', priority=0.0)
hasObserver(object, event, method)
observer(event, method)
removeObserver(object, event, method)
removeObservers(method=None)
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.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.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 lablemap representation that may be shared” between multiple segments.

slicer.util.arrayFromSegmentBinaryLabelmap(segmentationNode, segmentId)

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

Voxels values are copied.

If binary labelmap is the master representation then voxel values in the volume node can be modified by changing values in the numpy array.

After all modifications have 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.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 master 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.

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 an confirmation popup. Return if confirmed with OK.

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

Display an confirmation popup. Return if confirmed with Retry.

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

Display an confirmation popup. Return if confirmed with Yes.

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 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.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)

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.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 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 stops 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. Note that forcing the application to exit may result in improperly released files and other resources.

import sys
sys.exit(status)
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 hexdecimal 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. :param widget: parent widget where the widgets will be searched :param name: name attribute of the widget :param text: text attribute of the widget :param title: title attribute of the widget :param className: className() attribute of the widget :return: 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 then the text is only logged (at info level).

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.

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 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.loadFiducialList(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.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, 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.
  • 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, 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.
  • 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, 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.loadSequence(filename, properties={})

Load sequence (4D data set) from file.

Parameters:
  • filename – full path of the file to load.
  • properties
    • 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
    • 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
    • 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")
slicer.util.moduleNames()

Get list containing name of all successfully loaded modules.

Returns:list of module names
slicer.util.modulePath(moduleName)

Get module logic object.

Module logic allows a module to use features offered by another module. Throws a RuntimeError exception if the module does not have widget. :param moduleName: module name :return: 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. :param requirements: requirement specifier, same format as used by pip (https://docs.python.org/3/installing/index.html)

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, same format as used by pip (https://docs.python.org/3/installing/index.html)

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.
  • 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). :param 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)

Show/hide application logo at the top of module panel.

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.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. Note that if a value was associated with a key prior starting Slicer, it will not be set in the environment returned by this function.

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

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(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.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 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.

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

See example in addParameterEditWidgetConnections() documentation.

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 data size of the source numpy array does not have to match the current content of the volume node.

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 then the text is only logged (at warning level).

Module contents

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