Nitools

Basic Neuroimaging functionality for Nifti, Gifti, Cifti Data structures. Basic useful functions missing from nibabel and nilearn

Developed and maintained by the Diedrichsenlab.

Installation

For developement, please clone the Github repository: https://github.com/DiedrichsenLab/nitools

To simply use it, you can install the package with pip:

pip install neuroimagingtools

Nifti and Volume functions

Nifti and Volume-based tools for sampling and deforming

volume.affine_transform(x1, x2, x3, M)

Returns affine transform of x in vector

Parameters:
  • x1 (np-array) – X-coordinate of original (any size)

  • x2 (np-array) – Y-coordinate of original

  • x3 (np-array) – Z-coordinate of original

  • M (2d-array) – 4x4 transformation matrix

Returns:
  • x1 (np-array) – X-coordinate of transform

  • x2 (np-array) – Y-coordinate of transform

  • x3 (np-array) – Z-coordinate of transform

volume.affine_transform_mat(x, M)

Returns affine transform of x in matrix form

Parameters:
  • x (np-array) – 3xN array for original coordinates

  • M (2d-array) – 4x4 transformation matrix

Returns:

y (np-array) – 3xN array pof X-coordinate of transformed coordinaters

volume.coords_to_voxelidxs(coords, volDef)

Maps coordinates to voxel indices

INPUT:
coords (3*N matrix or 3xPxQ array):

(x,y,z) coordinates

voldef (nibabel object):

Nibabel object with attributes .affine (4x4 voxel to coordinate transformation matrix from the images to be sampled (1-based)) and shape (1x3 volume dimension in voxels)

OUTPUT:
linidxsrs (3xN-array or 3xPxQ matrix):

voxel indices

volume.coords_to_linvidxs(coords, vol_def, mask=False)

Maps coordinates to linear voxel indices

Parameters:
  • coords (3xN matrix or Qx3xN array) – (x,y,z) coordinates

  • vol_def (nibabel object) – Nibabel object with attributes .affine (4x4 voxel to coordinate transformation matrix from the images to be sampled (1-based)) and shape (1x3 volume dimension in voxels)

  • mask (bool) – If true, uses the mask image to restrict voxels (all outside = -1)

Returns:
  • linvidxs (N-array or QxN matrix) – Linear voxel indices

  • good (bool) – boolean array that tells you whether the index was in the mask

volume.euclidean_dist_sq(coordA, coordB)

Computes full matrix of square Euclidean distance between sets of coordinates

Parameters:
  • coordA (ndarray) – 3xP matrix of coordinates

  • coordB (ndarray) – 3xQ matrix of coordinats

Returns:

Dist (ndarray) – PxQ matrix of squared distances

volume.sample_image(img, xm, ym, zm, interpolation)

Return values after resample image

Parameters:
  • img (Nifti image) – Input Nifti Image

  • xm (np-array) – X-coordinate in world coordinates

  • ym (np-array) – Y-coordinate in world coordinates

  • zm (np-array) – Z-coordinate in world coordinates

  • interpolation (int) – 0: Nearest neighbor 1: Trilinear interpolation

Returns:

value (np-array) – Array contains all values in the image

volume.check_voxel_range(img, i, j, k)

Checks if i,j,k voxels coordinates are within an image

Parameters:
  • img (niftiImage or ndarray) – needs shape to determine voxels ranges

  • i (np.array) – all i-coordinates

  • j (np.array) – all j-coordinates

  • k (np.array) – all k-coordinates

Returns:

invalid (nd.array) – boolean array indicating whether i,j,k coordinates are invalid

volume.deform_image(source, deform, interpolation)

This function resamples an image into an atlas space, using a non-linear deformation map

Parameters:
  • source (NiftiImage) – Source nifti imate

  • deform (NiftiImage) – A (x,y,z,1,3) deformation image

  • interpolation (int) – 0: Nearest Nieghbour 1:trilinear interpolation

Returns:

NiftiImage – Resampled source imahe - has the same shape as deform

volume.change_nifti_numformat(infile, outfile, new_numformat='uint16', typecast_data=True)

Changes the number format of a nifti file and saves it.

Parameters:
  • infile (str) – file name of input file

  • outfile (str) – file name output file

  • new_numformat (str) – New number format. Defaults to ‘uint16’.

  • type_cast_data (bool) – If true, typecasts the data as well.

Note

typecast_data changes the data format and can lead to and wrap-around of values, as the data is typecasted as well. Do only when correcting a previous mistake in processing.

Gifti functions

Nitools Gifti functions

