scilpy.image package

scilpy.image.labels module

scilpy.image.labels.combine_labels(data_list, indices_per_input_volume, out_labels_choice, background_id=0, merge_groups=False)[source]
Parameters:
  • data_list (list) – List of np.ndarray. Data as labels.

  • indices_per_input_volume (list[np.ndarray]) – List of np.ndarray containing the indices to use in each input volume.

  • out_labels_choice (tuple(str, any)) –

    Tuple of a string expressing the choice of output option and the associated necessary value. Choices are:

    (‘all_labels’): Keeps values from the input volumes, or with

    merge_groups, used the volumes ordering.

    (‘out_label_ids’, list): Out labels will be renamed as given from

    the list.

    (‘unique’): Out labels will be renamed to range from 1 to

    total_nb_labels (+ the background).

    (‘group_in_m’): Add (x * 10 000) to each volume labels, where x is the

    input volume order number.

  • background_id (int) – Background id, excluded from output. The value is also used as output background value. Default : 0.

  • merge_groups (bool) – If true, indices from indices_per_input_volume will be merged for each volume, as a single label. Can only be used with ‘all_labels’ or ‘out_label_ids’. Default: False.

scilpy.image.labels.dilate_labels(data, vox_size, distance, nbr_processes, labels_to_dilate=None, labels_not_to_dilate=None, labels_to_fill=None, mask=None)[source]
Parameters:
  • data (np.ndarray) – The data (as labels) to dilate.

  • vox_size (np.ndarray(1, 3)) – The voxel size.

  • distance (float) – Maximal distance to dilate (in mm).

  • nbr_processes (int) – Number of processes.

  • labels_to_dilate (list, optional) – Label list to dilate. By default it dilates all labels not in labels_to_fill nor in labels_not_to_dilate.

  • labels_not_to_dilate (list, optional) – Label list not to dilate.

  • labels_to_fill (list, optional) – Background id / labels to be filled. The first one is given as output background value. Default: [0]

  • mask (np.ndarray, optional) – Only dilate values inside the mask.

scilpy.image.labels.get_binary_mask_from_labels(atlas, label_list)[source]

Get a binary mask from labels.

Parameters:
  • atlas (numpy.ndarray) – The image will all labels as values (ex, result from get_data_as_labels).

  • label_list (list[int]) – The labels to get.

scilpy.image.labels.get_data_as_labels(in_img)[source]

Get data as label (force type np.uint16), check data type before casting.

Parameters:

in_img (nibabel.nifti1.Nifti1Image) – Image.

Returns:

data – Data (dtype: np.uint16).

Return type:

numpy.ndarray

scilpy.image.labels.get_labels_from_mask(mask_data, labels=None, background_label=0, min_voxel_count=0)[source]

Get labels from a binary mask which contains multiple blobs. Each blob will be assigned a label, by default starting from 1. Background will be assigned the background_label value.

Parameters:
  • mask_data (np.ndarray) – The mask data.

  • labels (list, optional) – Labels to assign to each blobs in the mask. Excludes the background label.

  • background_label (int) – Label for the background.

  • min_voxel_count (int, optional) – Minimum number of voxels for a blob to be considered. Blobs with fewer voxels will be ignored.

Returns:

label_map – The labels.

Return type:

np.ndarray

scilpy.image.labels.get_stats_in_label(map_data, label_data, label_lut)[source]

Get statistics about a map for each label in an atlas.

Parameters:
  • map_data (np.ndarray) – The map from which to get statistics.

  • label_data (np.ndarray) – The loaded atlas.

  • label_lut (dict) – The loaded label LUT (look-up table).

Returns:

out_dict – A dict with one key per label name, and its values are the computed statistics.

Return type:

dict

scilpy.image.labels.harmonize_labels(original_data, min_voxel_overlap=1, max_adjacency=100.0)[source]

Harmonize lesion labels across multiple 3D volumes by ensuring consistent labeling.

This function takes multiple 3D NIfTI volumes with labeled regions (e.g., lesions) and harmonizes the labels so that regions that are the same across different volumes are assigned a consistent label. It operates by iteratively comparing labels in each volume to those in previous volumes and matching them based on spatial proximity and overlap.

Parameters:
  • original_data (list of numpy.ndarray) – A list of 3D numpy arrays where each array contains labeled regions. Labels should be non-zero integers, where each unique integer represents a different region or lesion.

  • min_voxel_overlap (int, optional) – Minimum number of overlapping voxels required for two regions (lesions) from different volumes to be considered as potentially the same lesion. Default is 1.

  • max_adjacency (float, optional) – Maximum distance allowed between the centroids of two regions for them to be considered as the same lesion. Default is 1e2 (infinite).

Returns:

A list of 3D numpy arrays with the same shape as original_data, where labels have been harmonized across all volumes. Each region across volumes that is identified as the same will have the same label.

Return type:

list of numpy.ndarray

scilpy.image.labels.load_wmparc_labels()[source]

Load labels dictionary of different parcellations from the Desikan-Killiany atlas.

