Commit 30e8c661 authored by Paul McCarthy's avatar Paul McCarthy 🚵
Browse files

RF: little tweaks

parent 48aaf997
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
# `fslpy` # `fslpy`
**Important:** Portions of this practical require `fslpy` 2.9.0, due to be **Important:** Portions of this practical require `fslpy` 2.9.0, due to be
released with FSL 6.0.4, in Spring 2020. released with FSL 6.0.4, in Spring 2020.
[`fslpy`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/) is a [`fslpy`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/) is a
Python library which is built into FSL, and contains a range of functionality Python library which is built into FSL, and contains a range of functionality
for working with FSL and with neuroimaging data from Python. for working with FSL and with neuroimaging data from Python.
This practical highlights some of the most useful features provided by This practical highlights some of the most useful features provided by
`fslpy`. You may find `fslpy` useful if you are writing Python code to `fslpy`. You may find `fslpy` useful if you are writing Python code to
perform analyses and image processing in conjunction with FSL. perform analyses and image processing in conjunction with FSL.
* [The `Image` class, and other data types](#the-image-class-and-other-data-types) * [The `Image` class, and other data types](#the-image-class-and-other-data-types)
* [Creating images](#creating-images) * [Creating images](#creating-images)
* [Working with image data](#working-with-image-data) * [Working with image data](#working-with-image-data)
* [Loading other file types](#loading-other-file-types) * [Loading other file types](#loading-other-file-types)
* [NIfTI coordinate systems](#nifti-coordinate-systems) * [NIfTI coordinate systems](#nifti-coordinate-systems)
* [Transformations and resampling](#transformations-and-resampling) * [Transformations and resampling](#transformations-and-resampling)
* [FSL wrapper functions](#fsl-wrapper-functions) * [FSL wrapper functions](#fsl-wrapper-functions)
* [In-memory images](#in-memory-images) * [In-memory images](#in-memory-images)
* [Loading outputs into Python](#loading-outputs-into-python) * [Loading outputs into Python](#loading-outputs-into-python)
* [The `fslmaths` wrapper](#the-fslmaths-wrapper) * [The `fslmaths` wrapper](#the-fslmaths-wrapper)
* [The `FileTree`](#the-filetree) * [The `FileTree`](#the-filetree)
* [Describing your data](#describing-your-data) * [Describing your data](#describing-your-data)
* [Using the `FileTree`](#using-the-filetree) * [Using the `FileTree`](#using-the-filetree)
* [Building a processing pipeline with `FileTree`](#building-a-processing-pipeline-with-filetree) * [Building a processing pipeline with `FileTree`](#building-a-processing-pipeline-with-filetree)
* [The `FileTreeQuery`](#the-filetreequery) * [The `FileTreeQuery`](#the-filetreequery)
* [Calling shell commands](#calling-shell-commands) * [Calling shell commands](#calling-shell-commands)
* [The `runfsl` function](#the-runfsl-function) * [The `runfsl` function](#the-runfsl-function)
* [Submitting to the cluster](#submitting-to-the-cluster) * [Submitting to the cluster](#submitting-to-the-cluster)
* [Redirecting output](#redirecting-output) * [Redirecting output](#redirecting-output)
* [FSL atlases](#fsl-atlases) * [FSL atlases](#fsl-atlases)
* [Querying atlases](#querying-atlases) * [Querying atlases](#querying-atlases)
* [Loading atlas images](#loading-atlas-images) * [Loading atlas images](#loading-atlas-images)
* [Working with atlases](#working-with-atlases) * [Working with atlases](#working-with-atlases)
> **Note**: `fslpy` is distinct from `fslpython` - `fslpython` is the Python > **Note**: `fslpy` is distinct from `fslpython` - `fslpython` is the Python
> environment that is baked into FSL. `fslpy` is a Python library which is > environment that is baked into FSL. `fslpy` is a Python library which is
> installed into the `fslpython` environment. > installed into the `fslpython` environment.
Let's start with some standard imports and environment set-up: Let's start with some standard imports and environment set-up:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` ```
%matplotlib inline %matplotlib inline
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
import os import os
import os.path as op import os.path as op
import nibabel as nib import nibabel as nib
import numpy as np import numpy as np
import warnings import warnings
warnings.filterwarnings("ignore") warnings.filterwarnings("ignore")
np.set_printoptions(suppress=True, precision=4)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
And a little function that we can use to generate a simple orthographic plot: And a little function that we can use to generate a simple orthographic plot:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` ```
def ortho(data, voxel, fig=None, cursor=False, **kwargs): def ortho(data, voxel, fig=None, cursor=False, **kwargs):
"""Simple orthographic plot of a 3D array using matplotlib. """Simple orthographic plot of a 3D array using matplotlib.
:arg data: 3D numpy array :arg data: 3D numpy array
:arg voxel: XYZ coordinates for each slice :arg voxel: XYZ coordinates for each slice
:arg fig: Existing figure and axes for overlay plotting :arg fig: Existing figure and axes for overlay plotting
:arg cursor: Show a cursor at the `voxel` :arg cursor: Show a cursor at the `voxel`
All other arguments are passed through to the `imshow` function. All other arguments are passed through to the `imshow` function.
:returns: The figure and orthogaxes (which can be passed back in as the :returns: The figure and orthogaxes (which can be passed back in as the
`fig` argument to plot overlays). `fig` argument to plot overlays).
""" """
voxel = [int(round(v)) for v in voxel] voxel = [int(round(v)) for v in voxel]
data = np.asanyarray(data, dtype=np.float) data = np.asanyarray(data, dtype=np.float)
data[data <= 0] = np.nan data[data <= 0] = np.nan
x, y, z = voxel x, y, z = voxel
xslice = np.flipud(data[x, :, :].T) xslice = np.flipud(data[x, :, :].T)
yslice = np.flipud(data[:, y, :].T) yslice = np.flipud(data[:, y, :].T)
zslice = np.flipud(data[:, :, z].T) zslice = np.flipud(data[:, :, z].T)
if fig is None: if fig is None:
fig = plt.figure() fig = plt.figure()
xax = fig.add_subplot(1, 3, 1) xax = fig.add_subplot(1, 3, 1)
yax = fig.add_subplot(1, 3, 2) yax = fig.add_subplot(1, 3, 2)
zax = fig.add_subplot(1, 3, 3) zax = fig.add_subplot(1, 3, 3)
else: else:
fig, xax, yax, zax = fig fig, xax, yax, zax = fig
xax.imshow(xslice, **kwargs) xax.imshow(xslice, **kwargs)
yax.imshow(yslice, **kwargs) yax.imshow(yslice, **kwargs)
zax.imshow(zslice, **kwargs) zax.imshow(zslice, **kwargs)
if cursor: if cursor:
cargs = {'color' : (0, 1, 0), 'linewidth' : 1} cargs = {'color' : (0, 1, 0), 'linewidth' : 1}
xax.axvline( y, **cargs) xax.axvline( y, **cargs)
xax.axhline(data.shape[2] - z, **cargs) xax.axhline(data.shape[2] - z, **cargs)
yax.axvline( x, **cargs) yax.axvline( x, **cargs)
yax.axhline(data.shape[2] - z, **cargs) yax.axhline(data.shape[2] - z, **cargs)
zax.axvline( x, **cargs) zax.axvline( x, **cargs)
zax.axhline(data.shape[1] - y, **cargs) zax.axhline(data.shape[1] - y, **cargs)
for ax in (xax, yax, zax): for ax in (xax, yax, zax):
ax.set_xticks([]) ax.set_xticks([])
ax.set_yticks([]) ax.set_yticks([])
fig.tight_layout(pad=0) fig.tight_layout(pad=0)
return (fig, xax, yax, zax) return (fig, xax, yax, zax)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
And another function which uses FSLeyes for more complex plots: And another function which uses FSLeyes for more complex plots:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` ```
def render(cmdline): def render(cmdline):
import shlex import shlex
import IPython.display as display import IPython.display as display
prefix = '-of screenshot.png -hl -c 2 ' prefix = '-of screenshot.png -hl -c 2 '
try: try:
from fsleyes.render import main from fsleyes.render import main
main(shlex.split(prefix + cmdline)) main(shlex.split(prefix + cmdline))
except ImportError: except ImportError:
# fall-back for macOS - we have to run # fall-back for macOS - we have to run
# FSLeyes render in a separate process # FSLeyes render in a separate process
from fsl.utils.run import runfsl from fsl.utils.run import runfsl
prefix = 'render ' + prefix prefix = 'render ' + prefix
runfsl(prefix + cmdline, env={}) runfsl(prefix + cmdline, env={})
return display.Image('screenshot.png') return display.Image('screenshot.png')
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
<a class="anchor" id="the-image-class-and-other-data-types"></a> <a class="anchor" id="the-image-class-and-other-data-types"></a>
## The `Image` class, and other data types ## The `Image` class, and other data types
The The
[`fsl.data.image`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.image.html#fsl.data.image.Image) [`fsl.data.image`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.image.html#fsl.data.image.Image)
module provides the `Image` class, which sits on top of `nibabel` and contains module provides the `Image` class, which sits on top of `nibabel` and contains
some handy functionality if you need to work with coordinate transformations, some handy functionality if you need to work with coordinate transformations,
or do some FSL-specific processing. The `Image` class provides features such or do some FSL-specific processing. The `Image` class provides features such
as: as:
- Support for NIFTI1, NIFTI2, and ANALYZE image files - Support for NIFTI1, NIFTI2, and ANALYZE image files
- Access to affine transformations between the voxel, FSL and world coordinate - Access to affine transformations between the voxel, FSL and world coordinate
systems systems
- Ability to load metadata from BIDS sidecar files - Ability to load metadata from BIDS sidecar files
> The `Image` class behaves differently to the `nibabel.Nifti1Image`. For > The `Image` class behaves differently to the `nibabel.Nifti1Image`. For
> example, when you create an `Image` object, the default behaviour is to load > example, when you create an `Image` object, the default behaviour is to load
> the image data into memory. This is configurable however; take a look at > the image data into memory. This is configurable however; take a look at
> [the > [the
> documentation](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.image.html#fsl.data.image.Image) > documentation](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.image.html#fsl.data.image.Image)
> to explore all of the options. > to explore all of the options.
Some simple image processing routines are also provided - these are covered Some simple image processing routines are also provided - these are covered
[below](#image-processing). [below](#image-processing).
<a class="anchor" id="creating-images"></a> <a class="anchor" id="creating-images"></a>
### Creating images ### Creating images
It's easy to create an `Image` - you can create one from a file name: It's easy to create an `Image` - you can create one from a file name:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` ```
from fsl.data.image import Image from fsl.data.image import Image
stddir = op.expandvars('${FSLDIR}/data/standard/') stddir = op.expandvars('${FSLDIR}/data/standard/')
# load a FSL image - the file # load a FSL image - the file
# suffix is optional, just like # suffix is optional, just like
# in real FSL-land! # in real FSL-land!
std1mm = Image(op.join(stddir, 'MNI152_T1_1mm')) std1mm = Image(op.join(stddir, 'MNI152_T1_1mm'))
print(std1mm) print(std1mm)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
You can create an `Image` from an existing `nibabel` image: You can create an `Image` from an existing `nibabel` image:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` ```
# load a nibabel image, and # load a nibabel image, and
# convert it into an FSL image # convert it into an FSL image
nibimg = nib.load(op.join(stddir, 'MNI152_T1_1mm.nii.gz')) nibimg = nib.load(op.join(stddir, 'MNI152_T1_1mm.nii.gz'))
std1mm = Image(nibimg) std1mm = Image(nibimg)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Or you can create an `Image` from a `numpy` array: Or you can create an `Image` from a `numpy` array:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` ```
data = np.zeros((182, 218, 182)) data = np.zeros((182, 218, 182))
img = Image(data, xform=np.eye(4)) img = Image(data, xform=np.eye(4))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
If you have generated some data from another `Image` (or from a If you have generated some data from another `Image` (or from a
`nibabel.Nifti1Image`) you can use the `header` option to set `nibabel.Nifti1Image`) you can use the `header` option to set
the header information on the new image: the header information on the new image:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` ```
img = Image(data, header=std1mm.header) img = Image(data, header=std1mm.header)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
You can save an image to file via the `save` method: You can save an image to file via the `save` method:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` ```
img.save('empty') img.save('empty')
!ls !ls
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
`Image` objects have all of the attributes you might expect: `Image` objects have all of the attributes you might expect:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` ```
stddir = op.expandvars('${FSLDIR}/data/standard/') stddir = op.expandvars('${FSLDIR}/data/standard/')
std1mm = Image(op.join(stddir, 'MNI152_T1_1mm')) std1mm = Image(op.join(stddir, 'MNI152_T1_1mm'))
print('name: ', std1mm.name) print('name: ', std1mm.name)
print('file: ', std1mm.dataSource) print('file: ', std1mm.dataSource)
print('NIfTI version:', std1mm.niftiVersion) print('NIfTI version:', std1mm.niftiVersion)
print('ndim: ', std1mm.ndim) print('ndim: ', std1mm.ndim)
print('shape: ', std1mm.shape) print('shape: ', std1mm.shape)
print('dtype: ', std1mm.dtype) print('dtype: ', std1mm.dtype)
print('nvals: ', std1mm.nvals) print('nvals: ', std1mm.nvals)
print('pixdim: ', std1mm.pixdim) print('pixdim: ', std1mm.pixdim)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
and a number of useful methods: and a number of useful methods:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` ```
std2mm = Image(op.join(stddir, 'MNI152_T1_2mm')) std2mm = Image(op.join(stddir, 'MNI152_T1_2mm'))
mask2mm = Image(op.join(stddir, 'MNI152_T1_2mm_brain_mask')) mask2mm = Image(op.join(stddir, 'MNI152_T1_2mm_brain_mask'))
print(std1mm.sameSpace(std2mm)) print(std1mm.sameSpace(std2mm))
print(std2mm.sameSpace(mask2mm)) print(std2mm.sameSpace(mask2mm))
print(std2mm.getAffine('voxel', 'world')) print(std2mm.getAffine('voxel', 'world'))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
An `Image` object is a high-level wrapper around a `nibabel` image object - An `Image` object is a high-level wrapper around a `nibabel` image object -
you can always work directly with the `nibabel` object via the `nibImage` you can always work directly with the `nibabel` object via the `nibImage`
attribute: attribute:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` ```
print(std2mm) print(std2mm)
print(std2mm.nibImage) print(std2mm.nibImage)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
<a class="anchor" id="working-with-image-data"></a> <a class="anchor" id="working-with-image-data"></a>
### Working with image data ### Working with image data
You can get the image data as a `numpy` array via the `data` attribute: You can get the image data as a `numpy` array via the `data` attribute:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` ```
data = std2mm.data data = std2mm.data
print(data.min(), data.max()) print(data.min(), data.max())
ortho(data, (45, 54, 45)) ortho(data, (45, 54, 45))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
> Note that `Image.data` will give you the data in its underlying type, unlike > Note that `Image.data` will give you the data in its underlying type, unlike
> the `nibabel.get_fdata` method, which up-casts image data to floating-point. > the `nibabel.get_fdata` method, which up-casts image data to floating-point.
You can also read and write data directly via the `Image` object: You can also read and write data directly via the `Image` object:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` ```
slc = std2mm[:, :, 45] slc = std2mm[:, :, 45]
std2mm[0:10, :, :] *= 2 std2mm[0:10, :, :] *= 2
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Doing so has some advantages that may or may not be useful, depending on your Doing so has some advantages that may or may not be useful, depending on your
use-case: use-case:
- The image data will be kept on disk - only the parts that you access will - The image data will be kept on disk - only the parts that you access will
be loaded into RAM (you will also need to pass`loadData=False` when creating be loaded into RAM (you will also need to pass`loadData=False` when creating
the `Image` to achieve this). the `Image` to achieve this).
- The `Image` object will keep track of modifications to the data - this can - The `Image` object will keep track of modifications to the data - this can
be queried via the `saveState` attribute. be queried via the `saveState` attribute.
<a class="anchor" id="loading-other-file-types"></a> <a class="anchor" id="loading-other-file-types"></a>
### Loading other file types ### Loading other file types
The The
[`fsl.data`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.html#module-fsl.data) [`fsl.data`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.html#module-fsl.data)
package has a number of other classes for working with different types of FSL package has a number of other classes for working with different types of FSL
and neuroimaging data. Most of these are higher-level wrappers around the and neuroimaging data. Most of these are higher-level wrappers around the
corresponding `nibabel` types: corresponding `nibabel` types:
* The * The
[`fsl.data.bitmap.Bitmap`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.bitmap.html) [`fsl.data.bitmap.Bitmap`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.bitmap.html)
class can be used to load a bitmap image (e.g. `jpg, `png`, etc) and class can be used to load a bitmap image (e.g. `jpg`, `png`, etc) and
convert it to a NIfTI image. convert it to a NIfTI image.
* The * The
[`fsl.data.dicom.DicomImage`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.dicom.html) [`fsl.data.dicom.DicomImage`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.dicom.html)
class uses `dcm2niix` to load NIfTI images contained within a DICOM class uses `dcm2niix` to load NIfTI images contained within a DICOM
directory<sup>*</sup>.