gifti.make_func_gifti(data, anatomical_struct='Cerebellum', column_names=None)

Generates a function GiftiImage from a numpy array

Parameters:
  • data (np.array) – num_vert x num_col data

  • anatomical_struct (string) – Anatomical Structure default= ‘Cerebellum’

  • column_names (list) – List of strings for names for columns

Returns:

FuncGifti (GiftiImage) – functional Gifti Image

gifti.make_label_gifti(data, anatomical_struct='Cerebellum', labels=None, label_names=None, column_names=None, label_RGBA=None)

Generates a label GiftiImage from a numpy array

Parameters:
  • data (np.array) – num_vert x num_col data

  • anatomical_struct (string) – Anatomical Structure for the Meta-data. default: ‘Cerebellum’

  • labels (list) – Numerical values in data indicating the labels. default: np.unique(data)

  • label_names (list) – List of strings for names for labels

  • column_names (list) – List of strings for names for columns

  • label_RGBA (list) – List of rgba vectors for labels

Returns:

gifti (GiftiImage) – Label gifti image

gifti.make_surf_gifti(vertices, faces, normals, mat, anatomical_struct='CortexLeft')

Generates a surface GiftiImage from a surface

Parameters:
  • vertices (np.array) – num_vert x 3 array of vertices

  • faces (np.array) – num_faces x 3 array of faces

  • normals (np.array) – num_vert x 3 array of normals

  • mat (np.array) – a 4x4 affine matrix

  • anatomical_struct – Anatomical Structure for the Meta-data

Returns:

gifti (GiftiImage) – Surface gifti image

Examples

  1. Load vertices and faces from a surface file

    surf = nb.load(‘sub-01.L.pial.32k.surf.gii’) vertices = surf.agg_data(‘NIFTI_INTENT_POINTSET’) faces = surf.agg_data(‘NIFTI_INTENT_TRIANGLE’)

2.1 Load normals (from surf file directly if available)

normals = surf.agg_data(‘NIFTI_INTENT_NORMAL’)

2.2 Load normals (from a separate file)

norm_file = ‘sub-01.L.norm.32k.shape.gii’ normals = norm_file.agg_data()

  1. Input mat is a 4x4 affine matrix, e.g.:

    mat = np.eye(4)

gifti.get_gifti_data_matrix(gifti)

Returns the data matrix contained in a GiftiImage.

Parameters:

gifti (giftiImage) – Nibabel Gifti image

Returns:

data (ndarray) – Concatinated data from the Gifti file

gifti.get_gifti_column_names(gifti)

Returns the column names from a GiftiImage

Parameters:

gifti (gifti image) – Nibabel Gifti image

Returns:

names (list) – List of column names from gifti object attribute data arrays

gifti.get_gifti_colortable(gifti, ignore_zero=False)

Returns the RGBA color table and matplotlib cmap from gifti object

Parameters:
  • gifti (gifti image) – Nibabel GiftiImage

  • ignore_zero (bool) – Skip the color corresponding to label 0? Defaults to False

Returns:
  • rgba (np.ndarray) – N x 4 of RGB values

  • cmap (mpl obj) – matplotlib colormap

gifti.get_gifti_anatomical_struct(gifti)

Returns the primary anatomical structure for a GiftiImage

Parameters:

gifti (gifti image) – Nibabel Gifti image

Returns:

anatStruct (string) – AnatomicalStructurePrimary attribute from gifti object

gifti.get_gifti_labels(gifti)

Returns labels from gifti Image

Parameters:

gifti (gifti image) – Nibabel Gifti image

Returns:

labels (list) – labels from gifti object

Cifti functions

General tools for manipulating Cifti2Images

cifti.make_label_cifti(data, bm_axis, labels=None, label_names=None, column_names=None, label_RGBA=None)

Generates a label Cifti2Image from a numpy array

Parameters:
  • data (np.array) – num_vert x num_col data

  • bm_axis – The corresponding brain model axis (voxels or vertices)

  • labels (list) – Numerical values in data indicating the labels - defaults to np.unique(data)

  • label_names (list) – List of strings for names for labels

  • column_names (list) – List of strings for names for columns

  • label_RGBA (list) – List of rgba vectors for labels

Returns:

cifti (GiftiImage) – Label gifti image

cifti.join_giftis_to_cifti(giftis, mask=[None, None], seperate_labels=False, join_zero=True)

Combines a left and right hemispheric Gifti file into a single Cifti file that contains both hemisphere

