irtk Python documentation

The aim of this module is to provide a simple and pythonic interface to IRTK (http://www.doc.ic.ac.uk/~dr/software/) by considering a medical image as a subclass of a numpy.ndarray containing information headers (dimension, orientation, origin and pixel size). By overloading __getitem__, slicing the array automatically updates the dimension and origin information. Images are manipulated in C++ as 4D images (IRTK behaviour), but flat dimensions are removed from Python thanks to an automated call to numpy.squeeze.

Indices are ordered TZYX, eg img[t,z,y,x], which corresponds to the raw pixel array of IRTK but differs from the img(x,y,z,t) C++ interface. Nonetheless, the order in the information header still correspond to the C++ order, that is to say img.header['dim'][0] corresponds to img.GetX() and is equal to img.shape[-1], img.header['pixelSize'][0] corresponds to img.GetXSize(), img.header['orientation'][0] corresponds to xaxis, and finally img.header['origin'][0] correspond to the X origin.

Below is a basic example:

# load the module
import irtk

# read an image
img = irtk.imread("5066_4.nii", dtype="float32")
print img.min(), img.max(), img.std() # methods inherited from numpy.ndarray

# write a PNG thumbnail after saturation, displaying a segmentation by thresholding
irtk.imshow(img.saturate(0.01,0.99), img > 2000, opacity=0.4, filename="thumbnail.png")
images/thumbnail.png

Below is a more complex example where we read several scans, register them all to the first one and compute an average volume:

import sys
import irtk

filenames = sys.argv[1:]

img1 = irtk.imread(filenames[0], dtype='float32')
img1 = img1.rescale()
weights = (img1 > 0).astype('int')

for f in filenames[1:]:
    img2 = irtk.imread( f, dtype='float32').rescale()
    t = img2.register(img1) # rigid registration
    img2 = img2.transform(t,target=img1) # linear interpolation by default
    img1 += img2
    weights += img2 > 0

img1 /= weights.astype('float32') + 0.000001 # avoid division by zero

# write image to disk
irtk.imwrite( "average.nii", img1)

# save thumbnail
irtk.imshow( img1, filename="average.png" )
images/average.png

Module reference

This module is a wrapper around IRTK (http://www.doc.ic.ac.uk/~dr/software/) written using Cython and a script to simulate templated code.

class irtk.Image

A subclass of numpy.ndarray holding the information from the NIFTI headers.

ImageToWorld(pt)

BEWARE: images are indexed as img[t,z,y,x], so for instance:

Examples

>>> tx,ty,tz = img.ImageToWorld( [(img.shape[2]-1)/2,(img.shape[1]-1)/2,(img.shape[0]-1)/2] )
WorldToImage(pt)

Returns integers

static __new__(img=None, header=None, copy=True, squeeze=True, force_neurological=False)

constructor

anisoDiff(iterations=5)

Anisotropic diffusion

as3D()

Force 3D shape

as4D()

Force 4D shape

bbox(crop=False, world=False, lcc=False)

Bounding box.

copy(dtype=None)

Returns a deep copy of the object.

dice(mask2, verbose=False)

Dice and overlap metrics

gaussianBlurring(sigma=1.0)

Gaussian blurring

gdt(mask, l=10.0)

Gaussian blurring

get_data(dtype=None, purpose='python')

Return pixel data.

get_header()

Safe copy of the headers.

mask(mask, threshold=0)

Mask image (after transforming the mask if necessary).

nb_pixels(world=False)

Return number of pixels.

neurological()

Return True if neurological order.

order()

Return either “radiological” or “neurological”.

orientation()

Return orientation.

origin()

Return origin as a 3D point.

radiological()

Return True if radiological order.

register(target, transformation=None)

Perform image registration.

resample(pixelSize=[1, 1, 1], interpolation='linear', gaussian_parameter=1.0, labels=False, label_smoothing=3.0)

Resample.

resample2D(pixelSize=[1, 1], interpolation='linear', gaussian_parameter=1.0)

Resample 2D slices.

rescale(min=0, max=255, nonzero=False)

Stretch contrast.

reset_header(header=None)

Reset header.

resize(shape, interpolation='linear')

Resize image with an affine transformation to force it to a given shape.

saturate(q0=1.0, q1=99.0, nonzero=False)

Saturate pixel intensities using numpy.percentile.

set_header(new_header)

Set the headers from a new dict.

thumbnail(seg=None, overlay=None, colors=None, opacity=0.5, step=2, unroll=False, index=None)

Create a thumbnail.

transform(transformation=None, target=None, interpolation='linear', gaussian_parameter=1.0, labels=False, label_smoothing=3.0)

Transform image.

irtk.imread(filename, dtype=None, empty=False, force_neurological=True)

Reads an image in a format understandable by IRTK.

Parameters:

filename : str

Name of the file to read.

dtype : str, optional (default: None)

Pixel type of the output image. If dtype is None, then the pixel type that has been used to write the file to disk is selected. Note that for the slope/intercept information to be taken into account in NIFTI files. If an integer type is requested and slope is not 1 or intercept not 0, then the following message will be printed on stderr:

irtkGenericImage<float>::Read: Ignore slope and intercept, use irtkGenericImage<float> or irtkGenericImage<double> instead

Returns:

img : irtk.Image

A subclass of numpy.ndarray holding the information from the NIFTI headers.

Examples

>>> img = irtk.imread( "input.nii", dtype="float32" )
>>> print img[0:2,0:2,0:2]
Image data:
array([[[ 455.95440674,  452.3605957 ],
        [ 424.96868896,  419.69546509]],

       [[ 462.80618286,  477.69018555],
        [ 433.81433105,  455.43170166]]], dtype=float32)

Image shape: (2, 2, 2)

Header:
{   'dim': array([2, 2, 2, 1], dtype=int32),
    'orientation': array([[ 0.18479464, -0.98071011,  0.06370761],
                          [ 0.34170858,  0.12489687,  0.93146984],
                          [ 0.92145872,  0.15036121, -0.35819733]]),
    'origin': array([  6.61570985,  35.65394667, -74.69886408,   0.        ]),
    'pixelSize': array([ 0.75,  0.75,  0.75,  1.  ])}
irtk.imwrite(filename, img)

Write image.

irtk.imshow(img, seg=None, overlay=None, colors=None, opacity=0.5, filename=None, unroll=False, index=None)

Display a 2D image

irtk.viewer(img, seg=None, overlay=None, colors=None, opacity=0.5, index=None)

Inline viewer for IPython Notebook

irtk.zeros(header, dtype='float32')

Similar to numpy.zeros, but with given headers.

irtk.ones(header, dtype='float32')

Similar to numpy.ones, but with given headers.

irtk.new_header(pixelSize=[1, 1, 1, 1], orientation=None, origin=[0, 0, 0, 0], dim=None)

Create new header.

irtk.PointsToImage(pts, header)

Create an image from a set of 3D points.

irtk.drawSphere(img, (x, y, z), rx, ry=None, rz=None)

Draw a sphere in a given image.

irtk.sphere((x, y, z), r, header)

Create an image with a filled sphere.

irtk.crf(img, labels, proba, l=1.0, sigma=0.0, sigmaZ=0.0)

Conditional Random Field.

irtk.graphcut(img, labels, l=1.0, sigma=0.0, sigmaZ=0.0)

Graphcut.

irtk.largest_connected_component(img, fill_holes=False)

Largest connected component

irtk.landmarks_to_spheres(seg, r=10)

Landmarks to spheres

class irtk.RigidTransformation(filename=None, matrix=None, tx=0, ty=0, tz=0, rx=0, ry=0, rz=0)

Rigid transformation class.

apply(img, target_header=None, interpolation='linear', gaussian_parameter=1.0)

Apply.

get_parameters()

Return parameters.

invert()

Invert.

matrix()

Return matrix.

write(filename)

Save to disk.

class irtk.AffineTransformation(filename=None, matrix=None, tx=0, ty=0, tz=0, rx=0, ry=0, rz=0, sx=0, sy=0, sz=0, sxy=0, syz=0, sxz=0)

Affine transformation class.

apply(img, target_header=None, interpolation='linear', gaussian_parameter=1.0)

Apply.

get_parameters()

Return parameters.

invert()

Invert.

matrix()

Return matrix.

write(filename)

Save to disk.

irtk.read_points(filename)

Read points from file.

irtk.registration_rigid_points(source, target, rms=False)

Point registration.

irtk.registration_affine_points(source, target, rms=False)

Point registration.

irtk.flirt2dof(flirt_matrix, image_target, image_source, return_matrix=False)

BUG? https://gitlab.doc.ic.ac.uk/sk1712/irtk/commit/343536a64678ba4edaf926b235a5a29a99b90392?view=parallel

See fsl/src/newimage/newimagefns.cc : raw_affine_transform()

flirt_matrix = np.loadtxt(r) https://gitlab.doc.ic.ac.uk/sk1712/irtk/blob/develop/packages/applications/flirt2dof.cc

class irtk.Cmd(program, *args, **kwargs)

Generic wrapper for command line applications using medical images.

irtk.disk(r)

2D disk for morphological operations.

Indices and tables

Table Of Contents

Next topic

Why Python?

This Page