<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
	<id>https://www.slicer.org/w/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Kmader</id>
	<title>Slicer Wiki - User contributions [en]</title>
	<link rel="self" type="application/atom+xml" href="https://www.slicer.org/w/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Kmader"/>
	<link rel="alternate" type="text/html" href="https://www.slicer.org/wiki/Special:Contributions/Kmader"/>
	<updated>2026-05-25T16:15:37Z</updated>
	<subtitle>User contributions</subtitle>
	<generator>MediaWiki 1.33.0</generator>
	<entry>
		<id>https://www.slicer.org/w/index.php?title=Documentation/4.6/ScriptRepository&amp;diff=49896</id>
		<title>Documentation/4.6/ScriptRepository</title>
		<link rel="alternate" type="text/html" href="https://www.slicer.org/w/index.php?title=Documentation/4.6/ScriptRepository&amp;diff=49896"/>
		<updated>2017-02-22T15:40:58Z</updated>

		<summary type="html">&lt;p&gt;Kmader: to make the code a bit more runnable since the imports are required&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;noinclude&amp;gt;{{documentation/versioncheck}}&amp;lt;/noinclude&amp;gt;&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Community-contributed modules=&lt;br /&gt;
&lt;br /&gt;
Usage: save the .py file to a directory, add the directory to the additional module paths in the Slicer application settings (choose in the menu: Edit / Application settings, click Modules, click &amp;gt;&amp;gt; next to Additional module paths, click Add, and choose the .py file's location).&lt;br /&gt;
&lt;br /&gt;
==Filters==&lt;br /&gt;
* [https://raw.github.com/pieper/VolumeMasker/master/VolumeMasker.py VolumeMasker.py]: Update a target volume with the results of setting all input volume voxels to 0 except for those that correspond to a selected label value in an input label map (Used for example in the volume rendering in [https://www.youtube.com/watch?v=dfu2gugHLHs this video).&lt;br /&gt;
&lt;br /&gt;
==DICOM==&lt;br /&gt;
* [https://gist.github.com/pieper/6186477 dicom header browser] to easily scroll through dicom files using dcmdump.&lt;br /&gt;
* [https://subversion.assembla.com/svn/slicerrt/trunk/SlicerRt/src/BatchProcessing SlicerRT batch processing] to batch convert RT structure sets to labelmap NRRD files.&lt;br /&gt;
&lt;br /&gt;
==Informatics==&lt;br /&gt;
* [https://subversion.assembla.com/svn/slicerrt/trunk/SlicerRt/sandbox/MarkupsInfoModule/MarkupsInfo.py MarkupsInfo.py]: Compute the total length between all the points of a markup list.&lt;br /&gt;
* [https://subversion.assembla.com/svn/slicerrt/trunk/SlicerRt/sandbox/LineProfile/LineProfile.py LineProfile.py]: Compute intensity profile in a volume along a line.&lt;br /&gt;
&lt;br /&gt;
=Community-contributed examples=&lt;br /&gt;
&lt;br /&gt;
Usage: Copy-paste the shown code lines or linked .py file contents into Python console in Slicer.&lt;br /&gt;
&lt;br /&gt;
==Capture==&lt;br /&gt;
* Get a MRML node in the scene based on the node name and call methods of that object. For the MRHead sample data:&lt;br /&gt;
  vol=slicer.util.getNode('MR*')&lt;br /&gt;
  vol.GetImageData().GetDimensions()&lt;br /&gt;
* Capture the full Slicer screen and save it into a file&lt;br /&gt;
  img = qt.QPixmap.grabWidget(slicer.util.mainWindow()).toImage()&lt;br /&gt;
  img.save('c:/tmp/test.png')&lt;br /&gt;
* [https://subversion.assembla.com/svn/slicerrt/trunk/SlicerRt/sandbox/CaptureRotationVideo/CaptureRotationVideo.py CaptureRotationVideo.py]: Capture a video of the scene rotating in the 3D view&lt;br /&gt;
&lt;br /&gt;
==Launching Slicer==&lt;br /&gt;
* How to open an .mrb file with Slicer at the command line?&lt;br /&gt;
  Slicer.exe --python-code &amp;quot;slicer.util.loadScene( 'f:/2013-08-23-Scene.mrb' )&amp;quot;&lt;br /&gt;
* How to run a script in the Slicer environment in batch mode (without showing any graphical user interface)?&lt;br /&gt;
  Slicer.exe --python-code &amp;quot;doSomething; doSomethingElse; etc.&amp;quot; --testing --no-splash --no-main-window&lt;br /&gt;
&lt;br /&gt;
==DICOM==&lt;br /&gt;
* How to access tags of DICOM images imported into Slicer? For example, to print the first patient's first study's first series' &amp;quot;0020,0032&amp;quot; field:&lt;br /&gt;
  db=slicer.dicomDatabase&lt;br /&gt;
  patientList=db.patients()&lt;br /&gt;
  studyList=db.studiesForPatient(patientList[0])&lt;br /&gt;
  seriesList=db.seriesForStudy(studyList[0])&lt;br /&gt;
  fileList=db.filesForSeries(seriesList[0])&lt;br /&gt;
  print db.fileValue(fileList[0],'0020,0032')&lt;br /&gt;
&lt;br /&gt;
* How to access tag of a volume loaded from DICOM? For example, get the patient position stored in a volume:&lt;br /&gt;
  volumeName='2: ENT IMRT'&lt;br /&gt;
  n=slicer.util.getNode(volumeName)&lt;br /&gt;
  instUids=n.GetAttribute('DICOM.instanceUIDs').split()&lt;br /&gt;
  filename=slicer.dicomDatabase.fileForInstance(instUids[0])&lt;br /&gt;
  print slicer.dicomDatabase.fileValue(filename,'0018,5100')&lt;br /&gt;
&lt;br /&gt;
* How to access tag of an item in the Subject Hierachy tree? For example, get the content time tag of a structure set:&lt;br /&gt;
  rtStructName = '3: RTSTRUCT: PROS'&lt;br /&gt;
  rtStructNode = slicer.util.getNode(rtStructName)&lt;br /&gt;
  rtStructSubjectHierarchyNode = slicer.vtkMRMLSubjectHierarchyNode.GetAssociatedSubjectHierarchyNode(rtStructNode)&lt;br /&gt;
  ctSliceInstanceUids = rtStructSubjectHierarchyNode.GetAttribute('DICOM.ReferencedInstanceUIDs').split()&lt;br /&gt;
  filename = slicer.dicomDatabase.fileForInstance(ctSliceInstanceUids[0])&lt;br /&gt;
  print slicer.dicomDatabase.fileValue(filename,'0008,0033')&lt;br /&gt;
&lt;br /&gt;
==Toolbar functions==&lt;br /&gt;
* How to turn on slice intersections in the crosshair menu on the toolbar:&lt;br /&gt;
  viewNodes = slicer.mrmlScene.GetNodesByClass('vtkMRMLSliceCompositeNode')&lt;br /&gt;
  viewNodes.UnRegister(slicer.mrmlScene)&lt;br /&gt;
  viewNodes.InitTraversal()&lt;br /&gt;
  viewNode = viewNodes.GetNextItemAsObject()&lt;br /&gt;
  while viewNode:&lt;br /&gt;
    viewNode.SetSliceIntersectionVisibility(1)&lt;br /&gt;
    viewNode = viewNodes.GetNextItemAsObject()&lt;br /&gt;
&lt;br /&gt;
How to find similar functions? For this one I searched for &amp;quot;slice intersections&amp;quot; text in the whole slicer source code, found that the function is implemented in Base\QTGUI\qSlicerViewersToolBar.cxx, then translated the qSlicerViewersToolBarPrivate::setSliceIntersectionVisible(bool visible) method to Python.&lt;br /&gt;
&lt;br /&gt;
==Manipulating objects in the slice viewer==&lt;br /&gt;
* How to define/edit a circular region of interest in a slice viewer?&lt;br /&gt;
&lt;br /&gt;
Drop two markup points on a slice view and copy-paste the code below into the Python console. After this, as you move the markups you’ll see a circle following the markups.&lt;br /&gt;
&lt;br /&gt;
  # Update the sphere from the fiducial points&lt;br /&gt;
  def UpdateSphere(param1, param2):  &lt;br /&gt;
    centerPointCoord = [0.0, 0.0, 0.0]&lt;br /&gt;
    markups.GetNthFiducialPosition(0,centerPointCoord)&lt;br /&gt;
    circumferencePointCoord = [0.0, 0.0, 0.0]&lt;br /&gt;
    markups.GetNthFiducialPosition(1,circumferencePointCoord)&lt;br /&gt;
    sphere.SetCenter(centerPointCoord)&lt;br /&gt;
    radius=math.sqrt((centerPointCoord[0]-circumferencePointCoord[0])**2+(centerPointCoord[1]-circumferencePointCoord[1])**2+(centerPointCoord[2]-circumferencePointCoord[2])**2)&lt;br /&gt;
    sphere.SetRadius(radius)&lt;br /&gt;
    sphere.SetPhiResolution(30)&lt;br /&gt;
    sphere.SetThetaResolution(30)&lt;br /&gt;
    sphere.Update()&lt;br /&gt;
  &lt;br /&gt;
  # Get a reference to the markup&lt;br /&gt;
  markups=slicer.util.getNode('F')&lt;br /&gt;
  # Create the sphere that will intersect the slice viewer&lt;br /&gt;
  sphere = vtk.vtkSphereSource()&lt;br /&gt;
  # Initial positioning of the sphere&lt;br /&gt;
  UpdateSphere(0,0)&lt;br /&gt;
  # Create model node and add to scene&lt;br /&gt;
  model = slicer.vtkMRMLModelNode()&lt;br /&gt;
  model.SetAndObservePolyData(sphere.GetOutput())&lt;br /&gt;
  modelDisplay = slicer.vtkMRMLModelDisplayNode()&lt;br /&gt;
  modelDisplay.SetSliceIntersectionVisibility(True) # Show in slice view&lt;br /&gt;
  modelDisplay.SetVisibility(False) # Hide in 3D view&lt;br /&gt;
  slicer.mrmlScene.AddNode(modelDisplay)&lt;br /&gt;
  model.SetAndObserveDisplayNodeID(modelDisplay.GetID())&lt;br /&gt;
  modelDisplay.SetInputPolyData(model.GetPolyData())&lt;br /&gt;
  slicer.mrmlScene.AddNode(model) &lt;br /&gt;
  # Call UpdateSphere whenever the fiducials are changed&lt;br /&gt;
  markups.AddObserver(&amp;quot;ModifiedEvent&amp;quot;, UpdateSphere, 2)&lt;br /&gt;
&lt;br /&gt;
== Add a texture mapped plane to the scene as a model ==&lt;br /&gt;
Note that model textures are not exposed in the GUI and are not saved in the scene&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
# use dummy image data here&lt;br /&gt;
e = vtk.vtkImageEllipsoidSource()&lt;br /&gt;
&lt;br /&gt;
scene = slicer.mrmlScene&lt;br /&gt;
&lt;br /&gt;
# Create model node&lt;br /&gt;
model = slicer.vtkMRMLModelNode()&lt;br /&gt;
model.SetScene(scene)&lt;br /&gt;
model.SetName(scene.GenerateUniqueName(&amp;quot;2DImageModel&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
planeSource = vtk.vtkPlaneSource()&lt;br /&gt;
model.SetAndObservePolyData(planeSource.GetOutput())&lt;br /&gt;
&lt;br /&gt;
# Create display node&lt;br /&gt;
modelDisplay = slicer.vtkMRMLModelDisplayNode()&lt;br /&gt;
modelDisplay.SetColor(1,1,0) # yellow&lt;br /&gt;
modelDisplay.SetBackfaceCulling(0)&lt;br /&gt;
modelDisplay.SetScene(scene)&lt;br /&gt;
scene.AddNode(modelDisplay)&lt;br /&gt;
model.SetAndObserveDisplayNodeID(modelDisplay.GetID())&lt;br /&gt;
&lt;br /&gt;
# Add to scene&lt;br /&gt;
modelDisplay.SetAndObserveTextureImageData(e.GetOutput())&lt;br /&gt;
scene.AddNode(model) &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
transform = slicer.vtkMRMLLinearTransformNode()&lt;br /&gt;
scene.AddNode(transform) &lt;br /&gt;
model.SetAndObserveTransformNodeID(transform.GetID())&lt;br /&gt;
&lt;br /&gt;
vTransform = vtk.vtkTransform()&lt;br /&gt;
vTransform.Scale(50,50,50)&lt;br /&gt;
vTransform.RotateX(30)&lt;br /&gt;
transform.SetAndObserveMatrixTransformToParent(vTransform.GetMatrix())&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Export a model to Blender, including color ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
plyFilePath = &amp;quot;/tmp/fibers.ply&amp;quot;&lt;br /&gt;
&lt;br /&gt;
lineDisplayNode = getNode(&amp;quot;*LineDisplay*&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
tuber = vtk.vtkTubeFilter()&lt;br /&gt;
tuber.SetInput(lineDisplayNode.GetOutputPolyData())&lt;br /&gt;
&lt;br /&gt;
tubes = tuber.GetOutput()&lt;br /&gt;
tubes.Update()&lt;br /&gt;
scalars = tubes.GetPointData().GetArray(0)&lt;br /&gt;
scalars.SetName(&amp;quot;scalars&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
triangles = vtk.vtkTriangleFilter()&lt;br /&gt;
triangles.SetInput(tubes)&lt;br /&gt;
&lt;br /&gt;
colorNode = lineDisplayNode.GetColorNode()&lt;br /&gt;
lookupTable = vtk.vtkLookupTable()&lt;br /&gt;
lookupTable.DeepCopy(colorNode.GetLookupTable())&lt;br /&gt;
lookupTable.SetTableRange(0,1)&lt;br /&gt;
&lt;br /&gt;
plyWriter = vtk.vtkPLYWriter()&lt;br /&gt;
plyWriter.SetInput(triangles.GetOutput())&lt;br /&gt;
plyWriter.SetLookupTable(lookupTable)&lt;br /&gt;
plyWriter.SetArrayName(&amp;quot;scalars&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
plyWriter.SetFileName(plyFilePath)&lt;br /&gt;
plyWriter.Write()&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Clone a volume ==&lt;br /&gt;
This example shows how to clone the MRHead sample volume, including its pixel data and display settings.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
sourceVolumeNode = slicer.util.getNode('MRHead')&lt;br /&gt;
volumesLogic = slicer.modules.volumes.logic()&lt;br /&gt;
clonedVolumeNode = volumesLogic.CloneVolume(slicer.mrmlScene, sourceVolumeNode, 'Cloned volume')&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Create a new volume ==&lt;br /&gt;
This example shows how to create a new empty volume.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
imageSize=[512, 512, 512]&lt;br /&gt;
imageSpacing=[1.0, 1.0, 1.0]&lt;br /&gt;
voxelType=vtk.VTK_UNSIGNED_CHAR&lt;br /&gt;
# Create an empty image volume&lt;br /&gt;
imageData=vtk.vtkImageData()&lt;br /&gt;
imageData.SetDimensions(imageSize)&lt;br /&gt;
imageData.AllocateScalars(voxelType, 1)&lt;br /&gt;
thresholder=vtk.vtkImageThreshold()&lt;br /&gt;
thresholder.SetInputData(imageData)&lt;br /&gt;
thresholder.SetInValue(0)&lt;br /&gt;
thresholder.SetOutValue(0)&lt;br /&gt;
# Create volume node&lt;br /&gt;
volumeNode=slicer.vtkMRMLScalarVolumeNode()&lt;br /&gt;
volumeNode.SetSpacing(imageSpacing)&lt;br /&gt;
volumeNode.SetImageDataConnection(thresholder.GetOutputPort())&lt;br /&gt;
# Add volume to scene&lt;br /&gt;
slicer.mrmlScene.AddNode(volumeNode)&lt;br /&gt;
displayNode=slicer.vtkMRMLScalarVolumeDisplayNode()&lt;br /&gt;
slicer.mrmlScene.AddNode(displayNode)&lt;br /&gt;
colorNode = slicer.util.getNode('Grey')&lt;br /&gt;
displayNode.SetAndObserveColorNodeID(colorNode.GetID())&lt;br /&gt;
volumeNode.SetAndObserveDisplayNodeID(displayNode.GetID())&lt;br /&gt;
volumeNode.CreateDefaultStorageNode()&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Modify voxels in a volume ==&lt;br /&gt;
This example shows how to change voxels values of the MRHead sample volume.&lt;br /&gt;
The values will be computed by function f(r,a,s,) = (r-10)*(r-10)+(a+15)*(a+15)+s*s.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
volumeNode=slicer.util.getNode('MRHead')&lt;br /&gt;
ijkToRas = vtk.vtkMatrix4x4()&lt;br /&gt;
volumeNode.GetIJKToRASMatrix(ijkToRas)&lt;br /&gt;
imageData=volumeNode.GetImageData()&lt;br /&gt;
extent = imageData.GetExtent()&lt;br /&gt;
for k in xrange(extent[4], extent[5]+1):&lt;br /&gt;
  for j in xrange(extent[2], extent[3]+1):&lt;br /&gt;
    for i in xrange(extent[0], extent[1]+1):&lt;br /&gt;
      position_Ijk=[i, j, k, 1]&lt;br /&gt;
      position_Ras=ijkToRas.MultiplyPoint(position_Ijk)&lt;br /&gt;
      r=position_Ras[0]&lt;br /&gt;
      a=position_Ras[1]&lt;br /&gt;
      s=position_Ras[2]      &lt;br /&gt;
      functionValue=(r-10)*(r-10)+(a+15)*(a+15)+s*s&lt;br /&gt;
      imageData.SetScalarComponentFromDouble(i,j,k,0,functionValue)&lt;br /&gt;
imageData.SetScalarComponentFromFloat(distortionVectorPosition_Ijk[0], distortionVectorPosition_Ijk[1], distortionVectorPosition_Ijk[2], 0, fillValue)&lt;br /&gt;
imageData.Modified()&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Access values in a DTI tensor volume ==&lt;br /&gt;
This example shows how to access individual tensors at the voxel level.&lt;br /&gt;
&lt;br /&gt;
First load your DWI volume and estimate tensors to produce a DTI volume called ‘Output DTI Volume’&lt;br /&gt;
&lt;br /&gt;
Then open the python window: View-&amp;gt;Python interactor&lt;br /&gt;
&lt;br /&gt;
Use this command to access tensors through numpy:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
tensors = array('Output DTI Volume')&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Type the following code into the Python window to access all tensor components using vtk commands:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
volumeNode=slicer.util.getNode('Output DTI Volume')&lt;br /&gt;
imageData=volumeNode.GetImageData()&lt;br /&gt;
tensors = imageData.GetPointData().GetTensors()&lt;br /&gt;
extent = imageData.GetExtent()&lt;br /&gt;
idx = 0&lt;br /&gt;
for k in xrange(extent[4], extent[5]+1):&lt;br /&gt;
  for j in xrange(extent[2], extent[3]+1):&lt;br /&gt;
    for i in xrange(extent[0], extent[1]+1):&lt;br /&gt;
      tensors.GetTuple9(idx)&lt;br /&gt;
      idx += 1&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Change window/level (brightness/contrast) or colormap of a volume ==&lt;br /&gt;
This example shows how to change window/level of the MRHead sample volume.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
volumeNode = getNode('MRHead')&lt;br /&gt;
displayNode = volumeNode.GetDisplayNode()&lt;br /&gt;
displayNode.AutoWindowLevelOff()&lt;br /&gt;
displayNode.SetWindow(50)&lt;br /&gt;
displayNode.SetLevel(100)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Change color mapping from grayscale to rainbow:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
displayNode.SetAndObserveColorNodeID('vtkMRMLColorTableNodeRainbow')&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Manipulate a Slice View ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
lm = slicer.app.layoutManager()&lt;br /&gt;
red = lm.sliceWidget('Red')&lt;br /&gt;
redLogic = red.sliceLogic()&lt;br /&gt;
# Print current slice offset position&lt;br /&gt;
print redLogic.GetSliceOffset()&lt;br /&gt;
# Change slice position&lt;br /&gt;
redLogic.SetSliceOffset(20)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Save a series of images from a Slice View ==&lt;br /&gt;
&lt;br /&gt;
Save the following into a file such as '/tmp/record.py' and then in the slicer python console type &amp;quot;execfile('/tmp/record.py')&amp;quot;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
layoutName = 'Green'&lt;br /&gt;
imagePathPattern = '/tmp/image-%03d.png'&lt;br /&gt;
steps = 10&lt;br /&gt;
&lt;br /&gt;
widget = slicer.app.layoutManager().sliceWidget(layoutName)&lt;br /&gt;
view = widget.sliceView()&lt;br /&gt;
logic = widget.sliceLogic()&lt;br /&gt;
bounds = [0,]*6&lt;br /&gt;
logic.GetSliceBounds(bounds)&lt;br /&gt;
&lt;br /&gt;
for step in range(steps):&lt;br /&gt;
    offset = bounds[4] + step/(1.*steps) * (bounds[5]-bounds[4])&lt;br /&gt;
    logic.SetSliceOffset(offset)&lt;br /&gt;
    view.forceRender()&lt;br /&gt;
    image = qt.QPixmap.grabWidget(view).toImage()&lt;br /&gt;
    image.save(imagePathPattern % step)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Show a volume in the Slice Views ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
volumeNode = slicer.util.getNode('YourVolumeNode')&lt;br /&gt;
applicationLogic = slicer.app.applicationLogic()&lt;br /&gt;
selectionNode = applicationLogic.GetSelectionNode()&lt;br /&gt;
selectionNode.SetSecondaryVolumeID(volumeNode.GetID())&lt;br /&gt;
applicationLogic.PropagateForegroundVolumeSelection(0) &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
or&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
n =  slicer.util.getNode('YourVolumeNode')&lt;br /&gt;
for color in ['Red', 'Yellow', 'Green']:&lt;br /&gt;
    slicer.app.layoutManager().sliceWidget(color).sliceLogic().GetSliceCompositeNode().SetForegroundVolumeID(n.GetID())&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Change opacity of foreground volume in the Slice Views ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
lm = slicer.app.layoutManager()&lt;br /&gt;
sliceLogic = lm.sliceWidget('Red').sliceLogic()&lt;br /&gt;
compositeNode = sliceLogic.GetSliceCompositeNode()&lt;br /&gt;
compositeNode.SetForegroundOpacity(0.4)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Center the 3D View on the Scene ==&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
layoutManager = slicer.app.layoutManager()&lt;br /&gt;
threeDWidget = layoutManager.threeDWidget(0)&lt;br /&gt;
threeDView = threeDWidget.threeDView()&lt;br /&gt;
threeDView.resetFocalPoint()&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Display text in a 3D view or slice view ==&lt;br /&gt;
&lt;br /&gt;
The easiest way to show information overlaid on a viewer is to use corner annotations.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
view=slicer.app.layoutManager().threeDWidget(0).threeDView()&lt;br /&gt;
# Set text to &amp;quot;Something&amp;quot;&lt;br /&gt;
view.cornerAnnotation().SetText(vtk.vtkCornerAnnotation.UpperRight,&amp;quot;Something&amp;quot;)&lt;br /&gt;
# Set color to red&lt;br /&gt;
view.cornerAnnotation().GetTextProperty().SetColor(1,0,0)&lt;br /&gt;
# Update the view&lt;br /&gt;
view.forceRender()&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Turning off interpolation ==&lt;br /&gt;
&lt;br /&gt;
You can turn off interpolation for newly loaded volumes with this script from Steve Pieper.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def NoInterpolate(caller,event):&lt;br /&gt;
  for node in slicer.util.getNodes('*').values():&lt;br /&gt;
    if node.IsA('vtkMRMLScalarVolumeDisplayNode'):&lt;br /&gt;
      node.SetInterpolate(0)&lt;br /&gt;
	&lt;br /&gt;
slicer.mrmlScene.AddObserver(slicer.mrmlScene.NodeAddedEvent, NoInterpolate)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The below link explains how to put this in your startup script.&lt;br /&gt;
&lt;br /&gt;
http://www.na-mic.org/Wiki/index.php/AHM2012-Slicer-Python#Refining_the_code_and_UI_with_slicerrc&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Customize viewer layout ==&lt;br /&gt;
&lt;br /&gt;
Show a custom layout of a 3D view on top of the red slice view:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
customLayout = (&amp;quot;&amp;lt;layout type=\&amp;quot;vertical\&amp;quot; split=\&amp;quot;true\&amp;quot; &amp;gt;&amp;quot;&lt;br /&gt;
  &amp;quot; &amp;lt;item&amp;gt;&amp;quot;&lt;br /&gt;
  &amp;quot;  &amp;lt;view class=\&amp;quot;vtkMRMLViewNode\&amp;quot; singletontag=\&amp;quot;1\&amp;quot;&amp;gt;&amp;quot;&lt;br /&gt;
  &amp;quot;    &amp;lt;property name=\&amp;quot;viewlabel\&amp;quot; action=\&amp;quot;default\&amp;quot;&amp;gt;1&amp;lt;/property&amp;gt;&amp;quot;&lt;br /&gt;
  &amp;quot;  &amp;lt;/view&amp;gt;&amp;quot;&lt;br /&gt;
  &amp;quot; &amp;lt;/item&amp;gt;&amp;quot;&lt;br /&gt;
  &amp;quot; &amp;lt;item&amp;gt;&amp;quot;&lt;br /&gt;
  &amp;quot;  &amp;lt;view class=\&amp;quot;vtkMRMLSliceNode\&amp;quot; singletontag=\&amp;quot;Red\&amp;quot;&amp;gt;&amp;quot;&lt;br /&gt;
  &amp;quot;   &amp;lt;property name=\&amp;quot;orientation\&amp;quot; action=\&amp;quot;default\&amp;quot;&amp;gt;Axial&amp;lt;/property&amp;gt;&amp;quot;&lt;br /&gt;
  &amp;quot;   &amp;lt;property name=\&amp;quot;viewlabel\&amp;quot; action=\&amp;quot;default\&amp;quot;&amp;gt;R&amp;lt;/property&amp;gt;&amp;quot;&lt;br /&gt;
  &amp;quot;   &amp;lt;property name=\&amp;quot;viewcolor\&amp;quot; action=\&amp;quot;default\&amp;quot;&amp;gt;#F34A33&amp;lt;/property&amp;gt;&amp;quot;&lt;br /&gt;
  &amp;quot;  &amp;lt;/view&amp;gt;&amp;quot;&lt;br /&gt;
  &amp;quot; &amp;lt;/item&amp;gt;&amp;quot;&lt;br /&gt;
  &amp;quot;&amp;lt;/layout&amp;gt;&amp;quot;)&lt;br /&gt;
  &lt;br /&gt;
customLayoutId=501&lt;br /&gt;
&lt;br /&gt;
layoutManager = slicer.app.layoutManager()&lt;br /&gt;
layoutManager.layoutLogic().GetLayoutNode().AddLayoutDescription(customLayoutId, customLayout)                                         &lt;br /&gt;
layoutManager.setLayout(customLayoutId)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
See description of standard layouts (that can be used as examples) here:&lt;br /&gt;
https://github.com/Slicer/Slicer/blob/master/Libs/MRML/Logic/vtkMRMLLayoutLogic.cxx&lt;br /&gt;
&lt;br /&gt;
== Running an ITK filter in Python using SimpleITK ==&lt;br /&gt;
Open the &amp;quot;Sample Data&amp;quot; module and download &amp;quot;MR Head&amp;quot;, then paste the following snippet in Python interactor:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import SimpleITK as sitk&lt;br /&gt;
import sitkUtils&lt;br /&gt;
inputImage = sitkUtils.PullFromSlicer('MRHead')&lt;br /&gt;
filter = sitk.SignedMaurerDistanceMapImageFilter()&lt;br /&gt;
outputImage = filter.Execute(inputImage)&lt;br /&gt;
sitkUtils.PushToSlicer(outputImage,'outputImage')&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
More information:&lt;br /&gt;
* See the SimpleITK documentation for SimpleITK examples: http://www.itk.org/SimpleITKDoxygen/html/examples.html&lt;br /&gt;
* sitkUtils in Slicer is used for pushing and pulling images from Slicer to SimpleITK: https://github.com/Slicer/Slicer/blob/master/Base/Python/sitkUtils.py&lt;br /&gt;
&lt;br /&gt;
== Get current mouse coordinates in a slice view ==&lt;br /&gt;
&lt;br /&gt;
You can get 3D (RAS) coordinates of the current mouse cursor from the crosshair singleton node as shown in the example below:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def onMouseMoved(observer,eventid):  &lt;br /&gt;
  ras=[0,0,0]&lt;br /&gt;
  crosshairNode.GetCursorPositionRAS(ras)&lt;br /&gt;
  print(ras)&lt;br /&gt;
&lt;br /&gt;
crosshairNode=slicer.util.getNode('Crosshair') &lt;br /&gt;
crosshairNode.AddObserver(slicer.vtkMRMLCrosshairNode.CursorPositionModifiedEvent, onMouseMoved)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Thick slab reconstruction and maximum/minimum intensity volume projections ==&lt;br /&gt;
&lt;br /&gt;
Set up 'red' slice viewer to show thick slab reconstructed from 3 slices:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
sliceNode = slicer.mrmlScene.GetNodeByID('vtkMRMLSliceNodeRed')&lt;br /&gt;
appLogic = slicer.app.applicationLogic()&lt;br /&gt;
sliceLogic = appLogic.GetSliceLogic(sliceNode)&lt;br /&gt;
sliceLayerLogic = sliceLogic.GetBackgroundLayer()&lt;br /&gt;
reslice = sliceLayerLogic.GetReslice()&lt;br /&gt;
reslice.SetSlabModeToMean()&lt;br /&gt;
reslice.SetSlabNumberOfSlices(10) # mean of 10 slices will computed&lt;br /&gt;
reslice.SetSlabSliceSpacingFraction(0.3) # spacing between each slice is 0.3 pixel (total 10 * 0.3 = 3 pixel neighborhood)&lt;br /&gt;
sliceNode.Modified()&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Set up 'red' slice viewer to show maximum intensity projection (MIP):&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
sliceNode = slicer.mrmlScene.GetNodeByID('vtkMRMLSliceNodeRed')&lt;br /&gt;
appLogic = slicer.app.applicationLogic()&lt;br /&gt;
sliceLogic = appLogic.GetSliceLogic(sliceNode)&lt;br /&gt;
sliceLayerLogic = sliceLogic.GetBackgroundLayer()&lt;br /&gt;
reslice = sliceLayerLogic.GetReslice()&lt;br /&gt;
reslice.SetSlabModeToMax()&lt;br /&gt;
reslice.SetSlabNumberOfSlices(600) # use a large number of slices (600) to cover the entire volume&lt;br /&gt;
reslice.SetSlabSliceSpacingFraction(0.5) # spacing between slices are 0.5 pixel (supersampling is useful to reduce interpolation artifacts)&lt;br /&gt;
sliceNode.Modified()&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The projected image is available in a ''vtkImageData'' object by calling ''reslice.GetOutput()''.&lt;br /&gt;
&lt;br /&gt;
== Change default file type for nodes (that have never been saved yet) ==&lt;br /&gt;
Default node can be specified that will be used as a basis of all new storage nodes. This can be used for setting default file extension. For example, change file format to STL for model nodes:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
msn=slicer.vtkMRMLModelStorageNode()&lt;br /&gt;
msn.SetDefaultWriteFileExtension('stl')&lt;br /&gt;
slicer.mrmlScene.AddDefaultNode(msn)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Change file type for saving for all volumes (with already existing storage nodes) ==&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
requiredFileExtension = '.nia'&lt;br /&gt;
originalFileExtension = '.nrrd'&lt;br /&gt;
volumeNodes = slicer.mrmlScene.GetNodesByClass('vtkMRMLScalarVolumeNode')&lt;br /&gt;
volumeNodes.UnRegister(slicer.mrmlScene)&lt;br /&gt;
volumeNodes.InitTraversal()&lt;br /&gt;
volumeNode = volumeNodes.GetNextItemAsObject()&lt;br /&gt;
while volumeNode:&lt;br /&gt;
  volumeStorageNode = volumeNode.GetStorageNode()&lt;br /&gt;
  if not volumeStorageNode:&lt;br /&gt;
    volumeStorageNode = volumeNode.CreateDefaultStorageNode()&lt;br /&gt;
    slicer.mrmlScene.AddNode(volumeStorageNode)&lt;br /&gt;
    volumeStorageNode.UnRegister(None)&lt;br /&gt;
    volumeNode.SetAndObserveStorageNodeID(volumeStorageNode.GetID())&lt;br /&gt;
    volumeStorageNode.SetFileName(volumeNode.GetName()+requiredFileExtension)&lt;br /&gt;
  else:&lt;br /&gt;
    volumeStorageNode.SetFileName(volumeStorageNode.GetFileName().replace(originalFileExtension,requiredFileExtension))&lt;br /&gt;
  volumeNode = volumeNodes.GetNextItemAsObject()&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Segmentations ==&lt;br /&gt;
&lt;br /&gt;
For all operations accessing or manupilating the internals of a segmentation will need this import!&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import vtkSegmentationCorePython as vtkSegmentationCore&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Get a segment ===&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
segmentation = segmentationNode.GetSegmentation()&lt;br /&gt;
segment = segmentation.GetSegment(segmentID)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Get a representation of a segment ===&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
# Get representation from a single segment. If it does not exist, it will return None&lt;br /&gt;
segment.GetRepresentation(vtkSegmentationCore.vtkSegmentationConverter.GetSegmentationBinaryLabelmapRepresentationName()) # This gets the binary labelmap, but same idea for all others&lt;br /&gt;
&lt;br /&gt;
# Get representation for a single segment. Convert temporarily for that particular segment if needed. Applies parent transforms by default (if not desired, another argument needs to be added to the end: false)&lt;br /&gt;
slicer.vtkSlicerSegmentationsModuleLogic.GetSegmentBinaryLabelmapRepresentation(segmentationNode, segmentID, outputOrientedImageData) # Get labelmap&lt;br /&gt;
slicer.vtkSlicerSegmentationsModuleLogic.GetSegmentRepresentation(segmentationNode, segmentID, vtkSegmentationCore.vtkSegmentationConverter.GetSegmentationClosedSurfaceRepresentationName(), outputPolyData) # Any representation&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Convert using default path and conversion parameters ===&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
segmentation.CreateRepresentation(vtkSegmentationCore.vtkSegmentationConverter.GetSegmentationBinaryLabelmapRepresentationName()) # This creates binary labelmap, but same idea for all others&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Convert using custom path or conversion parameters ===&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
# Custom path&lt;br /&gt;
TODO&lt;br /&gt;
&lt;br /&gt;
# Custom conversion parameter&lt;br /&gt;
referenceGeometry=vtkSegmentationCore.vtkSegmentationConverter.SerializeImageGeometry(referenceImageData)&lt;br /&gt;
segmentation.SetConversionParameter(vtkSegmentationCore.vtkSegmentationConverter.GetReferenceImageGeometryParameterName(), referenceGeometry)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;/div&gt;</summary>
		<author><name>Kmader</name></author>
		
	</entry>
</feed>