Python API

Note

The Python API is not stable yet, so be prepared to update your code with SCT updates.

Segmentation

Spinal Cord Segmentation

deepseg

Deals with models for deepseg module. Available models are listed under MODELS.

spinalcordtoolbox.deepseg.models.folder(name_model)[source]

Return absolute path of deep learning models.

Parameters

name – str: Name of model.

Returns

str: Folder to model

spinalcordtoolbox.deepseg.models.get_metadata(folder_model)[source]

Get metadata from json file located in folder_model

Parameters

path_model – str: Model folder

Returns

dict

spinalcordtoolbox.deepseg.models.get_required_contrasts(task)[source]

Get required contrasts according to models in tasks.

Returns

list: List of required contrasts

spinalcordtoolbox.deepseg.models.install_default_models()[source]

Download all default models and install them under SCT installation dir.

Returns

None

spinalcordtoolbox.deepseg.models.install_model(name_model)[source]

Download and install specified model under SCT installation dir.

Parameters

name – str: Name of model.

Returns

None

spinalcordtoolbox.deepseg.models.is_valid(path_model)[source]

Check if model has the necessary files and follow naming conventions: - Folder should have the same name as the enclosed files.

Parameters

path_model – str: Absolute path to folder that encloses the model files.

spinalcordtoolbox.deepseg.models.list_tasks()[source]

Display available tasks with description. :return: dict: Tasks that are installed

deepseg_sc

spinalcordtoolbox.deepseg_sc.core.apply_intensity_normalization(im_in, params=None)[source]

Standardize the intensity range.

spinalcordtoolbox.deepseg_sc.core.crop_image_around_centerline(im_in, ctr_in, crop_size)[source]

Crop the input image around the input centerline file.

spinalcordtoolbox.deepseg_sc.core.deep_segmentation_spinalcord(im_image, contrast_type, ctr_algo='cnn', ctr_file=None, brain_bool=True, kernel_size='2d', threshold_seg=None, remove_temp_files=1, verbose=1)[source]

Main pipeline for CNN-based segmentation of the spinal cord.

Parameters
  • im_image

  • contrast_type – {‘t1’, ‘t2’, t2s’, ‘dwi’}

  • ctr_algo

  • ctr_file

  • brain_bool

  • kernel_size

  • threshold_seg – Binarization threshold (between 0 and 1) to apply to the segmentation prediction. Set to -1 for no binarization (i.e. soft segmentation output)

  • remove_temp_files

  • verbose

Returns

spinalcordtoolbox.deepseg_sc.core.find_centerline(algo, image_fname, contrast_type, brain_bool, folder_output, remove_temp_files, centerline_fname)[source]

Assumes RPI orientation

Parameters
  • algo

  • image_fname

  • contrast_type

  • brain_bool

  • folder_output

  • remove_temp_files

  • centerline_fname

Returns

spinalcordtoolbox.deepseg_sc.core.heatmap(im, model, patch_shape, mean_train, std_train, brain_bool=True)[source]

Compute the heatmap with CNN_1 representing the SC localization.

spinalcordtoolbox.deepseg_sc.core.scale_intensity(data, out_min=0, out_max=255)[source]

Scale intensity of data in a range defined by [out_min, out_max], based on the 2nd and 98th percentiles.

spinalcordtoolbox.deepseg_sc.core.scan_slice(z_slice, model, mean_train, std_train, coord_lst, patch_shape, z_out_dim)[source]

Scan the entire axial slice to detect the centerline.

spinalcordtoolbox.deepseg_sc.core.segment_2d(model_fname, contrast_type, input_size, im_in)[source]

Segment data using 2D convolutions.

Returns

seg_crop.data: ndarray float32: Output prediction

spinalcordtoolbox.deepseg_sc.core.segment_3d(model_fname, contrast_type, im_in)[source]

Perform segmentation with 3D convolutions.

Returns

seg_crop.data: ndarray float32: Output prediction

spinalcordtoolbox.deepseg_sc.core.uncrop_image(ref_in, data_crop, x_crop_lst, y_crop_lst, z_crop_lst)[source]

Reconstruct the data from the cropped segmentation.

spinalcordtoolbox.deepseg_sc.postprocessing.fill_holes_2d(z_slice)[source]

Fill holes in the segmentation.

Parameters

z_slice – int 2d-array: Input 2D segmentation.

Returns

int 2d-array: Output segmentation with holes filled

spinalcordtoolbox.deepseg_sc.postprocessing.keep_largest_object(z_slice_bin, x_cOm, y_cOm)[source]

Keep the largest connected object per z_slice and fill little holes. Note: This function only works for binary segmentation.

Parameters
  • z_slice – int 2d-array: Input 2d segmentation

  • x_cOm – int: X center of mass of the segmentation for the previous 2d slice

  • y_cOm – int: Y center of mass of the segmentation for the previous 2d slice

Returns

z_slice: int 2d-array: Processed 2d segmentation

spinalcordtoolbox.deepseg_sc.postprocessing.post_processing_volume_wise(im_seg)[source]

Post processing function to clean the input segmentation: fill holes, remove edge outlier, etc. Note: This function is compatible with soft segmentation (i.e. float between 0-1).

GM/WM Segmentation

deepseg_gm

class spinalcordtoolbox.deepseg_gm.deepseg_gm.CroppedRegion(original_shape, starts, crops)[source]

This class holds cropping information about the volume center crop.

Constructor for the CroppedRegion.

Parameters
  • original_shape – the original volume shape.

  • starts – crop beginning (x, y).

  • crops – the crops (x, y).

pad(image)[source]

This method will pad an image using the saved cropped region.

Parameters

image – the image to pad.

Returns

padded image.

class spinalcordtoolbox.deepseg_gm.deepseg_gm.DataResource(dirname)[source]

This class is responsible for resource file management (such as loding models).

Initialize the resource with the directory name context.

Parameters

dirname – the root directory name.

get_file_path(filename)[source]

Get the absolute file path based on the data root directory.

Parameters

filename – the filename.

class spinalcordtoolbox.deepseg_gm.deepseg_gm.StandardizationTransform(mean, std)[source]

This transformation will standardize the volume according to the specified mean/std.dev.

Constructor for the normalization transformation.

Parameters
  • mean – the mean parameter

  • std – the standar deviation parameter

class spinalcordtoolbox.deepseg_gm.deepseg_gm.VolumeStandardizationTransform[source]

This transformation will standardize the volume with the parameters estimated from the volume itself.

spinalcordtoolbox.deepseg_gm.deepseg_gm.check_backend()[source]

This function will check for the current backend and then it will warn the user if the backend is theano.

spinalcordtoolbox.deepseg_gm.deepseg_gm.crop_center(img, cropx, cropy)[source]

This function will crop the center of the volume image.

Parameters
  • img – image to be cropped.

  • cropx – x-coord of the crop.

  • cropy – y-coord of the crop.

Returns

(cropped image, cropped region)

spinalcordtoolbox.deepseg_gm.deepseg_gm.segment_file(input_filename, output_filename, model_name, threshold, verbosity, use_tta)[source]

Segment a volume file.

Parameters
  • input_filename – the input filename.

  • output_filename – the output filename.

  • model_name – the name of model to use.

  • threshold – threshold to apply in predictions (if None, no threshold will be applied)

  • verbosity – the verbosity level.

  • use_tta – whether it should use TTA (test-time augmentation) or not.

Returns

the output filename.

spinalcordtoolbox.deepseg_gm.deepseg_gm.segment_volume(ninput_volume, model_name, threshold=0.999, use_tta=False)[source]

Segment a nifti volume.

Parameters
  • ninput_volume – the input volume.

  • model_name – the name of the model to use.

  • threshold – threshold to be applied in predictions.

  • use_tta – whether TTA (test-time augmentation) should be used or not.

Returns

segmented slices.

spinalcordtoolbox.deepseg_gm.deepseg_gm.threshold_predictions(predictions, thr=0.999)[source]

This method will threshold predictions.

Parameters

thr – the threshold (if None, no threshold will be applied).

Returns

thresholded predictions

spinalcordtoolbox.deepseg_gm.model.create_model(nfilters, input_size=(200, 200))[source]

Create the ASPP model.

Parameters
  • nfilters – number of filters at each block.

  • input_size – the network input size (H, W)

spinalcordtoolbox.deepseg_gm.model.dice_coef(y_true, y_pred)[source]

Dice coefficient specification

Parameters
  • y_true – ground truth.

  • y_pred – predictions.

spinalcordtoolbox.deepseg_gm.model.dice_coef_loss(y_true, y_pred)[source]

Dice loss specification.

Parameters
  • y_true – ground truth.

  • y_pred – predictions.

MS Lesion Segmentation

deepseg_lesion

spinalcordtoolbox.deepseg_lesion.core.apply_intensity_normalization(img, contrast)[source]

Standardize the intensity range.

spinalcordtoolbox.deepseg_lesion.core.apply_intensity_normalization_model(img, landmarks_lst)[source]

Description: apply the learned intensity landmarks to the input image.

spinalcordtoolbox.deepseg_lesion.core.deep_segmentation_MSlesion(im_image, contrast_type, ctr_algo='svm', ctr_file=None, brain_bool=True, remove_temp_files=1, verbose=1)[source]

Segment lesions from MRI data.

Parameters
  • im_image – Image() object containing the lesions to segment

  • contrast_type – Constrast of the image. Need to use one supported by the CNN models.

  • ctr_algo – Algo to find the centerline. See sct_get_centerline

  • ctr_file – Centerline or segmentation (optional)

  • brain_bool – If brain if present or not in the image.

  • remove_temp_files

Returns

spinalcordtoolbox.deepseg_lesion.core.exp_model(xs, ys, s2)[source]

FIXME doc

spinalcordtoolbox.deepseg_lesion.core.segment_3d(model_fname, contrast_type, im)[source]

Perform segmentation with 3D convolutions.

Centerline

spinalcordtoolbox.centerline

class spinalcordtoolbox.centerline.core.FitResults[source]

Collection of metrics to assess fitting performance