scilpy.image.labels.merge_labels_into_mask(atlas, filtering_args)[source]

Merge labels into a mask.

Parameters:
  • atlas (np.ndarray) – Atlas with labels as a numpy array (uint16) to merge.

  • filtering_args (str) – Filtering arguments from the command line.

Returns:

mask – Mask obtained from the combination of multiple labels.

Return type:

nibabel.nifti1.Nifti1Image

scilpy.image.labels.remove_labels(labels_volume, label_indices, background_id=0)[source]

Remove given labels from the volume.

Parameters:
  • labels_volume (np.ndarray) – The volume (as labels).

  • label_indices (list) – List of labels indices to remove.

  • background_id (int) – Value used for removed labels

scilpy.image.labels.split_labels(labels_volume, label_indices)[source]

For each label in list, return a separate volume containing only that label.

Parameters:
  • labels_volume (np.ndarray) – A 3D volume.

  • label_indices (list or np.array) – The list of labels to extract.

Returns:

split_data – One 3D volume per label.

Return type:

list

scilpy.image.reslice module

scilpy.image.reslice.reslice(data, affine, zooms, new_zooms, order=1, mode='constant', cval=0, num_processes=1)[source]

Reslice data with new voxel resolution defined by new_zooms

Parameters:
  • data (array, shape (I,J,K) or (I,J,K,N)) – 3d volume or 4d volume with datasets

  • affine (array, shape (4,4)) – mapping from voxel coordinates to world coordinates

  • zooms (tuple, shape (3,)) – voxel size for (i,j,k) dimensions

  • new_zooms (tuple, shape (3,)) – new voxel size for (i,j,k) after resampling

  • order (int, from 0 to 5) – order of interpolation for resampling/reslicing, 0 nearest interpolation, 1 trilinear etc.. if you don’t want any smoothing 0 is the option you need.

  • mode (string ('constant', 'nearest', 'reflect' or 'wrap')) – Points outside the boundaries of the input are filled according to the given mode.

  • cval (float) – Value used for points outside the boundaries of the input if mode=’constant’.

  • num_processes (int) – Split the calculation to a pool of children processes. This only applies to 4D data arrays. If a positive integer then it defines the size of the multiprocessing pool that will be used. If 0, then the size of the pool will equal the number of cores available.

Returns:

  • data2 (array, shape (I,J,K) or (I,J,K,N)) – datasets resampled into isotropic voxel size

  • affine2 (array, shape (4,4)) – new affine for the resampled image

Examples

>>> from dipy.io.image import load_nifti
>>> from dipy.align.reslice import reslice
>>> from dipy.data import get_fnames
>>> f_name = get_fnames('aniso_vox')
>>> data, affine, zooms = load_nifti(f_name, return_voxsize=True)
>>> data.shape == (58, 58, 24)
True
>>> zooms
(4.0, 4.0, 5.0)
>>> new_zooms = (3.,3.,3.)
>>> new_zooms
(3.0, 3.0, 3.0)
>>> data2, affine2 = reslice(data, affine, zooms, new_zooms)
>>> data2.shape == (77, 77, 40)
True

scilpy.image.utils module

scilpy.image.utils.check_slice_indices(vol_img, axis_name, slice_ids)[source]

Check that the given volume can be sliced at the given slice indices along the requested axis.

Parameters:
  • vol_img (nib.Nifti1Image) – Volume image.

  • axis_name (str) – Slicing axis name.

  • slice_ids (array-like) – Slice indices.

scilpy.image.utils.compute_nifti_bounding_box(img)[source]

Finds bounding box from data and transforms it in world space for use on data with different attributes like voxel size.

Parameters:

img (nib.Nifti1Image) – Input image file.

Returns:

wbbox – Bounding box in world space.

Return type:

WorldBoundingBox Object

scilpy.image.utils.extract_affine(input_files)[source]

Extract the affine from a list of nifti files.

Parameters:

input_files (list of strings (file paths)) – Diffusion data files.

Returns:

affine – Affine of the nifti volume.

Return type:

np.ndarray

scilpy.image.utils.find_strides_transform(strides)[source]

Find the transform required to get to [1, 2, 3] from the current strides.

Parameters:

strides (np.array) – Current strides of the volume.

Returns:

transform – Transform to apply to get to [1, 2, 3].

Return type:

list of int

scilpy.image.utils.split_mask_blobs_kmeans(data, nb_clusters)[source]

Split a mask between head and tail with k means.

Parameters:
  • data (numpy.ndarray) – Mask to be split.

  • nb_clusters (int) – Number of clusters to split.

Returns:

masks – The masks for each cluster.

Return type:

List[np.ndarray]

scilpy.image.utils.verify_strides(vol_img)[source]

Verify if the strides of the given volume are [1, 2, 3].

Parameters:

vol_img (nib.Nifti1Image) – Volume image.

Returns:

  • strides (np.array) – Current strides of the volume.

  • is_stride_correct (bool) – True if the strides are [1, 2, 3], false otherwise.

scilpy.image.utils.volume_iterator(img, blocksize=1, start=0, end=0)[source]

