Comprehensive Python library for diffusion MRI analysis including tensor imaging, tractography, and visualization
—
3D visualization tools for diffusion data, streamlines, and scalar maps with interactive rendering capabilities. DIPY's visualization is built on the FURY library providing GPU-accelerated rendering for large datasets.
Core window and scene management for 3D visualization.
def Scene(background=(0, 0, 0), skybox=None):
"""
Create 3D visualization scene.
Parameters:
background (tuple): RGB background color (0-1)
skybox (array): skybox texture for background
Returns:
Scene: 3D scene object for adding actors
"""
def ShowManager(scene=None, title='DIPY', size=(300, 300), png_magnify=1, reset_camera=True, order_transparent=True):
"""
Create window manager for scene display.
Parameters:
scene (Scene): 3D scene to display
title (str): window title
size (tuple): window dimensions (width, height)
png_magnify (int): screenshot magnification
reset_camera (bool): reset camera on start
order_transparent (bool): depth sorting for transparency
Returns:
ShowManager: window manager object
"""
def record(scene=None, cam_pos=None, cam_focal=None, cam_view=None, out_path=None, path_numbering=False, n_frames=1, az_ang=10, magnification=1, size=(300, 300), reset_camera=True, verbose=False):
"""
Record scene to image or video files.
Parameters:
scene (Scene): scene to record
cam_pos (array): camera position
cam_focal (array): camera focal point
cam_view (array): camera view up vector
out_path (str): output file path
path_numbering (bool): add frame numbers to filename
n_frames (int): number of frames to record
az_ang (float): azimuth angle for rotation
magnification (int): image magnification
size (tuple): output image size
reset_camera (bool): reset camera before recording
verbose (bool): print progress information
"""Actors for rendering tractography streamlines with various styling options.
def line(lines, colors=None, opacity=1, linewidth=1, spline_subdiv=None, lod=True, lod_points=10000, lod_points_size=3, lookup_colormap=None):
"""
Create streamline actor for 3D rendering.
Parameters:
lines (list): streamlines as list of arrays
colors (array/tuple): colors for streamlines
opacity (float): transparency (0-1)
linewidth (float): line thickness
spline_subdiv (int): spline subdivision level
lod (bool): use level-of-detail rendering
lod_points (int): points threshold for LOD
lod_points_size (float): point size for LOD
lookup_colormap (array): colormap for scalar coloring
Returns:
vtkActor: streamline rendering actor
"""
def streamtube(lines, colors=None, opacity=1, linewidth=0.1, tube_sides=9, lod=True, lod_points=10000, lod_points_size=3, spline_subdiv=None, lookup_colormap=None):
"""
Create tube-based streamline actor.
Parameters:
lines (list): streamlines
colors (array): streamline colors
opacity (float): transparency
linewidth (float): tube radius
tube_sides (int): number of tube sides
lod (bool): level-of-detail rendering
lod_points (int): LOD threshold
lod_points_size (float): LOD point size
spline_subdiv (int): spline subdivision
lookup_colormap (array): scalar colormap
Returns:
vtkActor: tube streamline actor
"""
def bundle_maps(bundles, affine=None, bundle_dict=None, colors=None, offsets=None, hu_colors=None):
"""
Create bundle maps visualization.
Parameters:
bundles (list): list of streamline bundles
affine (array): voxel-to-world transformation
bundle_dict (dict): bundle metadata
colors (list): colors for each bundle
offsets (list): spatial offsets for bundles
hu_colors (list): hue-based colors
Returns:
vtkActor: bundle map actor
"""Actors for displaying 3D volumes and 2D slices of scalar data.
def slicer(data, affine=None, value_range=None, opacity=1.0, lookup_colormap=None, interpolation='linear', picking_tol=0.025):
"""
Create slice-based volume visualization.
Parameters:
data (array): 3D scalar data
affine (array): voxel-to-world transformation
value_range (tuple): data value range for coloring
opacity (float): slice opacity
lookup_colormap (array): colormap for values
interpolation (str): interpolation method ('linear', 'nearest')
picking_tol (float): picking tolerance for interaction
Returns:
vtkActor: slice rendering actor
"""
def scalar_bar(lookup_table, title=' '):
"""
Create scalar colorbar for legends.
Parameters:
lookup_table: VTK lookup table for colors
title (str): colorbar title
Returns:
vtkScalarBarActor: colorbar actor
"""
def contour_from_roi(data, affine=None, color=(1, 0, 0), opacity=1):
"""
Create surface contour from ROI mask.
Parameters:
data (array): binary mask data
affine (array): transformation matrix
color (tuple): surface color RGB
opacity (float): surface opacity
Returns:
vtkActor: surface contour actor
"""Specialized actors for diffusion tensor and orientation distribution function display.
def tensor_slicer(evals, evecs, scalar_colors=None, sphere=None, scale=2.2, norm=True, opacity=1.0):
"""
Visualize diffusion tensors as ellipsoids.
Parameters:
evals (array): tensor eigenvalues
evecs (array): tensor eigenvectors
scalar_colors (array): colors based on scalar values
sphere (Sphere): sphere for tessellation
scale (float): ellipsoid scaling factor
norm (bool): normalize tensor shapes
opacity (float): transparency
Returns:
vtkActor: tensor ellipsoid actor
"""
def odf_slicer(odfs, affine=None, mask=None, sphere=None, scale=2.2, norm=True, radial_scale=True, opacity=1.0, colormap='plasma', global_cm=False):
"""
Visualize orientation distribution functions.
Parameters:
odfs (array): ODF values on sphere
affine (array): transformation matrix
mask (array): binary mask for display
sphere (Sphere): sphere for ODF sampling
scale (float): ODF scaling
norm (bool): normalize ODF amplitudes
radial_scale (bool): scale radially
opacity (float): transparency
colormap (str): colormap name
global_cm (bool): use global colormap scaling
Returns:
vtkActor: ODF rendering actor
"""
def peak_slicer(peaks_dirs, peaks_values=None, mask=None, affine=None, colors=(1, 0, 0), opacity=1.0, linewidth=1, lod=False):
"""
Visualize fiber peaks as line segments.
Parameters:
peaks_dirs (array): peak directions
peaks_values (array): peak magnitudes
mask (array): display mask
affine (array): transformation matrix
colors (tuple/array): peak colors
opacity (float): line opacity
linewidth (float): line thickness
lod (bool): level-of-detail rendering
Returns:
vtkActor: peak line actor
"""Interactive UI components for data exploration and parameter adjustment.
class SlicerWidget:
"""Interactive slice viewer widget."""
def __init__(self, scene, slicer_actor, interactor=None):
"""Initialize slice widget with scene and actor."""
def set_slice_index(self, axis, index):
"""Set slice position along axis."""
class PeakSlicerWidget:
"""Interactive peak slice viewer."""
def __init__(self, peaks, affine=None, mask=None, scene=None):
"""Initialize peak slice widget."""
class BundleWidget:
"""Interactive bundle visualization widget."""
def __init__(self, streamlines, clusters=None, colors=None, scene=None):
"""Initialize bundle interaction widget."""Utilities for color mapping and visual styling of diffusion data.
def colormap_lookup_table(scale_range=(0, 1), hue_range=(0.8, 0), saturation_range=(1, 1), value_range=(0.8, 0.8)):
"""
Create lookup table for color mapping.
Parameters:
scale_range (tuple): data value range
hue_range (tuple): HSV hue range
saturation_range (tuple): HSV saturation range
value_range (tuple): HSV value range
Returns:
vtkLookupTable: VTK color lookup table
"""
def create_colormap(v, name='plasma', auto=True):
"""
Create colormap from data values.
Parameters:
v (array): data values for coloring
name (str): colormap name
auto (bool): automatic range scaling
Returns:
array: RGB colors for data points
"""
def distinguishable_colormap(bg=(0, 0, 0), exclude=None, nb_colors=None):
"""
Generate distinguishable colors for visualization.
Parameters:
bg (tuple): background color
exclude (list): colors to exclude
nb_colors (int): number of colors to generate
Returns:
array: RGB color array
"""# Basic streamline visualization
from dipy.viz import window, actor
from dipy.data import read_bundles_2_subjects
import numpy as np
# Load example streamlines
bundle1, bundle2 = read_bundles_2_subjects()
# Create scene and add streamlines
scene = window.Scene()
stream_actor = actor.line(bundle1, colors=(1, 0, 0), linewidth=2)
scene.add(stream_actor)
# Create interactive window
showm = window.ShowManager(scene, title='Streamlines', size=(800, 600))
showm.initialize()
showm.render()
showm.start()
# Volume slice visualization
from dipy.data import read_stanford_hardi
from dipy.reconst.dti import TensorModel
# Load and process data
img, gtab = read_stanford_hardi()
data = img.get_fdata()
# Compute FA
tensor_model = TensorModel(gtab)
tensor_fit = tensor_model.fit(data)
fa = tensor_fit.fa
# Create FA slicer
scene = window.Scene()
fa_actor = actor.slicer(fa, affine=img.affine)
scene.add(fa_actor)
# Add colorbar
from dipy.viz.colormap import colormap_lookup_table
lut = colormap_lookup_table(scale_range=(0, 1))
bar_actor = actor.scalar_bar(lut, title='Fractional Anisotropy')
scene.add(bar_actor)
# Display scene
showm = window.ShowManager(scene, size=(800, 600))
showm.initialize()
showm.render()
showm.start()
# ODF visualization
from dipy.reconst.csdeconv import ConstrainedSphericalDeconvModel, auto_response_ssst
from dipy.data import get_sphere
# Fit CSD model
response, ratio = auto_response_ssst(gtab, data)
csd_model = ConstrainedSphericalDeconvModel(gtab, response)
csd_fit = csd_model.fit(data)
# Get ODFs
sphere = get_sphere('symmetric724')
odfs = csd_fit.odf(sphere)
# Create ODF visualization
scene = window.Scene()
odf_actor = actor.odf_slicer(odfs, affine=img.affine, sphere=sphere,
colormap='plasma', scale=0.5)
scene.add(odf_actor)
# Record scene to image
window.record(scene, out_path='odfs.png', size=(1200, 800))
# Peak visualization
from dipy.direction import peaks_from_model
peaks = peaks_from_model(csd_model, data, sphere, npeaks=2)
scene = window.Scene()
peak_actor = actor.peak_slicer(peaks.peak_dirs, peaks.peak_values,
colors=(1, 0, 0), linewidth=2)
scene.add(peak_actor)
showm = window.ShowManager(scene)
showm.initialize()
showm.render()
showm.start()
# Tensor ellipsoid visualization
evals = tensor_fit.eigenvals
evecs = tensor_fit.eigenvecs
scene = window.Scene()
tensor_actor = actor.tensor_slicer(evals, evecs, scalar_colors=fa,
sphere=get_sphere('symmetric72'))
scene.add(tensor_actor)
showm = window.ShowManager(scene)
showm.initialize()
showm.render()
showm.start()Install with Tessl CLI
npx tessl i tessl/pypi-dipy