class spinalcordtoolbox.centerline.core.ParamCenterline(algo_fitting='bspline', degree=5, smooth=20, contrast=None, minmax=True)[source]

Default parameters for centerline fitting

Parameters
  • algo_fitting – str: polyfit: Polynomial fitting bspline: b-spline fitting linear: linear interpolation followed by smoothing with Hanning window nurbs: Non-Uniform Rational Basis Splines. See [De Leener et al., MIA, 2016] optic: Automatic segmentation using SVM and HOG. See [Gros et al., MIA 2018]. :param degree: Degree of polynomial function. Only for polyfit.

  • smooth – Degree of smoothness. Only for bspline and linear. When using algo_fitting=linear, it corresponds

  • contrast – Contrast type for algo_fitting=optic.

  • minmax – Crop output centerline where the segmentation starts/end. If False, centerline will span all slices to the size of a Hanning window (in mm).

spinalcordtoolbox.centerline.core.find_and_sort_coord(img)[source]

Find x,y,z coordinate of centerline and output an array which is sorted along SI direction. Removes any duplicate along the SI direction by averaging across the same ind_SI.

Parameters

img – Image(): Input image. Could be any orientation.

Returns

nx3 numpy array with X, Y, Z coordinates of center of mass

spinalcordtoolbox.centerline.core.get_centerline(im_seg, param=<spinalcordtoolbox.centerline.core.ParamCenterline object>, verbose=1)[source]

Extract centerline from an image (using optic) or from a binary or weighted segmentation (using the center of mass).

Parameters
  • im_seg – Image(): Input segmentation or series of points along the centerline.

  • param – ParamCenterline() class:

  • verbose – int: verbose level

Returns

im_centerline: Image: Centerline in discrete coordinate (int)

Returns

arr_centerline: 3x1 array: Centerline in continuous coordinate (float) for each slice in RPI orientation.

Returns

arr_centerline_deriv: 3x1 array: Derivatives of x and y centerline wrt. z for each slice in RPI orient.

Returns

fit_results: FitResults class

spinalcordtoolbox.centerline.core.round_and_clip(arr, clip=None)[source]

FIXME doc Round to closest int, convert to dtype=int and clip to min/max values allowed by the list length

Parameters
  • arr

  • clip – [min, max]: Clip values in arr to min and max

Returns

spinalcordtoolbox.centerline.curve_fitting.bspline(x, y, xref, smooth, deg_bspline=3, pz=1)[source]

FIXME doc Bspline interpolation.

The smoothing factor (s) is calculated based on an empirical formula (made by JCA, based on preliminary results) and is a function of pz, density of points and an input smoothing parameter (smooth). The formula is adjusted such that the parameter (smooth) produces similar smoothing results than a Hanning window with length smooth, as implemented in linear().

Parameters
  • x

  • y

  • xref

  • smooth – float: Smoothing factor. 0: no smoothing, 5: moderate smoothing, 50: large smoothing

  • deg_bspline – int: Degree of spline

  • pz – float: dimension of pixel along superior-inferior direction (z, assuming RPI orientation)

Returns

spinalcordtoolbox.centerline.curve_fitting.linear(x, y, xref, smooth=0, pz=1)[source]

FIXME doc Linear interpolation followed by smoothing.

Parameters
  • x

  • y

  • xref

  • smooth – float: Smoothing factor corresponding to the length of the filter window (in mm). 0: no smoothing.

  • pz – float: dimension of pixel along superior-inferior direction (z, assuming RPI orientation)

Returns

spinalcordtoolbox.centerline.curve_fitting.polyfit_1d(x, y, xref, deg=5)[source]

1d Polynomial fitting using numpy’s Polynomial.fit

Parameters
  • x

  • y

  • deg

  • xref – np.array: vector of abscissa on which to project the fitted curve. Example: np.linspace(0, 50, 51)

Returns

p(xref): Fitted polynomial for each xref point

Returns

p.deriv(xref): Derivatives for each xref point

spinalcordtoolbox.centerline.curve_fitting.round_up_to_odd(f)[source]

Round input float to next odd integer.

spinalcordtoolbox.centerline.curve_fitting.smooth1d(x, window_len, window='hanning')[source]

Smooth the data using a window with requested size.

This method is based on the convolution of a scaled window with the signal. The signal is prepared by introducing reflected copies (central symmetry) of the signal (with the window size) in both ends so that transient parts are minimized in the beginning and end part of the output signal.

Modified from: https://scipy-cookbook.readthedocs.io/items/SignalSmooth.html

Param

x: the input signal

Param

window_len: the dimension of the smoothing window; should be an odd integer

Param

window: the type of window from ‘flat’, ‘hanning’, ‘hamming’, ‘bartlett’, ‘blackman’ flat window will produce a moving average smoothing.

Returns

the smoothed signal

example:

t=linspace(-2,2,0.1) x=sin(t)+randn(len(t))*0.1 y=smooth(x)

see also:

numpy.hanning, numpy.hamming, numpy.bartlett, numpy.blackman, numpy.convolve scipy.signal.lfilter

spinalcordtoolbox.centerline.optic.centerline2roi(fname_image, folder_output='./', verbose=0)[source]

Tis method converts a binary centerline image to a .roi centerline file

Parameters
  • fname_image – filename of the binary centerline image, in RPI orientation

  • folder_output – path to output folder where to copy .roi centerline

  • verbose – adjusts the verbosity of the logging.

Returns

filename of the .roi centerline that has been created

spinalcordtoolbox.centerline.optic.detect_centerline(img, contrast, verbose=1)[source]

Detect spinal cord centerline using OptiC.

Parameters
  • img – input Image() object.

  • contrast – str: The type of contrast. Will define the path to Optic model.

Returns

Image(): Output centerline

Segmentation Processing

spinalcord.process_seg

spinalcordtoolbox.process_seg.compute_shape(segmentation, angle_correction=True, param_centerline=None, verbose=1)[source]

Compute morphometric measures of the spinal cord in the transverse (axial) plane from the segmentation. The segmentation could be binary or weighted for partial volume [0,1].

Parameters
  • segmentation – input segmentation. Could be either an Image or a file name.

  • angle_correction

  • param_centerline – see centerline.core.ParamCenterline()

  • verbose

Return metrics

Dict of class Metric(). If a metric cannot be calculated, its value will be nan.

Return fit_results

class centerline.core.FitResults()

spinalcordtoolbox.process_seg.fix_orientation(orientation)[source]

Re-map orientation from skimage.regionprops from [-pi/2,pi/2] to [0,90] and rotate by 90deg because image axis are inverted

QMRI

spinalcordtoolbox.qmri

spinalcordtoolbox.qmri.mt.compute_mtr(nii_mt1, nii_mt0, threshold_mtr=100)[source]

Compute Magnetization Transfer Ratio in percentage.

Parameters
  • nii_mt1 – Image object

  • nii_mt0 – Image object

  • threshold_mtr – float: value above which number will be clipped

Returns

nii_mtr

spinalcordtoolbox.qmri.mt.compute_mtsat(nii_mt, nii_pd, nii_t1, tr_mt, tr_pd, tr_t1, fa_mt, fa_pd, fa_t1, nii_b1map=None)[source]

Compute MTsat (in percent) and T1 map (in s) based on FLASH scans

Parameters
  • nii_mt – Image object for MTw

  • nii_pd – Image object for PDw

  • nii_t1 – Image object for T1w

  • tr_mt – Float: Repetition time for MTw image

  • tr_pd – Float: Repetition time for PDw image

  • tr_t1 – Float: Repetition time for T1w image

  • fa_mt – Float: Flip angle (in deg) for MTw image

  • fa_pd – Float: Flip angle (in deg) for PDw image

  • fa_t1 – Float: Flip angle (in deg) for T1w image

  • nii_b1map – Image object for B1-map (optional)

Returns

MTsat and T1map.

spinalcordtoolbox.qmri.mt.divide_after_removing_zero(dividend, divisor, threshold, replacement=nan)[source]

Mask zero, divide, look for numbers larger than ‘threshold’, and replace masked elements.

Parameters
  • dividend – np.array

  • divisor – np.array

  • threshold – float

  • replacement – float: value to replace masked value with.

Returns

result_full

Quality Control

The modules spinalcordtoolbox.reports.qc and spinalcordtoolbox.reports.slice are used to generate Quality Control reports.

spinalcordtoolbox.reports.qc

class spinalcordtoolbox.reports.qc.Params(input_file, command, args, orientation, dest_folder, dpi=300, dataset=None, subject=None)[source]

Parses and stores the variables that will be included into the QC details

Parameters
  • input_file – str: the input nifti file name

  • command – str: command name

  • args – str: the command’s arguments

  • orientation – str: The anatomical orientation

  • dest_folder – str: The absolute path of the QC root

  • dpi – int: Output resolution of the image

  • dataset – str: Dataset name

  • subject – str: Subject name

class spinalcordtoolbox.reports.qc.QcImage(qc_report, interpolation, action_list, process, stretch_contrast=True, stretch_contrast_method='contrast_stretching', angle_line=None, fps=None)[source]

Class used to create a .png file from a 2d image produced by the class “Slice”

Parameters
  • qc_report – QcReport: The QC report object

  • interpolation – str: Type of interpolation used in matplotlib

  • action_list – list: List of functions that generates a specific type of images

  • process – str: Name of SCT function. e.g., sct_propseg

  • stretch_contrast – adjust image so as to improve contrast

  • stretch_contrast_method – str: {‘contrast_stretching’, ‘equalized’}: Method for stretching contrast

  • angle_line – float: See generate_qc()

  • fps – float: Number of frames per second for output gif images. It is only used for sct_fmri_moco and sct_dmri_moco

grid(mask, ax)[source]

Centered grid to assess quality of motion correction

highlight_pmj(mask, ax)[source]

Hook to show a rectangle where PMJ is on the slice

label_centerline(mask, ax)[source]

Create figure with red label. Common scenario.

label_utils(mask, ax)[source]

Create figure with red label. Common scenario.

label_vertebrae(mask, ax)[source]

Draw vertebrae areas, then add text showing the vertebrae names