Generator that iterates on volumes of data.

Parameters:
  • img (nib.Nifti1Image) – Image of a 4D volume with shape X,Y,Z,N

  • blocksize (int, optional) – Number of volumes to return in a single batch

  • start (int, optional) – Starting iteration index in the 4D volume

  • end (int, optional) – Stopping iteration index in the 4D volume (the volume at this index is excluded)

Yields:

tuple of (list of int, ndarray) – The ids of the selected volumes, and the selected data as a 4D array

scilpy.image.volume_b0_synthesis module

scilpy.image.volume_b0_synthesis.compute_b0_synthesis(t1_data, t1_bet_data, b0_data, b0_bet_data, template_data, t1_affine, b0_affine, template_affine, verbose)[source]

Note. Tensorflow is required here, through dipy.Synb0. If not installed, dipy will raise an error, like: >> dipy.utils.tripwire.TripWireError: We need package tensorflow_addons for these functions, but import tensorflow_addons raised an ImportError.

Parameters:
  • t1_data (np.ndarary) – The T1 (wholebrain, with the skull).

  • t1_bet_data (np.ndarray) – The mask.

  • b0_data (np.ndarray) – The b0 (wholebrain, with the skull).

  • b0_bet_data (np.ndarray) – The mask.

  • template_data (np.ndarray) – The template for typical usage.

  • t1_affine (np.ndarray) – The T1’s affine.

  • b0_affine (np.ndarray) – The b0’s affine.

  • template_affine (np.ndarray) – The template’s affine

  • verbose (bool) – Whether to make dipy’s Synb0 verbose.

Returns:

rev_b0 – The synthetized b0.

Return type:

np.ndarray

scilpy.image.volume_math module

Utility operations provided for scil_volume_math.py and scil_connectivity_math.py

They basically act as wrappers around numpy to avoid installing MRtrix/FSL to apply simple operations on nibabel images or numpy arrays.

Docstrings here are NOT typical docstrings: they are the doc printed with the –help argument in those scripts.

Headers compatibility is NOT verified here. Verified in the main scripts.

scilpy.image.volume_math.absolute_value(input_list, ref_img)[source]
absolute_value: IMG

All negative values will become positive.

scilpy.image.volume_math.addition(input_list, ref_img)[source]
addition: IMGs

Add multiple images together.

scilpy.image.volume_math.around(input_list, ref_img)[source]
round: IMG

Round all decimal values to the closest integer.

scilpy.image.volume_math.base_10_log(input_list, ref_img)[source]
log_10: IMG

Apply a log (base 10) to all non zeros values of an image.

scilpy.image.volume_math.ceil(input_list, ref_img)[source]
ceil: IMG

Ceil all decimal values to the next integer.

scilpy.image.volume_math.closing(input_list, ref_img)[source]
closing: IMG, VALUE

Binary morphological operation, dilation followed by an erosion.

scilpy.image.volume_math.concatenate(input_list, ref_img)[source]
concatenate: IMGs

Concatenate a list of 3D and 4D images into a single 4D image.

scilpy.image.volume_math.convert(input_list, ref_img)[source]
convert: IMG

Perform no operation, but simply change the data type.

scilpy.image.volume_math.difference(input_list, ref_img)[source]
difference: IMG_1 IMG_2

Operation on binary image to keep voxels from the first file that are not in the second file (non-zeros).

scilpy.image.volume_math.dilation(input_list, ref_img)[source]
dilation: IMG, VALUE

Binary morphological operation to spatially extend the values of an image to their neighbors. VALUE is in voxels: an integer > 0.

scilpy.image.volume_math.division(input_list, ref_img)[source]
division: IMG_1 IMG_2

Divide first image by the second (danger of underflow and overflow) Ignore zeros values, excluded from the operation.

scilpy.image.volume_math.erosion(input_list, ref_img)[source]
erosion: IMG, VALUE

Binary morphological operation to spatially shrink the volume contained in a binary image. VALUE is in voxels: an integer > 0.

scilpy.image.volume_math.floor(input_list, ref_img)[source]
floor: IMG

Floor all decimal values to the previous integer.

scilpy.image.volume_math.gaussian_blur(input_list, ref_img)[source]
blur: IMG, VALUE

Apply a gaussian blur to a single image. VALUE is sigma, the standard deviation of the Gaussian kernel.

scilpy.image.volume_math.get_array_ops()[source]

Get a dictionary of all functions relating to array operations

scilpy.image.volume_math.get_image_ops()[source]

Get a dictionary of all functions relating to image operations

scilpy.image.volume_math.get_operations_doc(ops: dict)[source]

From a dictionary mapping operation names to functions, fetch and join all documentations, using the provided names.

scilpy.image.volume_math.intersection(input_list, ref_img)[source]
intersection: IMGs

Operation on binary image to keep the voxels, that are non-zero, are present in all files.

scilpy.image.volume_math.invert(input_list, ref_img)[source]
invert: IMG

Operation on binary image to interchange 0s and 1s in a binary mask.

