scilpy.viz package

scilpy.viz.color module

scilpy.viz.color.ambiant_occlusion(sft, colors, factor=4)[source]

Apply ambiant occlusion to a set of colors based on point density around each point.

Parameters:
  • sft (StatefulTractogram) – The streamlines.

  • colors (np.ndarray) – The original colors to modify.

  • factor (float) – The factor of occlusion (how density will affect the saturation).

Returns:

The modified colors.

Return type:

np.ndarray

scilpy.viz.color.clip_and_normalize_data_for_cmap(data, clip_outliers=False, min_range=None, max_range=None, min_cmap=None, max_cmap=None, log=False, LUT=None)[source]

Normalizes data between 0 and 1 for an easier management with colormaps. The real lower bound and upperbound are returned.

Data can be clipped to (min_range, max_range) before normalization. Alternatively, data can be kept as is, but the colormap be fixed to (min_cmap, max_cmap).

Parameters:
  • data (np.array) – The data: a vector array.

  • clip_outliers (bool) – If True, clips the data to the lowest and highest 5% quantile before normalizing and before any other clipping.

  • min_range (float) – Data values below min_range will be clipped.

  • max_range (float) – Data values above max_range will be clipped.

  • min_cmap (float) – Minimum value of the colormap. Most useful when min_range and max_range are not set; to fix the colormap range without modifying the data.

  • max_cmap (float) – Maximum value of the colormap. Idem.

  • log (bool) – If True, apply a logarithmic scale to the data.

  • LUT (np.ndarray) – If set, replaces the data values by the Look-Up Table values. In order, the first value of the LUT is set everywhere where data==1, etc.

scilpy.viz.color.convert_color_names_to_rgb(names)[source]

Convert a list of VTK color names to RGB

Parameters:

names (list) – List of VTK color names.

Returns:

colors – List of RGB vtkColor.

Return type:

list

scilpy.viz.color.format_hexadecimal_color_to_rgb(color)[source]

