PyNIfTI - Python-style access to NIfTI and ANALYZE files

1. What is NIfTI and what do I need PyNIfTI for?

NIfTI

NIfTI is a new Analyze-style data format, proposed by the NIfTI Data Format Working Group as a "short-term measure to facilitate inter-operation of functional MRI data analysis software packages".

Meanwhile a number of toolkits are NIfTI-aware (e.g. FSL, AFNI, SPM, Freesurfer and a to a certain degree also Brainvoyager). Additionally, dicomnifti allows the direct conversion from DICOM images into the NIfTI format.

With libniftiio there is a reference implementation of a C library to read, write and manipulate NIfTI images. The library source code is put into the public domain and a corresponding project is hosted at SourceForge.

In addition to the C library, there is also an IO library written in Java and Matlab functions to make use of NIfTI files from within Matlab.

Python

Unfortunately, it is not that trivial to read NIfTI images with Python. This is particularly sad, because there is a large number of easy-to-use, high-quality libraries for signal processing available for Python (e.g. SciPy).

Moreover Python has bindings to almost any important language/program in the fields of maths, statistics and/or engineering. If you want to use R to calculate some stats in a Python script, simply use RPy and pass any data to R. If you don't care about R, but Matlab is your one and only friend, there are at least two different Python modules to control Matlab from within Python scripts. Python is the glue between all those helpers and the Python user is able to combine as many tools as necessary to solve a given problem -- the easiest way.

PyNIfTI

PyNIfTI aims to provide easy access to NIfTI images from within Python. It uses SWIG-generated wrappers for the NIfTI reference library and provides the NiftiImage class for Python-style access to the image data.