scilpy.image.volume_math.lower_clip(input_list, ref_img)[source]
lower_clip: IMG THRESHOLD

All values below the threshold will be set to threshold.

scilpy.image.volume_math.lower_threshold(input_list, ref_img)[source]
lower_threshold: IMG THRESHOLD

All values below the threshold will be set to zero. All values above the threshold will be set to one.

scilpy.image.volume_math.lower_threshold_eq(input_list, ref_img)[source]
lower_threshold_eq: IMG THRESHOLD

All values below the threshold will be set to zero. All values above or equal the threshold will be set to one.

scilpy.image.volume_math.lower_threshold_otsu(input_list, ref_img)[source]
lower_threshold_otsu: IMG

All values below or equal to the Otsu threshold will be set to zero. All values above the Otsu threshold will be set to one. (Otsu’s method is an algorithm to perform automatic image thresholding of the background.)

scilpy.image.volume_math.maximum(input_list, ref_img)[source]
maximum: IMGs

Compute the voxel-wise maximum across images.

scilpy.image.volume_math.mean(input_list, ref_img)[source]
mean: IMGs

Compute the mean of images. If a single 4D image is provided, average along the last dimension.

scilpy.image.volume_math.multiplication(input_list, ref_img)[source]
multiplication: IMGs

Multiply multiple images together (danger of underflow and overflow)

scilpy.image.volume_math.natural_log(input_list, ref_img)[source]
log_e: IMG

Apply a natural log to all non zeros values of an image.

scilpy.image.volume_math.neighborhood_correlation(input_list, ref_img)[source]

correlation: IMGs

Computes the correlation of the 3x3x3 neighborhood of each voxel, for all pair of input images. The final image is the average correlation (through all pairs). For a given pair of images - Background is considered as 0. May lead to very high correlations close to the border of the background regions, or very poor ones if the background in both images differ. - Images are zero-padded. For the same reason as higher, may lead to very high correlations if you have data close to the border of the image. - NaN values (if a voxel’s neighborhood is entirely uniform; std 0) are replaced by

  • 0 if at least one neighborhood was entirely containing background.

  • 1 if the voxel’s neighborhoods are uniform in both images

  • 0 if the voxel’s neighborhoods is uniform in one image, but not the other.

UPDATE AS OF VERSION 2.0: Random noise was previously added in the process to help avoid NaN values. Now replaced by either 0 or 1 as explained above.

scilpy.image.volume_math.neighborhood_correlation_(input_list)[source]

Same as above (neighborhood_correlation) but without the verifications required for scil_volume_math.py.

input_list can be a list of images or a list of arrays.

scilpy.image.volume_math.normalize_max(input_list, ref_img)[source]
normalize_max: IMG

Normalize the image so the maximum value is one.

scilpy.image.volume_math.normalize_sum(input_list, ref_img)[source]
normalize_sum: IMG

Normalize the image so the sum of all values is one.

scilpy.image.volume_math.opening(input_list, ref_img)[source]
opening: IMG, VALUE

Binary morphological operation, erosion followed by a dilation.

scilpy.image.volume_math.std(input_list, ref_img)[source]
std: IMGs

Compute the standard deviation average of multiple images. If a single 4D image is provided, compute the STD along the last dimension.

scilpy.image.volume_math.subtraction(input_list, ref_img)[source]
subtraction: IMG_1 IMG_2

Subtract first image by the second (IMG_1 - IMG_2).

scilpy.image.volume_math.union(input_list, ref_img)[source]
union: IMGs

Operation on binary image to keep voxels, that are non-zero, in at least one file.

scilpy.image.volume_math.upper_clip(input_list, ref_img)[source]
upper_clip: IMG THRESHOLD

All values above the threshold will be set to threshold.

scilpy.image.volume_math.upper_threshold(input_list, ref_img)[source]
upper_threshold: IMG THRESHOLD

All values below the threshold will be set to one. All values above the threshold will be set to zero. Equivalent to lower_threshold followed by an inversion.

scilpy.image.volume_math.upper_threshold_eq(input_list, ref_img)[source]
upper_threshold_eq: IMG THRESHOLD

All values below or equal the threshold will be set to one. All values above the threshold will be set to zero. Equivalent to lower_threshold followed by an inversion.

scilpy.image.volume_math.upper_threshold_otsu(input_list, ref_img)[source]
upper_threshold_otsu: IMG

All values below the Otsu threshold will be set to one. All values above or equal to the Otsu threshold will be set to zero. Equivalent to lower_threshold_otsu followed by an inversion.

scilpy.image.volume_metrics module

scilpy.image.volume_metrics.estimate_piesno_sigma(data, number_coils=0)[source]

Here are Dipy’s note on this method: > It is expected that > 1. The data has a noisy, non-masked background and > 2. The data is a repetition of the same measurements along the last > axis, i.e. dMRI or fMRI data, not structural data like T1/T2. > This function processes the data slice by slice, as originally designed > inthe paper. Use it to get a slice by slice estimation of the noise, as > in spinal cord imaging for example.