line_angle(mask, ax)[source]

Create figure with line superposed over each mosaic square. The line has an angle encoded in the argument self._angle_line

listed_seg(mask, ax)[source]

Create figure with red segmentation. Common scenario.

no_seg_seg(mask, ax)[source]

Create figure with image overlay. Notably used by sct_registration_to_template

template(mask, ax)[source]

Show template statistical atlas

vertical_line(mask, ax)[source]

Centered vertical line to assess quality of straightening

class spinalcordtoolbox.reports.qc.QcReport(qc_params, usage)[source]

This class generates the quality control report.

It will also setup the folder structure so the report generator only needs to fetch the appropriate files.

Parameters

Parameters
  • qc_params – arguments of the “-param-qc” option in Terminal

  • usage – str: description of the process

make_content_path()[source]

Creates the whole directory to contain the QC report

Returns

return “root folder of the report” and the “furthest folder path” containing the images

update_description_file(dimension)[source]

Create the description file with a JSON structure

Param

dimension 2-tuple, the dimension of the image frame (w, h)

spinalcordtoolbox.reports.qc.add_entry(src, process, args, path_qc, plane, path_img=None, path_img_overlay=None, qcslice=None, qcslice_operations=[], qcslice_layout=None, dpi=300, stretch_contrast_method='contrast_stretching', angle_line=None, fps=None, dataset=None, subject=None)[source]

Create QC report.

Parameters
  • src – Path to input file (only used to populate report metadata)

  • process

  • args

  • path_qc

  • plane

  • path_img – Path to image to display

  • path_img_overlay – Path to image to display on top of path_img (will flip between the two)

  • qcslice – spinalcordtoolbox.reports.slice:Axial or spinalcordtoolbox.reports.slice:Sagittal

  • qcslice_operations

  • qcslice_layout

  • dpi – int: Output resolution of the image

  • stretch_contrast_method – Method for stretching contrast. See QcImage

  • angle_line – [float]: See generate_qc()

  • fps – float: Number of frames per second for output gif images

  • dataset – str: Dataset name

  • subject – str: Subject name

Returns

spinalcordtoolbox.reports.qc.generate_qc(fname_in1, fname_in2=None, fname_seg=None, angle_line=None, args=None, path_qc=None, dataset=None, subject=None, path_img=None, process=None, fps=None)[source]

Generate a QC entry allowing to quickly review results. This function is the entry point and is called by SCT scripts (e.g. sct_propseg).

Parameters
  • fname_in1 – str: File name of input image #1 (mandatory)

  • fname_in2 – str: File name of input image #2

  • fname_seg – str: File name of input segmentation

  • angle_line – list: Angle [in rad, wrt. vertical line, must be between -pi and pi] to apply to the line overlaid on the image, for each slice, for slice that don’t have an angle to display, a nan is expected. To be used for assessing cord orientation.

  • args – args from parent function

  • path_qc – str: Path to save QC report

  • dataset – str: Dataset name

  • subject – str: Subject name

  • path_img – dict: Path to image to display (e.g., a graph), instead of computing the image from MRI.

  • process – str: Name of SCT function. e.g., sct_propseg

  • fps – float: Number of frames per second for output gif images. Used only for sct_frmi_moco and sct_dmri_moco.

Returns

None

spinalcordtoolbox.reports.qc.get_json_data_from_path(path_json)[source]

Read all json files present in the given path, and output an aggregated json structure

spinalcordtoolbox.reports.slice

class spinalcordtoolbox.reports.slice.Axial(images, p_resample=0.6)[source]

The axial representation of a slice

Parameters

images – list of 3D or 4D volumes to be separated into slices.

get_center(img_idx=- 1)[source]

Get the center of mass of each slice. For 4D images, segmentation is placed in self.image_seg. For 3D images, by default, it assumes that self._images is a list of images, and the last item is the segmentation from which the center of mass is computed.

get_dim(image)[source]

Abstract method to obtain the depth of the 3d matrix.

Parameters

image – input Image

Returns

numpy.ndarray

get_name()[source]

Get the class name

get_slice(data, i)[source]

Abstract method to obtain a slice of a 3d matrix

Parameters
  • data – volume

  • i – position to slice

Returns

2D slice

class spinalcordtoolbox.reports.slice.Sagittal(images, p_resample=0.6)[source]

The sagittal representation of a slice

Parameters

images – list of 3D or 4D volumes to be separated into slices.

get_center_spit(img_idx=- 1)[source]

Retrieve index along in the R-L direction for each S-I slice in order to center the spinal cord in the medial plane, around the labels or segmentation.

By default, it looks at the latest image in the input list of images, assuming the latest is the labels or segmentation.

If only one label is found, the cord will be centered at that label.

Returns

index: [int] * n_SI

get_dim(image)[source]

Abstract method to obtain the depth of the 3d matrix.

Parameters

image – input Image

Returns

numpy.ndarray

get_name()[source]

Get the class name

get_slice(data, i)[source]

Abstract method to obtain a slice of a 3d matrix

Parameters
  • data – volume

  • i – position to slice

Returns

2D slice

class spinalcordtoolbox.reports.slice.Slice(images, p_resample=0.6)[source]

Abstract class representing slicing applied to >=1 volumes for the purpose of generating ROI slices.

Typically, the first volumes are images, while the last volume is a segmentation, which is used as overlay on the image, and/or to retrieve the center of mass to center the image on each QC mosaic square.

For convenience, the volumes are all brought in the SAL reference frame.

Functions with the suffix _slice gets a slice cut in the desired axis at the “i” position of the data of the 3D image. While the functions with the suffix _dim gets the size of the desired dimension of the 3D image.

IMPORTANT: Convention for orientation is “SAL”

Parameters

images – list of 3D or 4D volumes to be separated into slices.

static add_slice(matrix, i, column, size, patch)[source]

Adds a slice to the canvas containing all the slices

TODO : Move this to the Axial class

Parameters
  • matrix – input/output “big canvas”

  • i – slice position

  • column – number of columns in mosaic

  • size

  • patch – patch to insert

Returns

matrix

static crop(matrix, x, y, width, height)[source]

Crops the matrix to width and height from the center

Select the size of the matrix if the calculated crop width or height are larger than the size of the matrix.

TODO : Move this into the Axial class

Parameters
  • matrix – Array representation of the image

  • x – The center of the crop area in the x axis

  • y – The center of the crop area in the y axis

  • width – The width from the center

  • height – The height from the center

Returns

cropped matrix

abstract get_dim(image)[source]

Abstract method to obtain the depth of the 3d matrix.

Parameters

image – input Image

Returns

numpy.ndarray

abstract get_name()[source]

Get the class name

abstract get_slice(data, i)[source]

Abstract method to obtain a slice of a 3d matrix

Parameters
  • data – volume

  • i – position to slice

Returns

2D slice

mosaic(nb_column=0, size=15, return_center=False)[source]

Obtain matrices of the mosaics

Calculates how many squares will fit in a row based on the column and the size Multiply by 2 because the sides are of size*2. Central point is size +/-.

Parameters
  • nb_column – number of mosaic columns

  • size – each column size

Returns

tuple of numpy.ndarray containing the mosaics of each slice pixels

Returns

list of tuples, each tuple representing the center of each square of the mosaic. Only with param return_center is True

mosaics_through_time()[source]

Obtain mosaics for each volume

Returns

list of tuples of numpy.ndarray containing the mosaics of each volumes

static nan_fill(A)[source]

Interpolate NaN values with neighboring values in array (in-place) If only NaNs, return an array of zeros.

single()[source]

Obtain the matrices of the single slices. Flatten

Returns

tuple of numpy.ndarray, matrix of the input 3D MRI containing the slices and matrix of the transformed 3D MRI to output containing the slices

Vertebrae Labeling

spinalcordtoolbox.vertebrae

exception spinalcordtoolbox.vertebrae.core.EmptyArrayError[source]

Custom exception to distinguish between general SciPy ValueErrors.

spinalcordtoolbox.vertebrae.core.center_of_mass(x)[source]
Returns

array center of mass

spinalcordtoolbox.vertebrae.core.clean_labeled_segmentation(fname_labeled_seg, fname_seg, fname_labeled_seg_new)[source]

FIXME doc Clean labeled segmentation by: (i) removing voxels in segmentation_labeled that are not in segmentation and (ii) adding voxels in segmentation that are not in segmentation_labeled

Parameters
  • fname_labeled_seg

  • fname_seg

  • fname_labeled_seg_new – output

Returns

none

spinalcordtoolbox.vertebrae.core.compute_corr_3d(src, target, x, xshift, xsize, y, yshift, ysize, z, zshift, zsize, xtarget, ytarget, ztarget, zrange, verbose, save_suffix, gaussian_std, path_output)[source]

FIXME doc Find z that maximizes correlation between src and target 3d data.

Parameters
  • src – 3d source data

  • target – 3d target data

  • x

  • xshift

  • xsize

  • y

  • yshift

  • ysize

  • z

  • zshift

  • zsize

  • xtarget

  • ytarget

  • ztarget

  • zrange

  • verbose

  • save_suffix

  • gaussian_std

Returns

spinalcordtoolbox.vertebrae.core.create_label_z(fname_seg, z, value, fname_labelz='labelz.nii.gz')[source]

Create a label at coordinates x_center, y_center, z

Parameters
  • fname_seg – segmentation

  • z – int

  • fname_labelz – string file name of output label

Returns

fname_labelz

spinalcordtoolbox.vertebrae.core.get_z_and_disc_values_from_label(fname_label)[source]

Find z-value and label-value based on labeled image in RPI orientation

Parameters

fname_label – image in RPI orientation that contains label

Returns

[z_label, value_label] int list

spinalcordtoolbox.vertebrae.core.label_discs(fname_seg, list_disc_z, list_disc_value, verbose=1)[source]

Create file with single voxel label in the middle of the spinal cord for each disc.

Parameters
  • fname_seg – fname of the segmentation, no orientation expected

  • list_disc_z – list of z that correspond to a disc

  • list_disc_value – list of associated disc values

  • verbose