Parameters:
  • giftis (list) – List of 2 Gifti images or list of 2 file names to be merged: gives warning if not left and right hemisphere

  • mask (list, optional) – Mask for each hemisphere (only vertices within mask will be used). Defaults to [None,None]. Can be set to list of giftis, filesnames, or nd-arrays

  • seperate_labels (bool, optional) – False (default): Simple merges the two files True: Offsets the label for the right hemisphere, and prepend a L/R to label (default = False)

  • join_zero (bool, optional) – If separate labels, and joint_zero set to true, the zero-label will be joined for the two hemispheres, resulting label less overall. (default = True)

Returns:

cifti_img – Cifti-image

cifti.split_cifti_to_giftis(cifti_img, type='label', column_names=None)

Splits a Cifti files with cortical data into two gifti objects

Parameters:
  • cifti_img (nb.CiftiImage) – C

  • type (str) – Type of data “label”/”func”

  • column_names (list, optional) – Column names for Gifti header. Defaults to None.

Returns:

gii (list) – List of two GiftiImages

cifti.volume_from_cifti(cifti, struct_names=[])

Gets the 4D nifti object containing the data for all subcortical (volume-based) structures

Parameters:
  • cifti (ciftiImage) – cifti object containing the data

  • struct_names (list or None) – List of structure names that are included defaults to None

Returns:

nii_vol (niftiImage) – nifti object containing the data

cifti.surf_from_cifti(cifti, struct_names=['cortex_left', 'cortex_right'])

Gets the data for cortical surface vertices (Left and Right) from normal cifti or parcellated cifti

Parameters:
  • cifti (cifti2Image) – Input cifti that contains surface data Dimension 0 is data, Dimension 1 is brain model or parcel

  • struct_names (list) – Names of anatomical structures (in cifti format). Defaults to left and right hemisphere

Returns:

list of ndarrays – Data for all surface, with data x numVert for each surface

cifti.smooth_cifti(cifti_input, cifti_output, left_surface, right_surface, surface_sigma=2.0, volume_sigma=0.0, direction='COLUMN')

smoothes a cifti file on the direction specified by “direction”

Parameters:
  • cifti_input (str) – path to the input cifti file

  • cifti_output (str) – path to the output cifti file

  • left_surface (str) – path to the left surface

  • right_surface (str) – path to the right surface

  • surface_sigma (float) – sigma for surface smoothing

  • volume_sigma (float) – sigma for volume smoothing

  • direction (str) – direction of smoothing, either “ROW” or “COLUMN”

Color maps and files

Other neuroimaging file formats

color.read_lut(fname)

Reads a Lookuptable file

Parameters:

fname (str) – Filename

Returns:
  • index (ndarray) – Numerical keys

  • colors (ndarray) – N x 3 ndarray of colors

  • labels (list) – List of labels

color.save_lut(fname, index, colors, labels)

Save a set of colors and labels as a LUT file

Parameters:
  • fname (str) – File name

  • index (ndarray) – Numerical key

  • colors (ndarray) – List or RGB tuples 0-1

  • labels (list) – Names of categories

color.save_cmap(fname, colors)

Save a set of colors to a FSLeyes compatible cmap file

Parameters:
  • fname (str) – File name

  • colors (ndarray) – List or RGB tuples 0-1

Border functions

Other neuroimaging file formats

class border.Border(name=None, vertices=None, weights=None)

Border class

name

Name of the border

Type:

str

vertices

Vertices of the border

Type:

np.array

weights

Weights of Barycentric coordinates

Type:

np.array

get_coords(surf)

Gets coords the border onto a surface Barycentric coordinates are transformed into Euclidean coordinates

Parameters:

surf (str or nibabel) – Surface file

Returns:

coords (np.array) – Coordinates of the border on the surface

border.read_borders(fname)

Reads a Workbench border file from XML format into a list of Border objects

Parameters:

fname (str) – Filename

Returns:
  • borders (list) – List of border objects

  • binfo (dict) – Dictionary of border-file information

border.save_borders(borders, binfo, fname)

Saves a list of borders to a connectome workbench border file

Parameters:
  • borders (list) – List of border objects

  • binfo (dict) – Dictionary of border-file information

  • fname (str) – filename

border.project_border(XYZ, surf)

Project a set of points onto a surface

Parameters:
  • XYZ (ndarray) – Nx3 array of points

  • surf (GiftiImage) – nibabel surface object

Returns:
  • vertices – Nx3 array of vertices

  • weights – Nx3 array of weights

border.resample_border(border, surf, stepsize=5)

Resample a border with a fixed step size

Parameters:
  • border (Border) – Border object

  • surf (GiftiImage) – nibabel surface object

  • step (float) – Step size in mm

Returns:

border – Border object