Parameters:
  • data (np.ndarray) – The 4D volume.

  • number_coils (int) – The number of coils in the scanner.

Returns:

  • sigma (np.ndarray) – The piesno sigma estimation, one per slice.

  • mask_noise (np.ndarray) – The mask of pure noise voxels inferred from the data.

scilpy.image.volume_operations module

scilpy.image.volume_operations.apply_transform(transfo, reference, moving, interp='linear', keep_dtype=False)[source]

Apply transformation to an image using Dipy’s tool

Parameters:
  • transfo (numpy.ndarray) – Transformation matrix to be applied

  • reference (nib.Nifti1Image) – Filename of the reference image (target)

  • moving (nib.Nifti1Image) – Filename of the moving image

  • interp (string, either 'linear' or 'nearest') – the type of interpolation to be used, either ‘linear’ (for k-linear interpolation) or ‘nearest’ for nearest neighbor

  • keep_dtype (bool) – If True, keeps the data_type of the input moving image when saving the output image

Returns:

moved_im – The warped moving image.

Return type:

nib.Nifti1Image

scilpy.image.volume_operations.compute_distance_map(mask_1, mask_2, symmetric=False, max_distance=inf)[source]

Compute the distance map between two binary masks. The distance is computed using the Euclidean distance between the first mask and the closest point in the second mask.

Use the symmetric flag to compute the distance map in both directions.

WARNING: This function will work even if inputs are not binary masks, just make sure that you know what you are doing.

Parameters:
  • mask_1 (np.ndarray) – First binary mask.

  • mask_2 (np.ndarray) – Second binary mask.

  • symmetric (bool, optional) – If True, compute the symmetric distance map. Default is np.inf

  • max_distance (float, optional) – Maximum distance to consider for kdtree exploration. Default is None. If you put any value, coordinates further than this value will be considered as np.inf.

Returns:

distance_map – Distance map between the two masks.

Return type:

np.ndarray

scilpy.image.volume_operations.compute_nawm(lesion_atlas, nb_ring, ring_thickness, mask=None)[source]

Compute the NAWM (Normal Appearing White Matter) from a lesion map. The rings go from 2 to nb_ring + 2, with the lesion being 1.

The optional mask is used to compute the rings only in the mask region. This can be useful to avoid useless computation.

If the lesion_atlas is binary, the output will be 3D. If the lesion_atlas is a label map, the output will be 4D, with each label having its own NAWM.

Parameters:
  • lesion_atlas (np.ndarray) – Lesion map. Can be binary or label map.

  • nb_ring (int) – Number of rings to compute.

  • ring_thickness (int) – Thickness of the rings.

  • mask (np.ndarray, optional) – Mask where to compute the NAWM. Default is None.

Returns:

nawm – NAWM volume(s), 3D if binary lesion map, 4D if label lesion map.

Return type:

np.ndarray

scilpy.image.volume_operations.compute_snr(dwi, bval, bvec, b0_thr, mask, noise_mask=None, noise_map=None, split_shells=False)[source]

Computes the SNR. One SNR per DWI volume is computed, with SNR = mean(data) / std(noise)

Where - mean is the mean of all DWI voxels inside your given mask. - std is the standard deviatation of the noise. For instance, you could

want to use std of the background. Here, we use:
  • noise_map[mask] if noise_map is provided

  • data[noise_mask] if noise_mask is provided

  • data[automatic_mask] if neither are provided: we will try to discover a noise_mask automatically in the background (from the upper half, to avoid using neck and shoulder).

Parameters:
  • dwi (nib.Nifti1Image) – DWI file in nibabel format.

  • bval (array) – Array containing bvalues (from dipy.io.gradients.read_bvals_bvecs).

  • bvec (array) – Array containing bvectors (from dipy.io.gradients.read_bvals_bvecs).

  • b0_thr (int) – Threshold to define b0 minimum value.

  • mask (nib.Nifti1Image) – Mask file in nibabel format.

  • noise_mask (nib.Nifti1Image, optional) – Noise mask file in nibabel format. Only one of noise_mask or noise_map may be used.

  • noise_map (nib.Nifti1Image, optional) – Noise map file in nibabel format. Only one of noise_mask or noise_map may be used.

  • split_shells (bool) – If true, we will only work with one b-value per shell (the discovered centroids).

Returns:

  • val (dict) – Dictionary of values (bvec, bval, mean, std, snr) for all volumes.

  • noise_mask (np.ndarray or None) – The noise_mask that was used; either None (if noise_map was given), or the given mask, or the discovered mask.

scilpy.image.volume_operations.count_non_zero_voxels(image)[source]

Count number of non-zero voxels

Parameters:

image (np.ndarray) – The loaded image.

Returns:

nb_voxels – The count.

Return type:

int

scilpy.image.volume_operations.crop_volume(img: Nifti1Image, wbbox)[source]

Applies cropping from a world space defined bounding box and fixes the affine to keep data aligned.

Parameters:
  • img (nib.Nifti1Image) – Input image to crop.

  • wbbox (WorldBoundingBox) – Bounding box.