While PyNIfTI is not yet complete (i.e. doesn't support everything the C library can do), it already provides access to the most important features of the NIfTI-1 data format and libniftiio capabilities. The following features are currently implemented:

Scripts

Some functions provided by PyNIfTI also might be useful outside the Python environment. Therefore I plan to add some command line scripts to the package.

Currently there is only one: pynifti_pst (pst: peristimulus timecourse). Using this script one can compute the signal timecourse for a certain condition for all voxels in a volume at once. This might be useful for exploring a dataset and accompanies similar tools like FSL's tsplot.

The output of pynifti_pst can be loaded into FSLView to simultaneously look at statistics and signal timecourses. Please see the corresponding example below.

Known issues aka bugs

2. License

PyNIfTI is written by Michael Hanke as free software (both beer and speech) and licensed under the MIT License.

3. Download

As PyNIfTI is still pretty young, a number of significant improvements/modifications are very likely to happen in the near future. If you discover any bugs or you are missing some features, please be sure to check the SVN repository (read below) if your problem is already solved.

Source code

Since June 2007 PyNIfTI is part of the niftilibs family. The PyNIfTI source code can be obtained from the Sourceforge project site.

Binary packages

GNU/Linux

PyNIfTI is available in recent versions of the Debian (since lenny) and Ubuntu (since gutsy in universe) distributions. The name of the binary package is python-nifti in both cases.

Binary packages for some additional Debian and (K)Ubuntu versions are also available. Please visit this page to read about how you have to setup your system to retrieve the PyNIfTI package via your package manager and stay in sync with future releases.

Windows

A binary installer for a recent Python version is available from the Sourceforge project site.

Macintosh

Unfortunately, no binary packages are available. I have no access to such a machine at the moment. But it is possible to build PyNIfTI from source on Mac OS X (see below for more information).

4. Installation

Compile from source: General instructions

PyNIfTI needs a few things to build and run properly:

Make sure that the compiled nifticlibs and the corresponding headers are available to your compiler. If they are located in a custom directory, you might have to specify --include-dirs and --library-dirs options to the build command below.

Once you have downloaded the sources, extract the tarball and enter the root directory of the extracted sources. A simple

python setup.py build_ext

should build the SWIG wrappers. If this has been done successfully, all you need to do is install the modules by invoking

sudo python setup.py install

If sudo is not configured (or even installed) you might have to use su instead.

Now fire up Python and try importing the module to see if everything is fine. It should look similar to this:

Python 2.4.4 (#2, Oct 20 2006, 00:23:25)
[GCC 4.1.2 20061015 (prerelease) (Debian 4.1.1-16.1)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import nifti
>>> 

Windows

It should be pretty straightforward to compile PyNIfTI for win32. The most convenient way seems to be using the Dev-Cpp IDE and the DevPak of the nifticlibs. Have a look into the toplevel Makefile of the PyNIfTI source distribution for some hints.

MacOS X and MacPython

When you are comiling PyNIfTI on MacOS X and want to use it with MacPython, please make sure that the NIfTI C libraries are compiled as fat binaries (compiled for both ppc and i386). Otherwise PyNIfTI extensions will not compile.

One can achieve this by adding both architectures to the CFLAGS definition in the toplevel Makefile of the NIfTI C library source code. Like this

CFLAGS = $(ANSI_FLAGS) -arch ppc -arch i386

Binary packages

GNU/Linux

If you have configured your system as described on this page all you have to do to install PyNIfTI is this:

apt-get update
apt-get install python-nifti

This should pull all necessary dependencies. If it doesn't, it's a bug that should be reported.

Windows

As always: click Next as long as necessary and finally Finish.

Troubleshooting

If you get an error when importing the nifti module in Python complaining about missing symbols your niftiio library contains references to some unresolved symbols. Try adding znzlib and zlib to the linker options the PyNIfTI setup.py, like this:

libraries = [ 'niftiio', 'znz', 'z' ],

5. Things to know

When accessing NIfTI image data through NumPy arrays the order of the dimensions is reversed. If the x, y, z, t dimensions of a NIfTI image are 64, 64, 32, 456 (as for example reported by nifti_tool), the shape of the NumPy array (e.g. as returned by NiftiImage.asarray()) will be: 456, 32, 64, 64.

This is done to be able to slice the data array much easier in the most common cases. For example, if you are interested in a certain volume of a timeseries it is much easier to write data[2] instead of data[:,:,:,2], right?.

6. Examples

The next sections contains some examples showing ways to use PyNIfTI to read and write imaging data from within Python to be able to process it with some random Python library.

All examples assume that you have imported the PyNIfTI module by invoking:

from nifti import *

a) Fileformat conversion

Open the MNI standard space template that is shipped with FSL. No filename extension is necessary as libniftiio determines it automatically:

nim = NiftiImage('avg152T1_brain')

The filename is available via the 'filename' attribute:

print nim.filename

yields 'avg152T1_brain.img'. This indicates an ANALYZE image. If you want to save this image as a single gzipped NIfTI file simply do:

nim.save('mni.nii.gz')

The filetype is determined from the filename. If you want to save to gzipped ANALYZE file pairs instead the following would be an alternative to calling the save() with a new filename.

nim.filename = 'mni_analyze.img.gz'
nim.save()

Please see the docstring of the NiftiImage.setFilename() method to learn how the filetypes are determined from the filenames.

b) NIfTI files from array data

The next code snipped demonstrates how to create a 4d NIfTI image containing gaussian noise. First we need to import the NumPy module

import numpy

Now generate the noise dataset. Let's generate noise for 100 volumes with 16 slices and a 32x32 inplane matrix.

noise = numpy.random.randn(100,16,32,32)

Please notice the order in which the dimensions are specified: (t, z, y, x).

The datatype of the array will most likely be float64 -- which can be verified by invoking noise.dtype.

Converting this dataset into a NIfTI image is done by invoking the NiftiImage constructor with the noise dataset as argument:

nim = NiftiImage(noise)

The relevant header information is extracted from the NumPy array. If you query the header information about the dimensionality of the image, it returns the desired values:

print nim.header['dim'] # yields: [4, 32, 32, 16, 100, 0, 0, 0]

First value shows the number of dimensions in the datset: 4 (good, that's what we wanted). The following numbers are dataset size on the x, y, z, t, u, v, w axis (NIfTI files can handle up to 7 dimensions). Please notice, that the order of dimensions is now 'correct': We have 32x32 inplane resolution, 16 slices in z direction and 100 volumes.

Also the datatype was set appropriately. The exprression:

nim.header['datatype'] == nifticlib.NIFTI_TYPE_FLOAT64

will evaluate to True.

To save the noise file to disk, just call the save() method:

nim.save('noise.nii.gz')

c) Select ROIs

Suppose you want to have the first ten volumes of the noise dataset we have just created in a separate file. First open the file (can be skipped if it is still open):

nim = NiftiImage('noise.nii.gz')

Now select the first ten volumes and store them to another file, while preserving as much header information as possible:

nim2 = NiftiImage(nim.data[:10], nim.header)
nim2.save('part.hdr.gz')

The NiftiImage constructor takes a dictionary with header information as an optional argument. Settings that are not determined by the array (e.g. size, datatype) are copied from the dictionary and stored to the new NIfTI image.

d) Linear detrending of timeseries (SciPy module is required for this example)

Let's load another 4d NIfTI file and perform a linear detrending, by fitting a straight line to the timeseries of each voxel and substract that fit from the data. Although this might sound complicated at first, thanks to the excellent SciPy module it is just a few lines of code.

