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

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

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

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”

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

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. A RuntimeError exception is raised 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)
slicer.util.getModuleGui(module)
slicer.util.getNewModuleGui(module)
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.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.

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

Launch a process. Hiding the console and captures the process output. The console window is hidden when running on Windows. :param args: executable name, followed by command-line arguments :param useStartupEnvironment: launch the process in the original environment as the original Slicer process :param cwd: current working directory :return: 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)

Deprecated. Use loadMarkups function instead.

slicer.util.loadMarkupsCurve(filename)

Deprecated. Use loadMarkups function instead.

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

Deprecated. Use 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.

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.

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.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. :param filename: full path of the file to load. :return: 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. :param 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, verbose=True)

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

slicer.util.mainWindow(verbose=True)
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()
slicer.util.modulePath(moduleName)
slicer.util.moduleSelector()
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. :param 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(verbose=True)
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.resetSliceViews()

Reset focal view around volumes

slicer.util.resetThreeDViews()

Reset focal view around volumes

slicer.util.restart()
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)
slicer.util.selectedModule()
slicer.util.setApplicationLogoVisible(visible)

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

slicer.util.setDataProbeVisible(visible)

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

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

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

slicer.util.setModuleHelpSectionVisible(visible)

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

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.

slicer.util.setPythonConsoleVisible(visible)

Show/hide Python console.

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

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

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

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)
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 # TODO: switch to QTemporaryDir in Qt5. 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)

This method is deprecated. It converted unicode string into VTK string, but 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.

All previous content of the node is deleted.

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

Set values in a table node from a numpy array.

columnNames may contain a string or list of strings that will be used as column name(s). 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.
slicer.util.updateVTKMatrixFromArray(vmatrix, narray)

Update VTK matrix values from a numpy array. :param vmatrix: VTK matrix (vtkMatrix4x4 or vtkMatrix3x3) that will be update :param narray: input numpy array To set numpy array from VTK matrix, use arrayFromVTKMatrix().

slicer.util.updateVolumeFromArray(volumeNode, narray)

Sets voxels of a volume node from a numpy array. 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. :param narray: input numpy array 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.

Module contents

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