Returns:

cropped_im – The image with cropped data and transformed affine.

Return type:

nib.Nifti1Image

scilpy.image.volume_operations.flip_volume(data, axes)[source]

Flip volume along a specific axis.

Parameters:
  • data (np.ndarray) – Volume data.

  • axes (List) – A list containing any number of values amongst [‘x’, ‘y’, ‘z’].

Returns:

data – Flipped volume data along specified axes.

Return type:

np.ndarray

scilpy.image.volume_operations.mask_data_with_default_cube(data)[source]

Masks data outside a default cube (Cube: data.shape/3 centered)

Parameters:

data (np.ndarray) – Volume data, 3D.

Returns:

data – Data masked

Return type:

np.ndarray

scilpy.image.volume_operations.merge_metrics(*arrays, beta=1.0)[source]

Merge an arbitrary number of metrics into a single heatmap using a weighted geometric mean, ignoring NaN values. Each input array contributes equally to the geometric mean, and the result is boosted by a specified factor.

Parameters:
  • *arrays (ndarray) – An arbitrary number of input arrays (ndarrays). All arrays must have the same shape.

  • beta (float, optional) – Boosting factor for the geometric mean. The default is 1.0.

Returns:

Boosted geometric mean of the inputs (same shape as the input arrays) NaN values in any input array are propagated to the output.

Return type:

ndarray

scilpy.image.volume_operations.normalize_metric(metric, reverse=False)[source]

Normalize a metric array to a range between 0 and 1, optionally reversing the normalization.

Parameters:
  • metric (ndarray) – The input metric array to be normalized.

  • reverse (bool, optional) – If True, reverse the normalization (i.e., 1 - normalized value). Default is False.

Returns:

The normalized (and possibly reversed) metric array. NaN values in the input are retained.

Return type:

ndarray

scilpy.image.volume_operations.register_image(static, static_grid2world, moving, moving_grid2world, transformation_type='affine', dwi=None, fine=False)[source]

Register a moving image to a static image using either rigid or affine transformations. If a DWI (4D) is provided, it applies the transformation to each volume.

Parameters:
  • static (ndarray) – The static image volume to which the moving image will be registered.

  • static_grid2world (ndarray) – The grid-to-world (vox2ras) transformation associated with the static image.

  • moving (ndarray) – The moving image volume to register to the static image.

  • moving_grid2world (ndarray) – The grid-to-world (vox2ras) transformation associated with the moving image.

  • transformation_type (str, optional) – The type of transformation (‘rigid’ or ‘affine’). Default is ‘affine’.

  • dwi (ndarray, optional) – Diffusion-weighted imaging data (if applicable). Default is None. If given, then moving should be the reference template.

  • fine (bool, optional) – Whether to use fine or coarse settings for the registration. Default is False.

Raises:

ValueError – If the transformation_type is neither ‘rigid’ nor ‘affine’.

Returns:

  • moved (np.ndarray) – If dwi is None, returns the transformed moving image, else the transformed dwi.

  • transform (np.ndarray) – The transformation matrix.

scilpy.image.volume_operations.remove_outliers_ransac(in_data, min_fit, fit_thr, max_iter)[source]

Remove outliers from image using the RANSAC algorithm.

Parameters:
  • in_data (np.ndarray) – The input.

  • min_fit (int) – The minimum number of data values required to fit the model.

  • fit_thr (float) – Threshold value for determining when a data point fits a model.

  • max_iter (int) – The maximum number of iterations allowed in the algorithm.

Returns:

out_data – Data without outliers.

Return type:

np.ndarray

scilpy.image.volume_operations.resample_volume(img, ref_img=None, volume_shape=None, iso_min=False, voxel_res=None, interp='lin', enforce_dimensions=False)[source]

Function to resample a dataset to match the resolution of another reference dataset or to the resolution specified as in argument.

One (and only one) of the following options must be chosen: ref, volume_shape, iso_min or voxel_res.

Parameters:
  • img (nib.Nifti1Image) – Image to resample.

  • ref_img (nib.Nifti1Image, optional) – Reference volume to resample to. This method is used only if ref is not None. (default: None)

  • volume_shape (tuple, shape (3,) or int, optional) – Final shape to resample to. If the value it is set to is Y, it will resample to an isotropic shape of Y x Y x Y. This method is used only if volume_shape is not None. (default: None)

  • iso_min (bool, optional) – If true, resample the volume to R x R x R resolution, with R being the smallest current voxel dimension. If false, this method is not used.

  • voxel_res (tuple, shape (3,) or float, optional) – Set the zoom property of the image at the specified resolution.

  • interp (str, optional) – Interpolation mode. ‘nn’ = nearest neighbour, ‘lin’ = linear, ‘quad’ = quadratic, ‘cubic’ = cubic. (Default: linear)

  • enforce_dimensions (bool, optional) – If True, enforce the reference volume dimension (only if res is not None). (Default = False)

Returns:

resampled_image – Resampled image.

Return type:

nib.Nifti1Image

