Difference between revisions of "Slicer3:Python"

From Slicer Wiki
Jump to: navigation, search
Line 2: Line 2:
 
In post-3.2 Slicer3, Python support is currently disabled by default.  However, it is easy to enable and should compile on all tested platform (Mac, Windows, Linux).  Though [http://matplotlib.sourceforge.net/ matplotlib] is still not properly interacting with Slicer3, NumPy and Python support should work well for all platforms.  [[Slicer3:Execution_Model_Documentation:Python | Python command line modules]] are well supported, as is building full GUI modules in Python (documentation coming soon).
 
In post-3.2 Slicer3, Python support is currently disabled by default.  However, it is easy to enable and should compile on all tested platform (Mac, Windows, Linux).  Though [http://matplotlib.sourceforge.net/ matplotlib] is still not properly interacting with Slicer3, NumPy and Python support should work well for all platforms.  [[Slicer3:Execution_Model_Documentation:Python | Python command line modules]] are well supported, as is building full GUI modules in Python (documentation coming soon).
  
 +
 +
== Python for scientific computing ==
 +
Python has a fairly comprehensive package for scientific computing called [http://scipy.org SciPy].  Of main interest to Slicer users/developers is [http://numpy.scipy.org NumPy].  NumPy provides most of the features of the Matlab image processing toolbox and numeric computations, but in an Open Source package.  A compelling reason to use NumPy is the ease of interaction and integration with Slicer3.
 +
 +
== Slicer3 and Python ==
 
==== Enabling Python in the Slicer Build====
 
==== Enabling Python in the Slicer Build====
 
# Edit slicer_variables.tcl
 
# Edit slicer_variables.tcl
Line 11: Line 16:
  
 
  Macintosh:Slicer3 blezek$ Scripts/getbuildtest.tcl
 
  Macintosh:Slicer3 blezek$ Scripts/getbuildtest.tcl
 
== Python for scientific computing ==
 
Python has a fairly comprehensive package for scientific computing called [http://scipy.org SciPy].  Of main interest to Slicer users/developers is [http://numpy.scipy.org NumPy].  NumPy provides most of the features of the Matlab image processing toolbox and numeric computations, but in an Open Source package.  A compelling reason to use NumPy is the ease of interaction and integration with Slicer3.
 
 
== Slicer3 and Python ==
 
At the recent [[Slicer3:MiniRetreat February 7-8, 2007|Slicer3 Mini-Retreat]], a [http://python.org Python] interpreter was added to the Slicer build.  This may be built by following these steps.
 
 
# Install [http://www.python.org/download/ Python 2.4 or later]
 
# Install [http://sourceforge.net/project/showfiles.php?group_id=1369&package_id=175103 NumPy], be sure to find the correct installer for your version of Python
 
## '''Optional:''' Install [http://www.scipy.org/Download SciPy] which is used in the tutorials below
 
## '''Optional:''' Install [http://sourceforge.net/projects/matplotlib MatPlotLib], a NumPy plotting package developed to emulate Matlab's plotting capabilities.  Used in the tutorials.
 
# Run CMake setting the "USE_PYTHON" option, and setting the path to your Python installation
 
## Check Advanced Options
 
## Verify that CMake found your Python installation
 
# Compile Slicer
 
## It is best to clean the '''SlicerBaseGUI''' project, as this may not be correctly rebuilt.
 
## A new build target '''SlicerGUIPython''' should appear
 
  
 
A new menu command '''Python Interpreter''' should appear on the Window menu.
 
A new menu command '''Python Interpreter''' should appear on the Window menu.

Revision as of 01:52, 18 August 2008

Home < Slicer3:Python

Status of Python in Slicer

In post-3.2 Slicer3, Python support is currently disabled by default. However, it is easy to enable and should compile on all tested platform (Mac, Windows, Linux). Though matplotlib is still not properly interacting with Slicer3, NumPy and Python support should work well for all platforms. Python command line modules are well supported, as is building full GUI modules in Python (documentation coming soon).


Python for scientific computing

Python has a fairly comprehensive package for scientific computing called SciPy. Of main interest to Slicer users/developers is NumPy. NumPy provides most of the features of the Matlab image processing toolbox and numeric computations, but in an Open Source package. A compelling reason to use NumPy is the ease of interaction and integration with Slicer3.

Slicer3 and Python

Enabling Python in the Slicer Build

  1. Edit slicer_variables.tcl
    1. Change "set ::USE_PYTHON "off"" to "on"
  2. [Optional:] If you prefer to use your system Python installation, change set ::USE_SYSTEM_PYTHON "false" to "true"
    1. This will give an error under Linux and Windows, but it can be easily fixed by adding the system path for Python, just search for "if { $::USE_SYSTEM_PYTHON } {"

Build Slicer3 using "getbuildtest.tcl", i.e.:

Macintosh:Slicer3 blezek$ Scripts/getbuildtest.tcl

A new menu command Python Interpreter should appear on the Window menu.

PythonMenu.png

This command should bring up the Python Console window.

PythonConsole.png

Basic Slicer/Python tutorial

Note: this is initial documentation only, and is subject to change as the API evolves.

The Slicer Python interpreter has access to all Python modules referenced by the environment variable PYTHONPATH as well as the Slicer internal module. The Slicer module also supports the interface between Slicer Volume Nodes and NumPy. It would be instructive for the reader to review the NumPy documentation. For serious users of NumPy, there is the Guide to NumPy by Travis Oliphant for purchase.

In this example, a volume named T2_MGH.nhdr has been loaded into Slicer.

Important! Currently, Python does not increment the reference counter for the vtkMRMLVolumeNode, thus if the volume is unloaded from within Slicer, NumPy will have a reference to freed memory. This should be addressed soon.

Listing available datasets

>>> import Slicer
>>> help ( Slicer.ListVolumeNodes )
Help on function ListVolumeNodes in module Slicer:

ListVolumeNodes()
    Returns a dictionary containing the index and
    vtkMRMLVolumeNodes currently loaded by Slicer

>>> nodes = Slicer.ListVolumeNodes()
>>> nodes
{0: vtkTemp1554}
>>> t2 = nodes[0]
>>> t2.GetName()
'T2_MGH.nhdr'
>>> t2.GetSpacing()
'0.84375 0.84375 0.84 '
>>> print t2.ListMethods()
<<<Output truncated>>>

Help on most Python functions is available using the built in help() command. This example shows how to list the available MRML volumes loaded by Slicer, select the volume you would like to use, and print some information from the volume. An exhaustive list of methods defined on each volume can be found using the ListMethods() method on the volume node.

NumPy tutorial

Python and NumPy give direct access to the volume data in Slicer by wrapping the image data in a NumPy array object through the .ToArray() method on the volume node. This tutorial assumes you have installed SciPy.

>>> # Access the image data directly
>>> data = t2.GetImageData().ToArray()
>>> print data
[[[ 0  0  0 ...,  0  0  0]
  [ 0  0  1 ...,  0  1  0]
  [ 0  0  0 ...,  0  0  0]
  ..., 
  [ 0  8  0 ...,  0  1  2]
  [ 0  0  0 ...,  4  1  2]
  [ 0  0  2 ...,  6  0  2]]

<<< Some output truncated >>> 

 [[ 0  0  0 ...,  0  0  0]
  [ 0  0  0 ...,  0  0  0]
  [ 0  0  0 ...,  0  0  0]
  ..., 
  [ 0  3  3 ...,  0  0  8]
  [ 0  6  0 ...,  5  3 13]
  [ 0  5  1 ...,  9  3  8]]]
>>> # Load the image filtering package from scipy
>>> import scipy.ndimage
>>> # Filter into a new array
>>> temp = scipy.ndimage.gaussian_filter ( data, 2.0 )
>>> # Copy back into Slicer
>>> data[:] = temp[:]
>>> t2.Modified()

Before:

PythonBefore.png

After:

PythonAfter.png

MatPlotLib tutorial

The MatPlotLib interface should be familiar to Matlab users, as the design philosophy is the same (indeed, MatPlotLib is nearly identical, but free!). This tutorial assumes you have installed MatPlotLib and have followed the tutorials above.

>>> # import MatPlotLib via pylab functions so we can refer to them directly
>>> from pylab import *
>>> imshow ( data[128,:,:] )
>>> # Instruct pylab to show our plots... hit return to continue entering commands.
>>> show()

Pythonimshow.png

>>> # Clear the plot
>>> clf()
>>> # Be warned: hist takes some time on an image
>>> hist ( data, 20 )
(array([10813255,  1065860,  1106656,   802983,   761897,   730788,
         637444,   470011,   297534,   152217,    82640,    43318,
          26781,    16333,    11464,     8095,     6386,     4084,
           1419,      195]), array([   0. ,   31.5,   63. ,   94.5,  126. ,  157.5,  189. ,  220.5,
        252. ,  283.5,  315. ,  346.5,  378. ,  409.5,  441. ,  472.5,
        504. ,  535.5,  567. ,  598.5]), <a list of 20 Patch objects>)

Pythonhist.png

Where to go from here

Far from exhaustive, this documentation is intended to whet the appitite of researchers who love the power of Matlab, but feel trapped inside, unable to break out and deploy applications. This Python interface to Slicer is intended to help! Here are some selected resources to begin to understand the power of what the combined NumPy - Slicer package offers.