Returns

spinalcordtoolbox.vertebrae.core.label_segmentation(fname_seg, list_disc_z, list_disc_value, verbose=1)[source]

Label segmentation image

Parameters
  • fname_seg – fname of the segmentation, no orientation expected

  • list_disc_z – list of z that correspond to a disc

  • list_disc_value – list of associated disc values

  • verbose

Returns

spinalcordtoolbox.vertebrae.core.label_vert(fname_seg, fname_label, verbose=1)[source]

Label segmentation using vertebral labeling information. No orientation expected.

Parameters
  • fname_seg – file name of segmentation.

  • fname_label – file name for a labelled segmentation that will be used to label the input segmentation

  • fname_out – file name of the output labeled segmentation. If empty, will add suffix “_labeled” to fname_seg

  • verbose

Returns

spinalcordtoolbox.vertebrae.core.vertebral_detection(fname, fname_seg, contrast, param, init_disc, verbose=1, path_template='', path_output='../', scale_dist=1.0)[source]

Find intervertebral discs in straightened image using template matching

Parameters
  • fname – file name of straigthened spinal cord

  • fname_seg – file name of straigthened spinal cord segmentation

  • contrast – t1 or t2

  • param – advanced parameters

  • init_disc

  • verbose

  • path_template

  • path_output – output path for verbose=2 pictures

  • scale_dist – float: Scaling factor to adjust average distance between two adjacent intervertebral discs

Returns

spinalcordtoolbox.vertebrae.detect_c2c3.detect_c2c3(nii_im, nii_seg, contrast, nb_sag_avg=7.0, verbose=1)[source]

Detect the posterior edge of C2-C3 disc.

Parameters
  • nii_im

  • nii_seg

  • contrast

  • verbose

Returns

spinalcordtoolbox.vertebrae.detect_c2c3.detect_c2c3_from_file(fname_im, fname_seg, contrast, fname_c2c3=None, verbose=1)[source]

Detect the posterior edge of C2-C3 disc.

Parameters
  • fname_im

  • fname_seg

  • contrast

  • fname_c2c3

  • verbose

Returns

fname_c2c3

Metrics Aggregation

spinalcordtoolbox.aggregate_slicewise

class spinalcordtoolbox.aggregate_slicewise.LabelStruc(id, name, filename=None, map_cluster=None)[source]

Class for labels

class spinalcordtoolbox.aggregate_slicewise.Metric(data=None, label='')[source]

Class to include in dictionaries to associate data and label

Parameters
  • data – ndarray

  • label – str

spinalcordtoolbox.aggregate_slicewise.aggregate_per_slice_or_level(metric, mask=None, slices=[], levels=[], perslice=None, perlevel=False, vert_level=None, group_funcs=(('MEAN', <function func_wa>), ), map_clusters=None)[source]

The aggregation will be performed along the last dimension of ‘metric’ ndarray.

Parameters
  • metric – Class Metric(): data to aggregate.

  • mask – Class Metric(): mask to use for aggregating the data. Optional.

  • slices – List[int]: Slices to aggregate metric from. If empty, select all slices.

  • levels – List[int]: Vertebral levels to aggregate metric from. It has priority over “slices”.

  • perslice (Bool) – Aggregate per slice (True) or across slices (False)

  • perlevel (Bool) – Aggregate per level (True) or across levels (False). Has priority over “perslice”.

  • vert_level – Vertebral level. Could be either an Image or a file name.

  • group_funcs (tuple) – Name and function to apply on metric. Example: ((‘MEAN’, func_wa),)). Note, the function has special requirements in terms of i/o. See the definition to func_wa and use it as a template.

  • map_clusters – list of list of int: See func_map()

Returns

Aggregated metric

spinalcordtoolbox.aggregate_slicewise.check_labels(indiv_labels_ids, selected_labels)[source]

Check the consistency of the labels asked by the user.

spinalcordtoolbox.aggregate_slicewise.diff_between_list_or_int(l1, l2)[source]