scilpy.image.volume_operations.reshape_volume(img, volume_shape, mode='constant', cval=0, dtype=None)[source]

Reshape a volume to a specified shape by padding or cropping. The new volume is centered wrt the old volume in world space.

Parameters:
  • img (nib.Nifti1Image) – The input image.

  • volume_shape (tuple of 3 ints) – The desired shape of the volume.

  • mode (str, optional) – Padding mode. See np.pad for more information. Default is ‘constant’.

  • cval (float, optional) – Value to use for padding when mode is ‘constant’. Default is 0.

  • dtype (np.dtype) – Data type to cast the volume to. If unset, the volume is kept to its original type.

Returns:

reshaped_img – The reshaped image.

Return type:

nib.Nifti1Image

scilpy.image.volume_operations.smooth_to_fwhm(data, fwhm)[source]

Smooth a volume to given FWHM.

Parameters:
  • data (np.ndarray) – 3D or 4D data. If it is 4D, processing invidually on each volume (on the last dimension)

  • fwhm (float) – Full width at half maximum.

scilpy.image.volume_operations.transform_dwi(reg_obj, static, dwi, interpolation='linear')[source]

Iteratively apply transformation to 4D image using Dipy’s tool

Parameters:
  • reg_obj (AffineMap) – Registration object from Dipy returned by AffineMap

  • static (numpy.ndarray) – Target image data

  • dwi (numpy.ndarray) – 4D numpy array containing a scalar in each voxel (moving image data)

  • interpolation (string, either 'linear' or 'nearest') – the type of interpolation to be used, either ‘linear’ (for k-linear interpolation) or ‘nearest’ for nearest neighbor

Returns:

trans_dwi – The warped 4D volume.

Return type:

nib.Nifti1Image

scilpy.image.volume_space_management module

class scilpy.image.volume_space_management.DataVolume(data, voxres, interpolation=None, must_be_3d=False)[source]

Bases: object

Class to access/interpolate data from nibabel object

get_value_at_coordinate(x, y, z, space, origin)[source]

Get the voxel value at coordinates x, y, z, in the dataset. Coordinates must be in the given space and origin.

If the coordinates are out of bound, the nearest voxel value is taken.

Parameters:
  • x (floats) – Voxel coordinates along each axis.

  • y (floats) – Voxel coordinates along each axis.

  • z (floats) – Voxel coordinates along each axis.

  • space (dipy Space) – ‘vox’ or ‘voxmm’.

  • origin (dipy Origin) – ‘corner’ or ‘center’.

Returns:

value – The value evaluated at voxel x, y, z.

Return type:

ndarray (self.dim[-1],)

get_value_at_idx(i, j, k)[source]

Get the voxel value at index i, j, k in the dataset. If the coordinates are out of bound, the nearest voxel value is taken.

Parameters:
  • i (ints) – Voxel indice along each axis.

  • j (ints) – Voxel indice along each axis.

  • k (ints) – Voxel indice along each axis.

Returns:

value – The value evaluated at voxel x, y, z.

Return type:

ndarray (self.dim[-1],)

is_coordinate_in_bound(x, y, z, space, origin)[source]

Test if voxel is in dataset range.

Parameters:
  • x (floats) – Voxel coordinates along each axis.

  • y (floats) – Voxel coordinates along each axis.

  • z (floats) – Voxel coordinates along each axis.

  • space (dipy Space) – ‘vox’ or ‘voxmm’.

  • origin (dipy Origin) – ‘corner’ or ‘center’.

Returns:

out – True if voxel is in dataset range, False otherwise.

Return type:

bool

is_idx_in_bound(i, j, k)[source]

Test if voxel is in dataset range.

Parameters:
  • i (ints) – Voxel indice along each axis (as ints).

  • j (ints) – Voxel indice along each axis (as ints).

  • k (ints) – Voxel indice along each axis (as ints).

Returns:

out – True if voxel is in dataset range, False otherwise.

Return type:

bool

static vox_to_idx(x, y, z, origin)[source]

Get the 3D indice of the closest voxel at position x, y, z expressed in mm.

Parameters:
  • x (floats) – Position coordinate in voxel space along x, y, z axis.

  • y (floats) – Position coordinate in voxel space along x, y, z axis.

  • z (floats) – Position coordinate in voxel space along x, y, z axis.

  • origin (Dipy Space) – ‘center’ or ‘corner’.

Returns:

out – 3D indice of voxel at position x, y, z.

Return type:

list

voxmm_to_idx(x, y, z, origin)[source]

Get the 3D indice of the closest voxel at position x, y, z expressed in mm.

Parameters:
  • x (floats) – Position coordinate (mm) along x, y, z axis.

  • y (floats) – Position coordinate (mm) along x, y, z axis.

  • z (floats) – Position coordinate (mm) along x, y, z axis.

  • origin (dipy Space) – ‘center’ or ‘corner’.

Returns:

x, y, z – 3D indice of voxel at position x, y, z.

Return type:

ints

voxmm_to_vox(x, y, z)[source]

Get voxel space coordinates at position x, y, z (mm).