nim = NiftiImage('timeseries.nii')

Depending on the datatype of the input image the detrending process might change the datatype from integer to float. As operations that change the (binary) size of the NIfTI image are not supported, we need to make a copy of the data and later create a new NIfTI image.

data = nim.asarray()

Now detrend the data along the time axis. Remember that the array has the time axis as its first dimension (in contrast to the NIfTI file where it is the 4th).

from scipy import signal
data_detrended = signal.detrend( data, axis=0 )

Finally, create a new NIfTI image using header information from the original source image.

nim_detrended = NiftiImage( data_detrended, nim.header)

e) Make a quick plot of a voxels timeseries (Gnuplot module is required)

Plotting is essential to get a 'feeling' for the data. The python interface to Gnuplot makes it really easy to plot something (e.g. when running Python interactively via IPython). Please note, that there are many other possibilities for plotting. Some examples are: using R via RPy or Matlab-style plotting via matplotlib.

However, using Gnuplot is really easy. First import the Gnuplot module and create the interface object.

from Gnuplot import Gnuplot
gp = Gnuplot()

We want the timeseries as a line plot and not just the datapoints, so let's talk with Gnuplot.

gp('set data style lines')

Now load a 4d NIfTI image

nim = NiftiImage('perfect_subject.nii.gz')

and finally plot the timeseries of voxel (x=20, y=30, z=12):

gp.plot(nim.data[:,12,30,20])

A Gnuplot window showing the timeseries should popup now (screenshot). Please read the Gnuplot Manual to learn what it can do -- and it can do a lot more than just simple line plots (have a look at this page if you are interested).

f) Show a slice of a 3d volume (Matplotlib module is required)

This example demonstrates howto use the Matlab-style plotting of Matplotlib to view a slice from a 3d volume.

This time I assume that a 3d nifti file is already opened and available in the nim3d object. At first we need to load the necessary Python module.

from pylab import *

If everything went fine, we can now view a slice (x,y):

imshow(nim3d.data[200], interpolation='nearest', cmap=cm.gray)
show()

It is necessary to call the show() function one time after importing pylab to actually see the image when running Python interactively (screenshot).

When you want to have a look at a yz-slice, NumPy array magic comes into play.

imshow(nim3d.data[::-1,:,100], interpolation='nearest', cmap=cm.gray)

The ::-1 notation causes the z-axis to be flipped in the images. This makes a much nicer screenshot, because the used example volume has the z-axis originally oriented upsidedown.

g) Compute and display peristimulus signal timecourse of multiple conditions with pynifti_pst and FSLView

Sometimes one wants to look at the signal timecourse of some voxel after a certain stimulation onset. An easy way would be to have some fMRI data viewer that displays a statistical map and one could click on some activated voxel and the peristimulus signal timecourse of some condition in that voxel would be displayed.

This can easily be done by using pynifti_pst and FSLView.

pynifti_pst comes with a manpage that explains all options and arguments. Basically pynifti_pst need a 4d image (e.g. an fMRI timeseries; possibly preprocessed/filtered) and some stimulus onset information. This information can either be given directly on the command line or is read from files. Additionally one can specify onsets as volume numbers or as onset times.

pynifti_pst understands the FSL custom EV file format so one can easily use those files as input.

An example call could look like this:

pynifti_pst --times --nvols 5 -p uf92.feat/filtered_func_data.nii.gz pst_cond_a.nii.gz uf92.feat/custom_timing_files/ev1.txt uf92.feat/custom_timing_files/ev2.txt

This computes a peristimulus timeseries using the preprocessed fMRI from a FEAT output directory and two custom EV files that both together make up condition A. --times indicates that the EV files list onset times (not volume ids) and --nvols requests the mean peristimulus timecourse for 4 volumes after stimulus onset (5 including onset). -p recodes the peristimulus timeseries into percent signalchange, where the onset is always zero and any following value is the signal change with respect to the onset volume.

This call produces a simple 4d NIfTI image that can be loaded into FSLView as any other timeseries. The following call can be used to display an FSL zmap from the above results path on top of some anatomy. Additionally the peristimulus timeseries of two conditions are loaded. This screenshot shows how it could look like. One of the nice features of FSLView is that its timeseries window can remember selected curves, which can be useful to compare signal timecourses from different voxels (blue and green line in the screenshot).

fslview pst_cond_a.nii.gz pst_cond_b.nii.gz uf92_ana.nii.gz uf92.feat/stats/zstat1.nii.gz -b 3,5

History

The full changelog is here.