Return list l1 minus the elements in l2 Examples: ([1, 2, 3], 1) –> [2, 3] ([1, 2, 3], [1, 2] –> [3]

Parameters
  • l1 – a list of int

  • l2 – could be a list or an int

Returns

spinalcordtoolbox.aggregate_slicewise.extract_metric(data, labels=None, slices=None, levels=None, perslice=True, perlevel=False, vert_level=None, method=None, label_struc=None, id_label=None, indiv_labels_ids=None)[source]

Extract metric within a data, using mask and a given method.

Parameters
  • data – Class Metric(): Data (a.k.a. metric) of n-dimension to extract aggregated value from

  • labels – Class Metric(): Labels of (n+1)dim. The last dim encloses the labels.

  • slices

  • levels

  • perslice

  • perlevel

  • vert_level

  • method

  • label_struc – LabelStruc class defined above

  • id_label – int: ID of label to select

  • indiv_labels_ids – list of int: IDs of labels corresponding to individual (as opposed to combined) labels for use with ML or MAP estimation.

Returns

aggregate_per_slice_or_level()

spinalcordtoolbox.aggregate_slicewise.func_bin(data, mask, map_clusters=None)[source]

Get the average of data after binarizing the input mask

Parameters
  • data – nd-array: input data

  • mask – (n+1)d-array: input mask

  • map_clusters – not used

Returns

spinalcordtoolbox.aggregate_slicewise.func_map(data, mask, map_clusters)[source]

Compute maximum a posteriori (MAP) by aggregating the last dimension of mask according to a clustering method defined by map_clusters

Parameters
  • data – nd-array: input data

  • mask – (n+1)d-array: input mask. Note: this mask should include ALL labels to satisfy the necessary condition for ML-based estimation, i.e., at each voxel, the sum of all labels (across the last dimension) equals the probability to be inside the tissue. For example, for a pixel within the spinal cord, the sum of all labels should be 1.

  • map_clusters – list of list of int: Each sublist corresponds to a cluster of labels where ML estimation will be performed to provide the prior beta_0 for MAP estimation.

Returns

float: beta corresponding to the first label (beta[0])

Returns

nd-array: matrix of all beta

spinalcordtoolbox.aggregate_slicewise.func_max(data, mask=None, map_clusters=None)[source]

Get the max of an array

Parameters
  • data – nd-array: input data

  • mask – not used

  • map_clusters – not used

Returns

spinalcordtoolbox.aggregate_slicewise.func_median(data, mask, map_clusters=None)[source]

Compute weighted median. This is a “non-discrete” implementation of the median, in that it computes the mean between the middle discrete values. For more context, see: https://github.com/nudomarinero/wquantiles/issues/4 :param data: nd-array: input data :param mask: (n+1)d-array: input mask :param map_clusters: not used :return:

spinalcordtoolbox.aggregate_slicewise.func_ml(data, mask, map_clusters=None)[source]

Compute maximum likelihood (ML) for the first label of mask.

Parameters
  • data – nd-array: input data

  • mask – (n+1)d-array: input mask. Note: this mask should include ALL labels to satisfy the necessary condition for ML-based estimation, i.e., at each voxel, the sum of all labels (across the last dimension) equals the probability to be inside the tissue. For example, for a pixel within the spinal cord, the sum of all labels should be 1.

Returns

float: beta corresponding to the first label

spinalcordtoolbox.aggregate_slicewise.func_std(data, mask=None, map_clusters=None)[source]

Compute standard deviation

Parameters
  • data – nd-array: input data

  • mask – (n+1)d-array: input mask

  • map_clusters – not used

Returns

spinalcordtoolbox.aggregate_slicewise.func_sum(data, mask=None, map_clusters=None)[source]

Compute sum

Parameters
  • data – nd-array: input data

  • mask – not used

  • map_clusters – not used

Returns

spinalcordtoolbox.aggregate_slicewise.func_wa(data, mask=None, map_clusters=None)[source]

Compute weighted average

Parameters
  • data – nd-array: input data

  • mask – (n+1)d-array: input mask

  • map_clusters – not used

Returns

spinalcordtoolbox.aggregate_slicewise.make_a_string(item)[source]

Convert tuple or list or None to a string. Important: elements in tuple or list are separated with ; (not ,) for compatibility with csv.

spinalcordtoolbox.aggregate_slicewise.merge_dict(dict_in)[source]

Merge n dictionaries that are contained at the root key

dict_in = {
    'area': {(0): {'Level': 0, 'Mean(area)': 0.5}, (1): {'Level': 1, 'Mean(area)': 0.2}}
    'angle_RL': {(0): {'Level': 0, 'Mean(angle_RL)': 15}, (1): {'Level': 1, 'Mean(angle_RL)': 12}}
}
dict_merged = {
    (0): {'Level': 0, 'Mean(area): 0.5, 'Mean(angle_RL): 15}
    (1): {'Level': 1, 'Mean(area): 0.2, 'Mean(angle_RL): 12}
}
Parameters

dict_in – input dict.

Returns

normalized dict with sub-dicts at root level

spinalcordtoolbox.aggregate_slicewise.save_as_csv(agg_metric, fname_out, fname_in=None, append=False)[source]

Write metric structure as csv. If field ‘error’ exists, it will add a specific column.

Parameters
  • agg_metric – output of aggregate_per_slice_or_level()

  • fname_out – output filename. Extention (.csv) will be added if it does not exist.

  • fname_in – input file to be listed in the csv file (e.g., segmentation file which produced the results).

  • append – Bool: Append results at the end of file (if exists) instead of overwrite.

Returns

Image Manipulation

spinalcordtoolbox.cropping

class spinalcordtoolbox.cropping.BoundingBox(xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None)[source]
get_minmax(img=None)[source]

Get voxel-based bounding box from coordinates. Replaces ‘-1’ with max dim along each axis, ‘-2’ with max dim minus 1, etc.

Parameters

img – Image object to get dimensions

Returns

spinalcordtoolbox.image

class spinalcordtoolbox.image.Image(param=None, hdr=None, orientation=None, absolutepath=None, dim=None, verbose=1, check_sform=False)[source]

Create an object that behaves similarly to nibabel’s image object. Useful additions include: dim, check_sform and a few methods (load, save) that deal with image dtype.

Parameters
  • param – string indicating a path to a image file or an Image object.

  • hdr – a nibabel header object to use as the header for the image (overwritten if param is provided)

  • orientation – a three character orientation code (e.g. RPI).

  • absolutepath – a relative path to associate with the image.

  • dim – The dimensions of the image, defaults to automatically determined.

  • verbose – integer how verbose to be 0 is silent 1 is chatty.

  • check_sform – whether or not to check whether the sform matches the qform. If this is set to True, Image will fail raise an error if they don’t match.

property absolutepath

Storage path (either actual or potential)

Notes:

  • As several tools perform chdir() it’s very important to have absolute paths

  • When set, if relative:

    • If it already existed, it becomes a new basename in the old dirname

    • Else, it becomes absolute (shortcut)

Usually not directly touched (use Image.save), but in some cases it’s the best way to set it.

change_orientation(orientation, inverse=False, generate_path=False)[source]

Change orientation on image (in-place).

Parameters
  • orientation – orientation string (SCT “from” convention)

  • inverse – if you think backwards, use this to specify that you actually want to transform from the specified orientation, not to it.

  • generate_path – whether to create a derived path name from the original absolutepath (note: while it will generate a file suffix, don’t expect the suffix but rather use the Image’s absolutepath. If not set, the absolutepath is voided.

change_shape(shape, generate_path=False)[source]

Change data shape (in-place)

Parameters

generate_path – whether to create a derived path name from the original absolutepath (note: while it will generate a file suffix, don’t expect the suffix but rather use the Image’s absolutepath. If not set, the absolutepath is voided.

This is mostly useful for adding/removing a fourth dimension, you probably don’t want to use this function.

change_type(dtype, generate_path=False)[source]

Change data type on image.

Note: the image path is voided.

copy_qform_from_ref(im_ref)[source]

Copy qform and sform and associated codes from a reference Image object

Parameters

im_ref

Returns

getCoordinatesAveragedByValue()[source]

This function computes the mean coordinate of group of labels in the image. This is especially useful for label’s images.

Returns

list of coordinates that represent the center of mass of each group of value.

getNonZeroCoordinates(sorting=None, reverse_coord=False, coordValue=False)[source]

This function return all the non-zero coordinates that the image contains. Coordinate list can also be sorted by x, y, z, or the value with the parameter sorting=’x’, sorting=’y’, sorting=’z’ or sorting=’value’ If reverse_coord is True, coordinate are sorted from larger to smaller.

get_directions()[source]

This function return the X, Y, and Z axes of the image

return: X, Y and Z axes of the image

get_values(coordi=None, interpolation_mode=0, border='constant', cval=0.0)[source]

This function returns the intensity value of the image at the position coordi (can be a list of coordinates).

Parameters
  • coordi – continuouspix

  • interpolation_mode – 0=nearest neighbor, 1= linear, 2= 2nd-order spline, 3= 2nd-order spline, 4= 2nd-order spline, 5= 5th-order spline

Returns

intensity values at continuouspix with interpolation_mode

interpolate_from_image(im_ref, fname_output=None, interpolation_mode=1, border='constant')[source]

This function interpolates an image by following the grid of a reference image. Example of use:

from spinalcordtoolbox.image import Image
im_input = Image(fname_input)
im_ref = Image(fname_ref)
im_input.interpolate_from_image(im_ref, fname_output, interpolation_mode=1)
Parameters
  • im_ref – reference Image that contains the grid on which interpolate.

  • border – Points outside the boundaries of the input are filled according to the given mode (‘constant’, ‘nearest’, ‘reflect’ or ‘wrap’)

Returns

a new image that has the same dimensions/grid of the reference image but the data of self image.

loadFromPath(path, verbose)[source]

This function load an image from an absolute path using nibabel library

Parameters

path – path of the file from which the image will be loaded

Returns

mean(dim)[source]

Average across specified dimension

Parameters

dim – int: axis used for averaging

Returns

Image object

save(path=None, dtype=None, verbose=1, mutable=False)[source]

Write an image in a nifti file

Parameters
  • path – Where to save the data, if None it will be taken from the absolutepath member. If path is a directory, will save to a file under this directory with the basename from the absolutepath member.

  • dtype – if not set, the image is saved in the same type as input data if ‘minimize’, image storage space is minimized (2, ‘uint8’, np.uint8, “NIFTI_TYPE_UINT8”), (4, ‘int16’, np.int16, “NIFTI_TYPE_INT16”), (8, ‘int32’, np.int32, “NIFTI_TYPE_INT32”), (16, ‘float32’, np.float32, “NIFTI_TYPE_FLOAT32”), (32, ‘complex64’, np.complex64, “NIFTI_TYPE_COMPLEX64”), (64, ‘float64’, np.float64, “NIFTI_TYPE_FLOAT64”), (256, ‘int8’, np.int8, “NIFTI_TYPE_INT8”), (512, ‘uint16’, np.uint16, “NIFTI_TYPE_UINT16”), (768, ‘uint32’, np.uint32, “NIFTI_TYPE_UINT32”), (1024,’int64’, np.int64, “NIFTI_TYPE_INT64”), (1280, ‘uint64’, np.uint64, “NIFTI_TYPE_UINT64”), (1536, ‘float128’, _float128t, “NIFTI_TYPE_FLOAT128”), (1792, ‘complex128’, np.complex128, “NIFTI_TYPE_COMPLEX128”), (2048, ‘complex256’, _complex256t, “NIFTI_TYPE_COMPLEX256”),

  • mutable – whether to update members with newly created path or dtype

set_qform_to_sform()[source]

Use this or (set_sform_to_qform) when matching matrices are required.

set_sform_to_qform()[source]

Use this (or set_qform_to_sform) when matching matrices are required.

transfo_phys2pix(coordi, real=True)[source]

This function returns the pixels coordinates of all points of ‘coordi’

Parameters
  • coordi – sequence of (nb_points x 3) values containing the pixel coordinate of points.

  • real – whether to return real pixel coordinates

Returns

sequence with the physical coordinates of the points in the space of the image.

transfo_pix2phys(coordi=None)[source]

This function returns the physical coordinates of all points of ‘coordi’.

Parameters

coordi – sequence of (nb_points x 3) values containing the pixel coordinate of points.

Returns

sequence with the physical coordinates of the points in the space of the image.

Example:

img = Image('file.nii.gz')
coordi_pix = [[1,1,1]]   # for points: (1,1,1). N.B. Important to write [[x,y,z]] instead of [x,y,z]
coordi_pix = [[1,1,1],[2,2,2],[4,4,4]]   # for points: (1,1,1), (2,2,2) and (4,4,4)
coordi_phys = img.transfo_pix2phys(coordi=coordi_pix)
class spinalcordtoolbox.image.Slicer(im, orientation='LPI')[source]

Provides a sliced view onto original image data. Can be used as a sequence.

Notes:

  • The original image data is directly available without copy, which is a nice feature, not a bug! Use .copy() if you need copies…

Example:

for slice2d in msct_image.SlicerFancy(im3d, "RPI"):
    print(slice)
Parameters
  • im – image to iterate through

  • orientation – “from” letters to indicate how to slice the image. The slices are done on the last letter axis, and they are defined as the first/second letter.

class spinalcordtoolbox.image.SlicerMany(images, slicerclass, *args, **kw)[source]

Image*s* slicer utility class.

Can help getting ranges and slice indices. Can provide slices (being an iterator).

Use with great care for now, that it’s not very documented.

class spinalcordtoolbox.image.SlicerOneAxis(im, axis='IS')[source]

Image slicer to use when you don’t care about the 2D slice orientation, and don’t want to specify them. The slicer will just iterate through the right axis that corresponds to its specification.

Can help getting ranges and slice indices.

spinalcordtoolbox.image.add_suffix(fname, suffix)[source]

Add suffix between end of file name and extension.

Parameters
  • fname – absolute or relative file name. Example: t2.nii

  • suffix – suffix. Example: _mean

Returns

file name with suffix. Example: t2_mean.nii

Examples: .. code:: python

add_suffix(t2.nii, _mean) -> t2_mean.nii add_suffix(t2.nii.gz, a) -> t2a.nii.gz

spinalcordtoolbox.image.all_refspace_strings()[source]
Returns

all possible orientation strings [‘RAI’, ‘RAS’, ‘RPI’, ‘RPS’, …]

spinalcordtoolbox.image.change_orientation(im_src, orientation, im_dst=None, inverse=False, data_only=False)[source]
Parameters
  • im_src – source image

  • orientation – orientation string (SCT “from” convention)

  • im_dst – destination image (can be the source image for in-place operation, can be unset to generate one)

  • inverse – if you think backwards, use this to specify that you actually want to transform from the specified orientation, not to it.

  • data_only – If you want to only permute the data, not the header. Only use if you know there is a problem with the native orientation of the input data.

Returns

an image with changed orientation

Note

  • the resulting image has no path member set

  • if the source image is < 3D, it is reshaped to 3D and the destination is 3D

spinalcordtoolbox.image.change_shape(im_src, shape, im_dst=None)[source]
Parameters

shape – shape to obtain (must be compatible with original one)

Returns

an image with changed shape

Note

The resulting image has no path

spinalcordtoolbox.image.change_type(im_src, dtype, im_dst=None)[source]

Change the voxel type of the image

Parameters

dtype – if not set, the image is saved in standard type if ‘minimize’, image space is minimize if ‘minimize_int’, image space is minimize and values are approximated to integers (2, ‘uint8’, np.uint8, “NIFTI_TYPE_UINT8”), (4, ‘int16’, np.int16, “NIFTI_TYPE_INT16”), (8, ‘int32’, np.int32, “NIFTI_TYPE_INT32”), (16, ‘float32’, np.float32, “NIFTI_TYPE_FLOAT32”), (32, ‘complex64’, np.complex64, “NIFTI_TYPE_COMPLEX64”), (64, ‘float64’, np.float64, “NIFTI_TYPE_FLOAT64”), (256, ‘int8’, np.int8, “NIFTI_TYPE_INT8”), (512, ‘uint16’, np.uint16, “NIFTI_TYPE_UINT16”), (768, ‘uint32’, np.uint32, “NIFTI_TYPE_UINT32”), (1024,’int64’, np.int64, “NIFTI_TYPE_INT64”), (1280, ‘uint64’, np.uint64, “NIFTI_TYPE_UINT64”), (1536, ‘float128’, _float128t, “NIFTI_TYPE_FLOAT128”), (1792, ‘complex128’, np.complex128, “NIFTI_TYPE_COMPLEX128”), (2048, ‘complex256’, _complex256t, “NIFTI_TYPE_COMPLEX256”),

Returns

spinalcordtoolbox.image.check_dim(fname, dim_lst=[3])[source]

Check if input dimension matches the input dimension requirements specified in the dim list. Example: to check if an image is 2D or 3D: check_dim(my_file, dim_lst=[2, 3]) :param fname: :return: True or False

spinalcordtoolbox.image.compute_dice(image1, image2, mode='3d', label=1, zboundaries=False)[source]

This function computes the Dice coefficient between two binary images. :param image1: object Image :param image2: object Image :param mode: mode of computation of Dice. 3d: compute Dice coefficient over the full 3D volume 2d-slices: compute the 2D Dice coefficient for each slice of the volumes :param: label: binary label for which Dice coefficient will be computed. Default=1 :paaram: zboundaries: True/False. If True, the Dice coefficient is computed over a Z-ROI where both segmentations are present. Default=False.

Returns

Dice coefficient as a float between 0 and 1. Raises ValueError exception if an error occurred.

spinalcordtoolbox.image.concat_data(im_in_list: Sequence[spinalcordtoolbox.image.Image], dim, pixdim=None, squeeze_data=False)[source]

Concatenate data

Parameters
  • im_in_list – list of Images

  • dim – dimension: 0, 1, 2, 3.

  • pixdim – pixel resolution to join to image header

  • squeeze_data – bool: if True, remove the last dim if it is a singleton.

Return im_out

concatenated image

spinalcordtoolbox.image.concat_warp2d(fname_list, fname_warp3d, fname_dest)[source]

Concatenate 2d warping fields into a 3d warping field along z dimension. The 3rd dimension of the resulting warping field will be zeroed.

Parameters
  • fname_list – list of 2d warping fields (along X and Y).

  • fname_warp3d – output name of 3d warping field

  • fname_dest – 3d destination file (used to copy header information)

Returns

none

spinalcordtoolbox.image.convert(img: spinalcordtoolbox.image.Image, squeeze_data=True, dtype=None)[source]
spinalcordtoolbox.image.create_formatted_header_string(header, output_format='sct')[source]

Generate a string with formatted header fields for pretty-printing.

Parameters
  • header – Input header to apply formatting to.

  • output_format – Specify how to format the output header.

spinalcordtoolbox.image.empty_like(img, dtype=None)[source]
Parameters
  • img – reference image

  • dtype – desired data type (optional)

Returns

an Image with the same shape and header, whose data is uninitialized

Similar to numpy.empty_like(), the goal of the function is to show the developer’s intent and avoid touching the allocated memory, because it will be written to afterwards.

spinalcordtoolbox.image.find_zmin_zmax(im, threshold=0.1)[source]

Find the min (and max) z-slice index below which (and above which) slices only have voxels below a given threshold.

Parameters
  • im – Image object

  • threshold – threshold to apply before looking for zmin/zmax, typically corresponding to noise level.

Returns

[zmin, zmax]

spinalcordtoolbox.image.generate_output_file(fname_in, fname_out, squeeze_data=True, verbose=1)[source]

Copy fname_in to fname_out with a few convenient checks: make sure input file exists, if fname_out exists send a warning, if input and output NIFTI format are different (nii vs. nii.gz) convert by unzipping or zipping, and display nice message at the end. :param fname_in: :param fname_out: :param verbose: :return: fname_out

spinalcordtoolbox.image.get_dimension(im_file, verbose=1)[source]

Get dimension from Image or nibabel object. Manages 2D, 3D or 4D images.

Param

im_file: Image or nibabel object

Returns

nx, ny, nz, nt, px, py, pz, pt

spinalcordtoolbox.image.get_orientation(im)[source]
Parameters

im – an Image

Returns

reference space string (ie. what’s in Image.orientation)

spinalcordtoolbox.image.orientation_string_nib2sct(s)[source]
Returns

SCT reference space code from nibabel one

spinalcordtoolbox.image.orientation_string_sct2nib(s)
Returns

SCT reference space code from nibabel one

spinalcordtoolbox.image.pad_image(im: spinalcordtoolbox.image.Image, pad_x_i: int = 0, pad_x_f: int = 0, pad_y_i: int = 0, pad_y_f: int = 0, pad_z_i: int = 0, pad_z_f: int = 0)[source]

Given an input image, create a copy with specified padding.

spinalcordtoolbox.image.spatial_crop(im_src, spec, im_dst=None)[source]

Crop an image in {0,1,2} dimension(s), properly altering the header to not change the physical-logical corresondance.

Parameters

spec – dict of dim -> [lo,hi] bounds (integer voxel coordinates)

spinalcordtoolbox.image.split_img_data(src_img: spinalcordtoolbox.image.Image, dim, squeeze_data=True)[source]

Split data

Parameters
  • src_img – input image.

  • dim – dimension: 0, 1, 2, 3.

Returns

list of split images

spinalcordtoolbox.image.splitext(fname)[source]

Split a fname (folder/file + ext) into a folder/file and extension.

Note: for .nii.gz the extension is understandably .nii.gz, not .gz (os.path.splitext() would want to do the latter, hence the special case).

spinalcordtoolbox.image.to_dtype(dtype)[source]

Take a dtypeification and return an np.dtype

Parameters

dtype – dtypeification (string or np.dtype or None are supported for now)

Returns

dtype or None

spinalcordtoolbox.image.zeros_like(img, dtype=None)[source]
Parameters
  • img – reference image

  • dtype – desired data type (optional)

Returns

an Image with the same shape and header, filled with zeros

Similar to numpy.zeros_like(), the goal of the function is to show the developer’s intent and avoid doing a copy, which is slower than initialization with a constant.

spinalcordtoolbox.resampling

spinalcordtoolbox.resampling.resample_file(fname_data, fname_out, new_size, new_size_type, interpolation, verbose, fname_ref=None)[source]

This function will resample the specified input image file to the target size. Can deal with 2d, 3d or 4d image objects.

Parameters
  • fname_data – The input image filename.

  • fname_out – The output image filename.

  • new_size – The target size, i.e. 0.25x0.25

  • new_size_type – Unit of resample (mm, vox, factor)

  • interpolation – The interpolation type

  • verbose – verbosity level

  • fname_ref – Reference image to resample input image to

spinalcordtoolbox.resampling.resample_nib(image, new_size=None, new_size_type=None, image_dest=None, interpolation='linear', mode='nearest')[source]

Resample a nibabel or Image object based on a specified resampling factor. Can deal with 2d, 3d or 4d image objects.

Parameters
  • image – nibabel or Image image.

  • new_size – list of float: Resampling factor, final dimension or resolution, depending on new_size_type.

  • new_size_type – {‘vox’, ‘factor’, ‘mm’}: Feature used for resampling. Examples: new_size=[128, 128, 90], new_size_type=’vox’ –> Resampling to a dimension of 128x128x90 voxels new_size=[2, 2, 2], new_size_type=’factor’ –> 2x isotropic upsampling new_size=[1, 1, 5], new_size_type=’mm’ –> Resampling to a resolution of 1x1x5 mm

  • image_dest – Destination image to resample the input image to. In this case, new_size and new_size_type are ignored

  • interpolation – {‘nn’, ‘linear’, ‘spline’}. The interpolation type

  • mode – Outside values are filled with 0 (‘constant’) or nearest value (‘nearest’).

Returns

The resampled nibabel or Image image (depending on the input object type).

Image Labelling

spinalcordtoolbox.labels

spinalcordtoolbox.labels.add(img: spinalcordtoolbox.image.Image, value: int)spinalcordtoolbox.image.Image[source]

This function adds a specified value to all non-zero voxels.

Parameters
  • img – source image

  • value – numeric value to add

Returns

new image with value added

spinalcordtoolbox.labels.check_missing_label(img, ref)[source]

Function that return the list of label that are present in ref and not in img. This is useful to find label that are in img and not in the ref (first output) and labels that are present in the ref and not in img (second output)

Parameters
  • img – source image

  • ref – reference image

Returns

two lists. The first one is the list of label present in the input and not in the ref image, the second one gives the labels presents in the ref and not in the input.

spinalcordtoolbox.labels.compute_mean_squared_error(img: spinalcordtoolbox.image.Image, ref: spinalcordtoolbox.image.Image)float[source]

Compute the Mean Squared Distance Error between two sets of labels (input and ref). Moreover, a warning is generated for each label mismatch.

Parameters
  • img – source image

  • ref – reference image

Returns

computed MSE

spinalcordtoolbox.labels.continuous_vertebral_levels(img: spinalcordtoolbox.image.Image)spinalcordtoolbox.image.Image[source]

This function transforms the vertebral levels file from the template into a continuous file. Instead of having integer representing the vertebral level on each slice, a continuous value that represents the position of the slice in the vertebral level coordinate system. The image must be RPI

Parameters

img – input image

Returns

image with continuous vertebral levels

spinalcordtoolbox.labels.create_labels(img: spinalcordtoolbox.image.Image, coordinates: Sequence[spinalcordtoolbox.types.Coordinate])spinalcordtoolbox.image.Image[source]

Add labels provided by a user to the image. This method works only if the user inserted correct coordinates. If only one label is to be added, coordinates must be completed with ‘[]’

Parameters
  • img – source image

  • coordinates – list of Coordinate objects (see spinalcordtoolbox.types)

Returns

labeled source image

spinalcordtoolbox.labels.create_labels_along_segmentation(img: spinalcordtoolbox.image.Image, labels: Sequence[Tuple[int, int]])spinalcordtoolbox.image.Image[source]

Create an image with labels defined along the spinal cord segmentation (or centerline). Input image does not need to be RPI (re-orientation is done within this function).

Parameters
  • img – source segmentation

  • labels – list of label tuples as (z_value, label_value)

Returns

labeled segmentation (Image)

spinalcordtoolbox.labels.create_labels_empty(img: spinalcordtoolbox.image.Image, coordinates: Sequence[spinalcordtoolbox.types.Coordinate])spinalcordtoolbox.image.Image[source]

Create an empty image with labels listed by the user. This method works only if the user inserted correct coordinates. If only one label is to be added, coordinates must be completed with ‘[]’

Parameters
  • img – source image

  • coordinates – list of Coordinate objects (see spinalcordtoolbox.types)

Returns

empty image with labels

spinalcordtoolbox.labels.cubic_to_point(img: spinalcordtoolbox.image.Image)spinalcordtoolbox.image.Image[source]

Calculate the center of mass of each group of labels and returns a file of same size with only a label by group at the center of mass of this group. It is to be used after applying homothetic warping field to a label file as the labels will be dilated.

Note

Be careful: this algorithm computes the center of mass of voxels with same value, if two groups of voxels with the same value are present but separated in space, this algorithm will compute the center of mass of the two groups together.

Parameters

img – source image

Returns

image with labels at center of mass

spinalcordtoolbox.labels.increment_z_inverse(img: spinalcordtoolbox.image.Image)spinalcordtoolbox.image.Image[source]

Take all non-zero values, sort them along the inverse z direction, and attributes the values 1, 2, 3, etc.

Parameters

img – source image

Returns

image with non-zero values sorted along inverse z

spinalcordtoolbox.labels.label_vertebrae(img: spinalcordtoolbox.image.Image, vertebral_levels: Optional[Sequence[int]] = None)spinalcordtoolbox.image.Image[source]

Find the center of mass of vertebral levels specified by the user.

Parameters
  • img – source image

  • vertebral_levels – list of vertebral levels

Returns

image with labels

spinalcordtoolbox.labels.labelize_from_discs(img: spinalcordtoolbox.image.Image, ref: spinalcordtoolbox.image.Image)spinalcordtoolbox.image.Image[source]

Create an image with regions labelized depending on values from reference. Typically, user inputs a segmentation image, and labels with disks position, and this function produces a segmentation image with vertebral levels labelized. Labels are assumed to be non-zero and incremented from top to bottom, assuming a RPI orientation

Parameters
  • img – segmentation

  • ref – reference labels

Returns

segmentation image with vertebral levels labelized

spinalcordtoolbox.labels.remove_labels_from_image(img: spinalcordtoolbox.image.Image, labels: Sequence[int])spinalcordtoolbox.image.Image[source]

Remove specified labels (set to 0) from an image.

Parameters
  • img – source image

  • labels – list of specified labels to remove

Returns

image with labels specified removed

spinalcordtoolbox.labels.remove_missing_labels(img: spinalcordtoolbox.image.Image, ref: spinalcordtoolbox.image.Image)[source]

Compare an input image and a reference image. Remove any label from the input image that doesn’t exist in the reference image.

Parameters
  • img – source image

  • ref – reference image

Returns

image with labels missing from reference removed

spinalcordtoolbox.labels.remove_other_labels_from_image(img: spinalcordtoolbox.image.Image, labels: Sequence[int])spinalcordtoolbox.image.Image[source]

Remove labels other than specified from an image

Parameters
  • img – source image

  • labels – list of specified labels to keep

Returns

image with labels specified kept only

Spinal Cord Flattening

spinalcordtoolbox.flattening

spinalcordtoolbox.flattening.flatten_sagittal(im_anat, im_centerline, verbose)[source]

Flatten a 3D volume using the segmentation, such that the spinal cord is centered in the R-L medial plane.

Parameters
  • im_anat

  • im_centerline

  • verbose

Returns

Motion Correction

spinalcordtoolbox.moco

class spinalcordtoolbox.moco.ParamMoco(is_diffusion=None, group_size=1, metric='MeanSquares', smooth='1')[source]

Class with a bunch of moco-specific parameters

Parameters
  • is_diffusion – Bool: If True, data will be treated as diffusion-MRI data (process slightly differs)

  • group_size – int: Number of images averaged for ‘dwi’ method.

  • metric – {MeanSquares, MI, CC}: metric to use for registration

  • smooth – str: Smoothing sigma in mm # TODO: make it int

spinalcordtoolbox.moco.copy_mat_files(nt, list_file_mat, index, folder_out, param)[source]

Copy mat file from the grouped folder to the final folder (will be used by all individual ungrouped volumes)

Parameters
  • nt – int: Total number of volumes in native 4d data

  • list_file_mat – list of list: File name of transformations

  • index – list: Index to associate a given matrix file with a 3d volume (from the 4d native data)

  • param – Param class

  • folder_out – str: Output folder

Returns

None

spinalcordtoolbox.moco.moco(param)[source]

Main function that performs motion correction.

Parameters

param

Returns

spinalcordtoolbox.moco.moco_wrapper(param)[source]

Wrapper that performs motion correction.

Parameters

param – ParamMoco class

Returns

fname_moco

spinalcordtoolbox.moco.register(param, file_src, file_dest, file_mat, file_out, im_mask=None)[source]

Register two images by estimating slice-wise Tx and Ty transformations, which are regularized along Z. This function uses ANTs’ isct_antsSliceRegularizedRegistration.

Parameters
  • param

  • file_src

  • file_dest

  • file_mat

  • file_out

  • im_mask – Image of mask, could be 2D or 3D

Returns

Helpers and Utilities

spinalcordtoolbox.math

spinalcordtoolbox.math.compute_similarity(data1, data2, metric)[source]

Compute a similarity metric between two images data

Parameters
  • data1 – numpy.array 3D data

  • data2 – numpy.array 3D data

  • fname_out – file name of the output file. Output file should be either a text file (‘.txt’) or a pickle file (‘.pkl’, ‘.pklz’ or ‘.pickle’)

  • metric – ‘mi’ for mutual information or ‘corr’ for pearson correlation coefficient

Returns

tuple with computetd results of similarity, data1 flattened array, data2 flattened array

spinalcordtoolbox.math.concatenate_along_4th_dimension(data1, data2)[source]

Concatenate two data along 4th dimension.

Parameters
  • data1 – 3d or 4d array

  • data2 – 3d or 4d array

Return data_concat

concate(data1, data2)

spinalcordtoolbox.math.correlation(x, y, type='pearson')[source]

Compute pearson or spearman correlation coeff Pearson’s R is parametric whereas Spearman’s R is non parametric (less sensitive)

Parameters
  • x – 1D numpy.array : flatten data from an image

  • y – 1D numpy.array : flatten data from an image

  • type – str: ‘pearson’ or ‘spearman’: type of R correlation coeff to compute

Returns

float value : correlation coefficient (between -1 and 1)

spinalcordtoolbox.math.denoise_nlmeans(data_in, patch_radius=1, block_radius=5)[source]
Parameters

data_in – nd_array to denoise

Note

for more info about patch_radius and block radius, please refer to the dipy website: http://nipy.org/dipy/reference/dipy.denoise.html#dipy.denoise.nlmeans.nlmeans

spinalcordtoolbox.math.dice(im1, im2)[source]

Computes the Dice coefficient, a measure of set similarity.

:param im1 : array-like, bool Any array of arbitrary size. If not boolean, will be converted. :param im2 : array-like, bool Any other array of identical size. If not boolean, will be converted. :return dice : float Dice coefficient as a float on range [0,1]. Maximum similarity = 1 No similarity = 0

Note

The order of inputs for dice is irrelevant. The result will be identical if im1 and im2 are switched.

Source: https://gist.github.com/JDWarner/6730747

spinalcordtoolbox.math.dilate(data, size, shape, dim=None)[source]

Dilate data using ball structuring element

Parameters
  • data – Image or numpy array: 2d or 3d array

  • size – int: If shape={‘square’, ‘cube’}: Corresponds to the length of an edge (size=1 has no effect). If shape={‘disk’, ‘ball’}: Corresponds to the radius, not including the center element (size=0 has no effect).

  • shape – {‘square’, ‘cube’, ‘disk’, ‘ball’}

  • dim – {0, 1, 2}: Dimension of the array which 2D structural element will be orthogonal to. For example, if you wish to apply a 2D disk kernel in the X-Y plane, leaving Z unaffected, parameters will be: shape=disk, dim=2.

Returns

numpy array: data dilated

spinalcordtoolbox.math.erode(data, size, shape, dim=None)[source]

Dilate data using ball structuring element

Parameters
  • data – Image or numpy array: 2d or 3d array

  • size – int: If shape={‘square’, ‘cube’}: Corresponds to the length of an edge (size=1 has no effect). If shape={‘disk’, ‘ball’}: Corresponds to the radius, not including the center element (size=0 has no effect).

  • shape – {‘square’, ‘cube’, ‘disk’, ‘ball’}

  • dim – {0, 1, 2}: Dimension of the array which 2D structural element will be orthogonal to. For example, if you wish to apply a 2D disk kernel in the X-Y plane, leaving Z unaffected, parameters will be: shape=disk, dim=2.

Returns

numpy array: data dilated

spinalcordtoolbox.math.laplacian(data, sigmas)[source]

Apply Laplacian filter

spinalcordtoolbox.math.mutual_information(x, y, nbins=32, normalized=False)[source]

Compute mutual information

Parameters
  • x – 1D numpy.array : flatten data from an image

  • y – 1D numpy.array : flatten data from an image

  • nbins – number of bins to compute the contingency matrix (only used if normalized=False)

Returns

float non negative value : mutual information

spinalcordtoolbox.math.smooth(data, sigmas)[source]

Smooth data by convolving Gaussian kernel :param data: input 3D numpy array :param sigmas: Kernel SD in voxel :return:

spinalcordtoolbox.metadata

class spinalcordtoolbox.metadata.InfoLabel(indiv_labels=None, combined_labels=None, clusters_apriori=None)[source]

Class representing data available in info_label.txt meta-data files, which are used to tie together several NIFTI files covering the same volume, each containing a layer.

The info_label.txt file contains at least one IndivLabels section, which lists layer label id, layer label name, and layer filename (path relative to the info_label.txt file).

Another possible section is CombinedLabels which is creating new labels (ids and names) by combining several labels from IndivLabels.

Another possible section is MAPLabels which contains clusters used for the first step of the MAP estimation (“for advanced users only”).

The file is text, UTF-8 encoded; see the loading/saving code for the detailed file layout.

Parameters
  • indiv_labels – list of 3-tuple with (id, name, filename)

  • combined_labels – list of 3-tuple with (id, name, ids)

  • clusters_apriori – list of 2-tuple with (name, ids)

load(file, parent=None, verify=True)[source]

Load contents from file :param file: input filename or file-like object to load from

save(file, header=None)[source]

Save contents to file :param file: output filename or file-like object

spinalcordtoolbox.metadata.get_file_label(path_label='', id_label=0, output='file')[source]

Get label file name given based on info_label.txt file. :param path_label: folder containing info_label.txt and the files :param id_label: (int) ID of the label to be found :param output: {file, filewithpath} :return: selected output ; if not found, raise a RuntimeError

spinalcordtoolbox.metadata.get_indiv_label_info(directory)[source]

Get all individual label info (id, name, filename) in a folder :param directory: folder containing info_label.txt and the files :return: dictionary containing “id” the label IDs (int), “name” the labels (string), “file” the label filename (string)

spinalcordtoolbox.metadata.read_label_file(path_info_label, file_info_label)[source]

Reads file_info_label (located inside label folder) and returns the information needed.

spinalcordtoolbox.types

class spinalcordtoolbox.types.Centerline(points_x=None, points_y=None, points_z=None, deriv_x=None, deriv_y=None, deriv_z=None, fname=None)[source]

This class represents a centerline in an image. Its coordinates can be in voxel space as well as in physical space. A centerline is defined by its points and the derivatives of each point. When initialized, the lenght of the centerline is computed as well as the coordinate reference system of each plane. # TODO: Check if the description above is correct. I’ve tried to input voxel space coordinates, and it broke the # code. For example, the method extract_perpendicular_square() is (i think) expecting physical coordinates.

average_vert_length = {'C1': 0.0, 'C2': 20.176514191661337, 'C3': 17.022090519403065, 'C4': 17.842111671016056, 'C5': 16.80035699231943, 'C6': 16.019212889311383, 'C7': 15.715854192723905, 'L1': 31.89272719870084, 'L2': 33.51189047448645, 'L3': 35.72141371861744, 'PMG': 15.0, 'PMJ': 30.0, 'T1': 16.84466163681078, 'T10': 25.501856729317133, 'T11': 27.619238824308123, 'T12': 29.465119270009946, 'T2': 19.865049296865475, 'T3': 21.550165130933905, 'T4': 21.761237991438083, 'T5': 22.633281372803687, 'T6': 23.801974227738132, 'T7': 24.35835781375833, 'T8': 25.200266294477885, 'T9': 25.315272064638506}

{‘T10’: [‘T10’, 25.543101799896391, 2.0015883550878457], ‘T11’: [‘T11’, 27.192970855618441, 1.9996136135271434], ‘T12’: [‘T12’, 29.559890137292335, 2.0204112073304121], ‘PMG’: [‘PMG’, 12.429867526011929, 2.9899172582983007], ‘C3’: [‘C3’, 18.229087873095388, 1.3299710200291315], ‘C2’: [‘C2’, 18.859365127066937, 1.5764843286826156], ‘C1’: [‘C1’, 0.0, 0.0], ‘C7’: [‘C7’, 15.543004729447034, 1.5597730786882851], ‘C6’: [‘C6’, 15.967482996580138, 1.4698898678270345], ‘PMJ’: [‘PMJ’, 11.38265467206886, 1.5641456310519117], ‘C4’: [‘C4’, 17.486130819790912, 1.5888243108648978], ‘T8’: [‘T8’, 25.649136105105754, 4.6835454011234718], ‘T9’: [‘T9’, 25.581999112288241, 1.9565018840832449], ‘T6’: [‘T6’, 23.539740893750668, 1.9073272889977211], ‘T7’: [‘T7’, 24.388589291326571, 1.828160893366733], ‘T4’: [‘T4’, 22.076131620822075, 1.726133989579701], ‘T5’: [‘T5’, 22.402770293433733, 2.0157113843189087], ‘T2’: [‘T2’, 19.800131846755267, 1.7600195442391204], ‘T3’: [‘T3’, 21.287064228802027, 1.8123109081532691], ‘T1’: [‘T1’, 16.525065003339993, 1.6130238001641826], ‘L2’: [‘L2’, 34.382300279977912, 2.378543023223767], ‘L3’: [‘L3’, 34.804841812064133, 2.7878124182683481], ‘L1’: [‘L1’, 32.02934490161379, 2.7697447948338381], ‘C5’: [‘C5’, 16.878263370935201, 1.6952832966782569]}

compare_centerline(other, reference_image=None)[source]

This function compute the mean square error and the maximum distance between two centerlines. If a reference image is provided, the distance metrics are computed on each slices where the both centerlines are present. :param other: Centerline object :params reference_image: Image object

Returns

mse, mean, std, max

compute_coordinate_system(index)[source]

This function computes the cordinate reference system (X, Y, and Z axes) for a given index of centerline.

Parameters

index – int

Returns

compute_vertebral_distribution(disks_levels, label_reference='C1')[source]

This function computes the vertebral distribution along the centerline, based on the position of intervertebral disks in space. A reference label can be provided (default is top of C1) so that relative distances are computed from this reference.

Parameters
  • disks_levels – list: list of coordinates with value [[x, y, z, value], [x, y, z, value], …] the value correspond to the intervertebral disk label

  • label_reference – reference label from which relative position will be computed. Must be on of self.labels_regions

display(mode='absolute')[source]

This function display the centerline using matplotlib. Two modes are available: absolute and relative. The absolute mode display the absolute position of centerline points. The relative mode display the centerline position relative to the reference label (default is C1). This mode requires the computation of vertebral distribution beforehand.

Parameters

mode – {absolute, relative} see description of function for details

find_nearest_index(coord)[source]

This function returns the index of the nearest point from centerline. Returns None if list of centerline points is empty. Raise an exception is the input coordinate has wrong format.

Parameters

coord – must be a numpy array [x, y, z]

Returns

index

get_closest_to_relative_position(vertebral_level, relative_position, mode='levels')[source]
Parameters
  • vertebral_level

  • relative_position – if mode is ‘levels’, it is the relative position [0, 1] from upper disk if mode is ‘length’, it is the relative position [mm] from C1 top

  • mode – {‘levels’, ‘length’}

get_distance_from_plane(coord, index, plane_params=None)[source]

This function returns the distance between a coordinate and the plan at index position. If the derivative at index is nul (a, b, c = 0, 0, 0), a ValueError exception is raised.

Parameters
  • coord – must be a numpy array [x, y, z]

  • index – int

  • plane_params – list [a, b, c, d] with plane parameters. If not provided, these parameters are computed from index.

Returns

get_in_plane_coordinates(coord, index)[source]

This function returns the coordinate of the point from coord in the coordinate system of the plane. The point must be in the plane (you can use the function get_projected_coordinate_on_plane() to get it.

Parameters
  • coord – must be a numpy array [x, y, z]

  • index – int

Returns

get_nearest_plane(coord, index=None)[source]

This function computes the nearest plane from the point and returns the parameters of its parametric equation [a, b, c, d] and the distance between the point and the plane.

Parameters

coord – must be a numpy array [x, y, z]

Returns

index, plane_parameters [a, b, c, d|, distance_from_plane

get_plan_parameters(index)[source]

This function returns the parameters of the parametric equation of the plane at index.

Parameters

index – int

Returns

List of parameters [a, b, c, d], corresponding to plane parametric equation a*x + b*y + c*z + d = 0

get_point_from_index(index)[source]

Returns the coordinate of centerline at specified index. Raise an index error if the index is not in the list.

Parameters

index – int

Returns

get_projected_coordinates_on_plane(coord, index, plane_params=None)[source]

This function returns the coordinates of

Parameters
  • coord – must be a numpy array [x, y, z]

  • index – int

  • plane_params

Returns

class spinalcordtoolbox.types.Coordinate(coord=None, mode='continuous')[source]

Class to represent 3D coordinates.

Parameters
  • Point – See class definition above

  • mode – ‘index’, ‘continuous’ # TODO: document

Example: .. code:: python

coord = Coordinate([x, y, z]) coord = Coordinate([x, y, z, value])

permute(img, orient_dest, orient_src=None)[source]

Permute coordinate based on source and destination orientation.

:param img : spinalcordtoolbox.Image() object :param orient_dest: :param orient_src: :return:

Example: .. code:: python

coord.permute(Image(‘data.nii.gz’), ‘RPI’) coord.permute(Image(‘data.nii.gz’), ‘RPI’, orient_src=’SAL’)

class spinalcordtoolbox.types.CoordinateValue(coord=None, mode='index')[source]
class spinalcordtoolbox.types.Point[source]

spinalcordtoolbox.template

spinalcordtoolbox.template.get_slices_from_vertebral_levels(im_vertlevel, level)[source]

Find the slices of the corresponding vertebral level. Important: This function assumes that the 3rd dimension is Z. :param im_vertlevel: image object of vertebral labeling (e.g., label/template/PAM50_levels.nii.gz) :param level: int: vertebral level :return: list of int: slices

spinalcordtoolbox.template.get_vertebral_level_from_slice(im_vertlevel, idx_slice)[source]

Find the vertebral level of the corresponding slice. Important: This function assumes that the 3rd dimension is Z. :param im_vertlevel: image object of vertebral labeling (e.g., label/template/PAM50_levels.nii.gz) :param idx_slice: int: slice (z) :return: int: vertebral level. If no level is found (only zeros on this slice), return None.