Convert a hexadecimal color name (either “#RRGGBB” or 0xRRGGBB) to RGB values.

Parameters:

color (str) – The hexadecimal name

Returns:

(R, G, B)

Return type:

int values.

scilpy.viz.color.generate_local_coloring(sft)[source]

Generate a coloring based on the local orientation of the streamlines.

Parameters:

sft (StatefulTractogram / ArraySequence / List) – The tractogram / streamlines to generate the coloring from.

Returns:

The generated colors.

Return type:

np.ndarray

scilpy.viz.color.generate_n_colors(n, generator=<function distinguishable_colormap>, pick_from_base10=True)[source]

Generate a set of N colors. When using the default parameters, colors will always be unique. When using a custom generator, ensure it generates unique colors, excluding the ones listed in BASE_10_COLORS, if unicity is desired.

Parameters:
  • n (int) – Number of colors to generate.

  • generator (function) – Color generating function f(nb_colors=n, exclude=[…]) -> [color, color, …], accepting an optional list of colors to exclude from the generation.

  • pick_from_base10 (bool) – When True, start picking from the base 10 colors before using the generator funtion (see BASE_COLORS_10).

Returns:

colors – A list of Nx3 RGB colors

Return type:

np.ndarray

scilpy.viz.color.get_lookup_table(name)[source]

Get a matplotlib lookup table (colormap) from a name or create a lookup table (colormap) from a list of named colors.

Parameters:

name (str) – Name of the lookup table (colormap), ex, jet, or: Two named colors separated by a -, ex, red-blue, to form a lookup table (colormap) from.

Returns:

The lookup table (colormap)

Return type:

matplotlib.colors.Colormap

scilpy.viz.color.lut_from_matplotlib_name(name, value_range, n_samples=256)[source]

Create a linear VTK lookup table from a matplotlib colormap.

Parameters:
  • name (str) – Name of the matplotlib colormap.

  • value_range (tuple) – Range of values to map the colors to.

  • n_samples (int) – Number of samples to take in the matplotlib colormap.

Returns:

A VTK lookup table (range: [0, 255]).

Return type:

vtkLookupTable

scilpy.viz.color.prepare_colorbar_figure(cmap, lbound, ubound, nb_values=255, nb_ticks=10, horizontal=False, log=False)[source]

Prepares a matplotlib figure of a colorbar.

Parameters:
  • cmap (plt colormap) – Ex, result from get_colormap().

  • lbound (float) – Lower bound

  • ubound (float) – Upper bound

  • nb_values (int) – Number of values. The cmap will be linearly divided between lbound and ubound into nb_values values. Default: 255.

  • nb_ticks (int) – The ticks on the colorbar can be set differently than the nb_values. Default: 10.

  • horizontal (bool) – If true, plot a horizontal cmap.

  • log (bool) – If true, apply a logarithm scaling.

Returns:

fig – The plt figure.

Return type:

plt figure

scilpy.viz.gradients module

scilpy.viz.gradients.build_ms_from_shell_idx(bvecs, shell_idx)[source]

Get bvecs from indexes

Parameters:
  • bvecs (numpy.ndarray) – bvecs

  • shell_idx (numpy.ndarray) – index for each bval

Returns:

ms – bvecs for each bval

Return type:

list of numpy.ndarray

scilpy.viz.gradients.plot_each_shell(ms, centroids, plot_sym_vecs=True, use_sphere=True, same_color=False, rad=0.025, opacity=1.0, ofile=None, ores=(300, 300), titles=None, silent=False)[source]

Plot each shell

Parameters:
  • ms (list of lists of numpy.ndarray) – bvecs for each bval: one list per shell.

  • centroids (list of ints) – List of shells to plot.

  • plot_sym_vecs (boolean) – Plot symmetrical vectors

  • use_sphere (boolean) – rendering of the sphere

  • same_color (boolean) – use same color for all shell

  • rad (float) – radius of each point

  • opacity (float) – opacity for the shells

  • ofile (str) – output filename. If not set, no output will be saved.

  • ores (tuple) – resolution of the output png

  • titles (list of str) – titles for the windows, one per shell

  • silent (bool) – If True, skips interactive visualization. In that case, titles will not be added to the window.

scilpy.viz.gradients.plot_proj_shell(ms, use_sym=True, use_sphere=True, same_color=False, rad=0.025, opacity=1.0, ofile=None, ores=(300, 300), title=None, silent=None)[source]

Plot each shell

Parameters:
  • ms (list of lists of numpy.ndarray) – bvecs for each bval: one list per shell.

  • use_sym (boolean) – Plot symmetrical vectors

  • use_sphere (boolean) – rendering of the sphere

  • same_color (boolean) – use same color for all shell

  • rad (float) – radius of each point

  • opacity (float) – opacity for the shells

  • ofile (str) – output filename. If not set, no output will be saved.

  • ores (tuple) – resolution of the output png

  • title (str) – title for the window

  • silent (bool) – If True, skips interactive visualization. Useful for debugging. In that case, titles will not be added to the window.

scilpy.viz.plot module

scilpy.viz.plot.plot_metrics_stats(means, stds, title=None, xlabel=None, ylabel=None, figlabel=None, fill_color=None, display_means=False)[source]

Plots the mean of a metric along n points with the standard deviation.

Parameters:
  • means (Numpy 1D (or 2D) array of size n) – Mean of the metric along n points.

  • stds (Numpy 1D (or 2D) array of size n) – Standard deviation of the metric along n points.

  • title (string) – Title of the figure.

  • xlabel (string) – Label of the X axis.

  • ylabel (string) – Label of the Y axis (suggestion: the metric name).

  • figlabel (string) – Label of the figure (only metadata in the figure object returned).

  • fill_color (string) – Hexadecimal RGB color filling the region between mean ± std. The hexadecimal RGB color should be formatted as #RRGGBB

  • display_means (bool) – Display the subjects means as semi-transparent line

Return type:

The figure object.

scilpy.viz.plot.plot_residuals(data_diff, mask, R_k, q1, q3, iqr, residual_basename)[source]

Plots residual statistics for DWI.

Parameters:
  • data_diff (np.ndarray) – The 4D residuals between the DWI and predicted data.

  • mask (Numpy 3D array or None) – Mask array indicating the region of interest for computing residuals. If None, residuals are computed for the entire dataset.

  • R_k (Numpy 1D array) – Mean residual values for each DWI volume.

  • q1 (Numpy 1D array) – First quartile values for each DWI volume.

  • q3 (Numpy 1D array) – Third quartile values for each DWI volume.

  • iqr (Numpy 1D array) – Interquartile range (Q3 - Q1) for each DWI volume.

  • residual_basename (string) – Basename for saving the output plot file. The file will be saved as ‘<residual_basename>_residuals_stats.png’.

Returns:

  • None

  • The function generates a plot and saves it as a PNG file.

scilpy.viz.screenshot module

scilpy.viz.screenshot.compose_image(img_scene, img_size, slice_number, *, corner_position=(0, 0), transparency_scene=None, image_alpha=1.0, labelmap_scene=None, labelmap_overlay_alpha=0.7, overlays_scene=None, overlays_alpha=0.7, overlays_colors=None, peaks_overlay_scene=None, peaks_overlay_alpha=0.7, display_slice_number=False, display_lr=False, lr_labels=['L', 'R'], canvas=None)[source]

Compose an image with the given scenes, with transparency, overlays, labelmap and annotations. If no canvas for the image is given, it will be automatically created with sizings to fit.

Parameters:
  • img_scene (np.ndarray) – Image scene data. Data should be 2D (dimx, dimy, 3).

  • img_size (array-like) – Image size (pixels) (width, height).

  • slice_number (int) – Number of the current slice.

  • corner_position (array-like) – Image corner (pixels) (left, top).

  • transparency_scene (np.ndarray, optional) – Transaprency scene data.

  • image_alpha (float) – Alpha value for the image in range [0, 1].

  • labelmap_scene (np.ndarray, optional) – Labelmap scene data.

  • labelmap_alpha (float) – Alpha value for labelmap overlay in range [0, 1].

  • overlays_scene (list[np.ndarray], optional) – Overlays scene data.

  • overlays_alpha (float) – Alpha value for the overlays in range [0, 1].

  • overlays_colors (list, optional) – Colors for the overlays as a list of 3 integers in range [0, 255].

  • peaks_overlay_scene (np.ndarray, optional) – Peaks overlay scene data.

  • peaks_overlay_alpha (float) – Alpha value for peaks overlay in range [0, 1].

  • display_slice_number (bool) – If true, displays the slice number in the upper left corner.

  • display_lr (bool or int) – If 1 or -1, annotates the left and right sides on the image. -1 flips left and right positions.

  • lr_labels (list) – Labels used to annotate the left and right sides of the image.

  • canvas (PIL.Image, optional) – Base canvas into which to paste the scene.

Returns:

canvas – Canvas containing the pasted scene.

Return type:

PIL.Image

scilpy.viz.screenshot.compose_mosaic(img_scene_container, cell_size, rows, cols, slice_numbers, overlap_factor=None, transparency_scene_container=None, image_alpha=1.0, labelmap_scene_container=None, labelmap_overlay_alpha=0.7, overlays_scene_container=None, overlays_alpha=0.7, overlays_colors=None, display_slice_number=False, display_lr=False, lr_labels=['L', 'R'])[source]

Create the mosaic canvas for given number of rows and columns, and the requested cell size and overlap values.

Parameters:
  • img_scene_container (list) – Image scene data container.

  • cell_size (array-like) – Cell size (pixels) (width, height).

  • rows (int) – Row count.

  • cols (int) – Column count.

  • overlap_factor (array-like) – Overlap factor (horizontal, vertical).

  • transparency_scene_container (iterable) – Transaprency scene data container.

  • image_alpha (float) – Alpha value for the image in range [0, 1].

  • labelmap_scene_container (iterable) – Labelmap scene data container.

  • overlays_scene_container (iterable) – Overlays scene data container.

  • overlays_alpha (float) – Alpha value for the overlays in range [0, 1].

  • overlays_colors (list, optional) – Color for the overlays as a list of 3 integers in range [0, 255].

  • display_slice_number (bool) – If true, displays the slice number in the upper left corner.

  • display_lr (bool or int) – If 1 or -1, annotates the left and right sides on the image. -1 flips left and right positions.

  • lr_labels (list) – Labels used to annotate the left and right sides of the image.

Returns:

mosaic – Canvas containing the mosaic scene.

Return type:

PIL.Image

scilpy.viz.screenshot.screenshot_contour(bin_img, orientation, slice_ids, size, bg_opacity=0.0)[source]

Take a screenshot of the given binary image countour with the appropriate slice data at the provided slice indices.

Parameters:
  • bin_img (nib.Nifti1Image) – Binary volume image.

  • orientation (str) – Slicing axis name.

  • slice_ids (array-like) – Slice indices.

  • size (array-like) – Size of the screenshot image (pixels).

  • bg_opacity (float) – Background opacity in range [0, 1].

Returns:

snapshots – Scene screenshots generator.

Return type:

generator

scilpy.viz.screenshot.screenshot_peaks(img, orientation, slice_ids, size, mask_img=None)[source]

Take a screenshot of the given peaks image at the provided slice indices.

Parameters:
  • img (nib.Nifti1Image) – Peaks volume image.

  • orientation (str) – Slicing axis name.

  • slice_ids (array-like) – Slice indices.

  • size (array-like) – Size of the screenshot image (pixels).

Returns:

snapshots – Scene screenshots generator.

Return type:

generator

scilpy.viz.screenshot.screenshot_volume(img, orientation, slice_ids, size, labelmap=None)[source]

Take a screenshot of the given volume at the provided slice indices.

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

  • orientation (str) – Slicing axis name.

  • slice_ids (array-like) – Slice indices.

  • size (array-like) – Size of the screenshot image (pixels).

  • labelmap (str, vtkLookupTable, optional) – Either a vtk lookup table or a matplotlib colormap name.

Returns:

snapshots – Scene screenshots generator.

Return type:

generator

scilpy.viz.slice module

scilpy.viz.slice.create_bingham_slicer(data, orientation, slice_index, sphere, color_per_lobe=False)[source]

Create a bingham fit slicer using a combination of odf_slicer actors

Parameters:
  • data (Array) – Volume of shape (X, Y, Z, N_LOBES, NB_PARAMS) containing the Bingham distributions parameters. Note, NB_PARAMS is usually 7. One of X, Y, Z should be of value 1 (one slice).

  • orientation (str) – Name of the axis to visualize. Choices are axial, coronal and sagittal.

  • slice_index (int) – Index of the slice of interest along the chosen orientation.

  • sphere (DIPY Sphere) – Sphere used for visualization.

  • color_per_lobe (bool) – If true, each Bingham distribution is colored using a disting color. Else, Bingham distributions are colored by their orientation.

Returns:

actors – ODF slicer actors representing the Bingham distributions.

Return type:

list of fury odf_slicer actors

scilpy.viz.slice.create_contours_slicer(data, contour_values, orientation, slice_index, smoothing_radius=0.0, opacity=1.0, linewidth=3.0, color=[255, 0, 0])[source]

Create an isocontour slicer at specifed contours values.

Parameters:
  • data (np.ndarray) – Data from which to extract contours (mask, binary image, labels).

  • contour_values (list) – Values at which to extract isocontours.

  • orientation (str) – Name of the axis to visualize. Choices are axial, coronal and sagittal.

  • slice_index (int) – Index of the slice to visualize along the chosen orientation.

  • smoothing_radius (float) – Pre-smoothing to apply to the image before computing the contour (in pixels).

  • opacity (float) – Opacity of the contour.

  • linewidth (float) – Thickness of the contour line.

  • color (tuple, list of int) – Color of the contour in RGB [0, 255].

Returns:

contours_slicer – Fury object containing the contours information.

Return type:

actor.slicer

scilpy.viz.slice.create_odf_slicer(sh_fodf, orientation, slice_index, sphere, sh_order, sh_basis, full_basis, scale, sh_variance=None, mask=None, nb_subdivide=None, radial_scale=False, norm=False, colormap=None, variance_k=1, variance_color=(255, 255, 255), is_legacy=True)[source]

Create a ODF slicer actor displaying a fODF slice. The input volume is a 3-dimensional grid containing the SH coefficients of the fODF for each voxel at each voxel, with the grid dimension having a size of 1 along the axis corresponding to the selected orientation.

Parameters:
  • sh_fodf (np.ndarray) – Spherical harmonics of fODF data.

  • orientation (str) – Name of the axis to visualize. Choices are axial, coronal and sagittal.

  • slice_index (int) – Index of the slice to visualize along the chosen orientation.

  • sphere (DIPY Sphere) – Sphere used for visualization.

  • sh_order (int) – Maximum spherical harmonics order.

  • sh_basis (str) – Type of basis for the spherical harmonics.

  • full_basis (bool) – Boolean indicating if the basis is full or not.

  • scale (float) – Scaling factor for FODF.

  • sh_variance (np.ndarray, optional) – Spherical harmonics of the variance fODF data.

  • mask (np.ndarray, optional) – Only the data inside the mask will be displayed. Defaults to None.

  • nb_subdivide (int, optional) – Number of subdivisions for given sphere. If None, uses the given sphere as is.

  • radial_scale (bool) – If True, enables radial scale for ODF slicer.

  • norm (bool) – If True, enables normalization of ODF slicer.

  • colormap (str, optional) – Colormap for the ODF slicer. If None, a RGB colormap is used.

  • variance_k (float) – Factor that multiplies sqrt(variance).

  • variance_color (tuple, optional) – Color of the variance fODF data, in RGB.

  • is_legacy (bool) – Whether the SH basis is used in legacy formats [True].

Returns:

  • odf_actor (actor.odf_slicer) – Fury object containing the odf information.

  • var_actor (actor.odf_slicer) – Fury object containing the odf variance information.

scilpy.viz.slice.create_peaks_slicer(data, orientation, slice_index, *, peak_values=None, mask=None, color=None, peaks_width=1.0, opacity=1.0, symmetric=False)[source]

Create a peaks slicer actor rendering a slice of the input peaks.

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

  • orientation (str) – Name of the axis to visualize. Choices are axial, coronal and sagittal.

  • slice_index (int) – Index of the slice to visualize along the chosen orientation.

  • peak_values (np.ndarray, optional) – Peaks values. Defaults to None.

  • mask (np.ndarray, optional) – Only the data inside the mask will be displayed. Defaults to None.

  • color (tuple (3,), optional) – Color used for peaks. If None, a RGB colormap is used. Defaults to None.

  • peaks_width (float) – Width of peaks segments. Defaults to 1.0.

  • opacity (float) – Opacity of the peaks. Defaults to 1.0.

  • symmetric (bool) – If True, peaks are drawn for both peaks_dirs and -peaks_dirs. Else, peaks are only drawn for directions given by peaks_dirs. Defaults to False.

Returns:

slicer_actor – Fury object containing the peaks information.

Return type:

actor.peak_slicer

scilpy.viz.slice.create_texture_slicer(texture, orientation, slice_index, *, mask=None, value_range=None, opacity=1.0, offset=0.5, lut=None, interpolation='nearest')[source]

Create a texture displayed at a given offset (in the given orientation) from the origin of the grid.

Parameters:
  • texture (np.ndarray (3d or 4d)) – Texture image. Can be 3d for scalar data of 4d for RGB data, in which case the values must be between 0 and 255.

  • orientation (str) – Name of the axis to visualize. Choices are axial, coronal and sagittal.

  • slice_index (int) – Index of the slice to visualize along the chosen orientation.

  • mask (np.ndarray, optional) – Only the data inside the mask will be displayed. Defaults to None.

  • value_range (tuple (2,), optional) – The range of values mapped to range [0, 1] for the texture image. If None, it equals to (bg.min(), bg.max()). Defaults to None.

  • opacity (float) – The opacity of the texture image. Opacity of 0.0 means transparent and 1.0 is completely visible. Defaults to 1.0.

  • offset (float) – The offset of the texture image. Defaults to 0.5.

  • lut (str, vtkLookupTable, optional) – Either a vtk lookup table or a matplotlib colormap name.

  • interpolation (str) – Interpolation mode for the texture image. Choices are nearest or linear. Defaults to nearest.

Returns:

slicer_actor – Fury object containing the texture information.

Return type:

actor.slicer

scilpy.viz.utils module

scilpy.viz.utils.affine_from_offset(orientation, offset)[source]

Create an affine matrix from a scalar offset in given orientation, in RPS coordinates for imaging.

Parameters:
  • orientation (str) – Name of the axis to visualize. Choices are axial, coronal and sagittal.

  • offset (float) – The offset of the texture image.

Returns:

affine – The affine transformation.

Return type:

np.ndarray

scilpy.viz.utils.check_mosaic_layout(img_count, rows, cols)[source]

Check whether a mosaic can be built given the image count and the requested number of rows and columns. Raise a ValueError if it cannot be built.

Parameters:
  • img_count (int) – Image count to be arranged in the mosaic.

  • rows (int) – Row count.

  • cols (int) – Column count.

scilpy.viz.utils.compute_cell_topleft_pos(idx, cols, offset_h, offset_v)[source]

Compute the top-left position of a cell to be drawn in a mosaic.

Parameters:
  • idx (int) – Cell index in the mosaic.

  • cols (int) – Column count.

  • offset_h – Horizontal offset (pixels).

  • offset_v – Vertical offset (pixels).

Returns:

  • top_pos (int) – Top position (pixels).

  • left_pos (int) – Left position (pixels).