Parameters:
  • x (floats) – Position coordinate (mm) along x, y, z axis.

  • y (floats) – Position coordinate (mm) along x, y, z axis.

  • z (floats) – Position coordinate (mm) along x, y, z axis.

Returns:

x, y, z – Voxel space coordinates for position x, y, z.

Return type:

floats

class scilpy.image.volume_space_management.FTODFDataVolume(centerlines, diameters, reference, blur_radius, random_generator, sh_basis, sh_order, smooth=0.006, full_basis=False, is_legacy=True, sphere_type='repulsion724')[source]

Bases: FibertubeDataVolume

Fibertube DataVolume that maps local fibertube orientations on a sphere, giving us a Fibertube Orientation Distribution Function (ftODF).

This DataVolume returns the same information as the FibertubeDataVolume class, but compressed into spherical harmonics to be used by a traditional ODF tracking algorithm.

class scilpy.image.volume_space_management.FibertubeDataVolume(centerlines, diameters, reference, blur_radius, random_generator)[source]

Bases: DataVolume

Adaptation of the scilpy.image.volume_space_management.AbstractDataVolume interface for fibertube tracking. Instead of a spherical function, provides direction and intersection volume of close-by fiber segments.

Data given at initialization must have “center” origin. Additionally, FibertubeDataVolume enforces this origin at every function call. This is because the origin must stay coherent with the data given at initialization and cannot change afterwards.

VALID_ORIGIN = 'center'
static extract_directions(pos, neighbors, blur_radius, segments_indices, centerlines, diameters, random_generator, volume_nb_samples=1000)[source]
get_absolute_direction(x, y, z)[source]
get_value_at_coordinate(x, y, z, space, origin)[source]

Get the voxel value at coordinates x, y, z, in the dataset. Coordinates must be in the given space and origin.

If the coordinates are out of bound, the nearest voxel value is taken.

Parameters:
  • x (floats) – Voxel coordinates along each axis.

  • y (floats) – Voxel coordinates along each axis.

  • z (floats) – Voxel coordinates along each axis.

  • space (dipy Space) – ‘vox’ or ‘voxmm’.

  • origin (dipy Origin) – ‘corner’ or ‘center’.

Returns:

value – The value evaluated at voxel x, y, z.

Return type:

ndarray (self.dim[-1],)

get_value_at_idx(i, j, k)[source]

Get the voxel value at index i, j, k in the dataset. If the coordinates are out of bound, the nearest voxel value is taken.

Parameters:
  • i (ints) – Voxel indice along each axis.

  • j (ints) – Voxel indice along each axis.

  • k (ints) – Voxel indice along each axis.

Returns:

value – The value evaluated at voxel x, y, z.

Return type:

ndarray (self.dim[-1],)

is_coordinate_in_bound(x, y, z, space, origin)[source]

Test if voxel is in dataset range.

Parameters:
  • x (floats) – Voxel coordinates along each axis.

  • y (floats) – Voxel coordinates along each axis.

  • z (floats) – Voxel coordinates along each axis.

  • space (dipy Space) – ‘vox’ or ‘voxmm’.

  • origin (dipy Origin) – ‘corner’ or ‘center’.

Returns:

out – True if voxel is in dataset range, False otherwise.

Return type:

bool

is_idx_in_bound(i, j, k)[source]

Test if voxel is in dataset range.

Parameters:
  • i (ints) – Voxel indice along each axis (as ints).

  • j (ints) – Voxel indice along each axis (as ints).

  • k (ints) – Voxel indice along each axis (as ints).

Returns:

out – True if voxel is in dataset range, False otherwise.

Return type:

bool

static vox_to_idx(x, y, z, origin)[source]

Get the 3D indice of the closest voxel at position x, y, z expressed in mm.

Parameters:
  • x (floats) – Position coordinate in voxel space along x, y, z axis.

  • y (floats) – Position coordinate in voxel space along x, y, z axis.

  • z (floats) – Position coordinate in voxel space along x, y, z axis.

  • origin (Dipy Space) – ‘center’ or ‘corner’.

Returns:

out – 3D indice of voxel at position x, y, z.

Return type:

list

vox_to_voxmm(x, y, z)[source]

Get mm space coordinates at position x, y, z (vox).

Parameters:
  • x (floats) – Position coordinate (vox) along x, y, z axis.

  • y (floats) – Position coordinate (vox) along x, y, z axis.

  • z (floats) – Position coordinate (vox) along x, y, z axis.

Returns:

x, y, z – mm space coordinates for position x, y, z.

Return type:

floats

voxmm_to_idx(x, y, z, origin)[source]

Get the 3D indice of the closest voxel at position x, y, z expressed in mm.

Parameters:
  • x (floats) – Position coordinate (mm) along x, y, z axis.

  • y (floats) – Position coordinate (mm) along x, y, z axis.

  • z (floats) – Position coordinate (mm) along x, y, z axis.

  • origin (dipy Space) – ‘center’ or ‘corner’.

Returns:

x, y, z – 3D indice of voxel at position x, y, z.

Return type:

ints