0
# Visualization and Analysis
1
2
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.
3
4
## Capabilities
5
6
### Scene Management
7
8
Core window and scene management for 3D visualization.
9
10
```python { .api }
11
def Scene(background=(0, 0, 0), skybox=None):
12
"""
13
Create 3D visualization scene.
14
15
Parameters:
16
background (tuple): RGB background color (0-1)
17
skybox (array): skybox texture for background
18
19
Returns:
20
Scene: 3D scene object for adding actors
21
"""
22
23
def ShowManager(scene=None, title='DIPY', size=(300, 300), png_magnify=1, reset_camera=True, order_transparent=True):
24
"""
25
Create window manager for scene display.
26
27
Parameters:
28
scene (Scene): 3D scene to display
29
title (str): window title
30
size (tuple): window dimensions (width, height)
31
png_magnify (int): screenshot magnification
32
reset_camera (bool): reset camera on start
33
order_transparent (bool): depth sorting for transparency
34
35
Returns:
36
ShowManager: window manager object
37
"""
38
39
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):
40
"""
41
Record scene to image or video files.
42
43
Parameters:
44
scene (Scene): scene to record
45
cam_pos (array): camera position
46
cam_focal (array): camera focal point
47
cam_view (array): camera view up vector
48
out_path (str): output file path
49
path_numbering (bool): add frame numbers to filename
50
n_frames (int): number of frames to record
51
az_ang (float): azimuth angle for rotation
52
magnification (int): image magnification
53
size (tuple): output image size
54
reset_camera (bool): reset camera before recording
55
verbose (bool): print progress information
56
"""
57
```
58
59
### Streamline Visualization
60
61
Actors for rendering tractography streamlines with various styling options.
62
63
```python { .api }
64
def line(lines, colors=None, opacity=1, linewidth=1, spline_subdiv=None, lod=True, lod_points=10000, lod_points_size=3, lookup_colormap=None):
65
"""
66
Create streamline actor for 3D rendering.
67
68
Parameters:
69
lines (list): streamlines as list of arrays
70
colors (array/tuple): colors for streamlines
71
opacity (float): transparency (0-1)
72
linewidth (float): line thickness
73
spline_subdiv (int): spline subdivision level
74
lod (bool): use level-of-detail rendering
75
lod_points (int): points threshold for LOD
76
lod_points_size (float): point size for LOD
77
lookup_colormap (array): colormap for scalar coloring
78
79
Returns:
80
vtkActor: streamline rendering actor
81
"""
82
83
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):
84
"""
85
Create tube-based streamline actor.
86
87
Parameters:
88
lines (list): streamlines
89
colors (array): streamline colors
90
opacity (float): transparency
91
linewidth (float): tube radius
92
tube_sides (int): number of tube sides
93
lod (bool): level-of-detail rendering
94
lod_points (int): LOD threshold
95
lod_points_size (float): LOD point size
96
spline_subdiv (int): spline subdivision
97
lookup_colormap (array): scalar colormap
98
99
Returns:
100
vtkActor: tube streamline actor
101
"""
102
103
def bundle_maps(bundles, affine=None, bundle_dict=None, colors=None, offsets=None, hu_colors=None):
104
"""
105
Create bundle maps visualization.
106
107
Parameters:
108
bundles (list): list of streamline bundles
109
affine (array): voxel-to-world transformation
110
bundle_dict (dict): bundle metadata
111
colors (list): colors for each bundle
112
offsets (list): spatial offsets for bundles
113
hu_colors (list): hue-based colors
114
115
Returns:
116
vtkActor: bundle map actor
117
"""
118
```
119
120
### Volume and Slice Visualization
121
122
Actors for displaying 3D volumes and 2D slices of scalar data.
123
124
```python { .api }
125
def slicer(data, affine=None, value_range=None, opacity=1.0, lookup_colormap=None, interpolation='linear', picking_tol=0.025):
126
"""
127
Create slice-based volume visualization.
128
129
Parameters:
130
data (array): 3D scalar data
131
affine (array): voxel-to-world transformation
132
value_range (tuple): data value range for coloring
133
opacity (float): slice opacity
134
lookup_colormap (array): colormap for values
135
interpolation (str): interpolation method ('linear', 'nearest')
136
picking_tol (float): picking tolerance for interaction
137
138
Returns:
139
vtkActor: slice rendering actor
140
"""
141
142
def scalar_bar(lookup_table, title=' '):
143
"""
144
Create scalar colorbar for legends.
145
146
Parameters:
147
lookup_table: VTK lookup table for colors
148
title (str): colorbar title
149
150
Returns:
151
vtkScalarBarActor: colorbar actor
152
"""
153
154
def contour_from_roi(data, affine=None, color=(1, 0, 0), opacity=1):
155
"""
156
Create surface contour from ROI mask.
157
158
Parameters:
159
data (array): binary mask data
160
affine (array): transformation matrix
161
color (tuple): surface color RGB
162
opacity (float): surface opacity
163
164
Returns:
165
vtkActor: surface contour actor
166
"""
167
```
168
169
### Tensor and ODF Visualization
170
171
Specialized actors for diffusion tensor and orientation distribution function display.
172
173
```python { .api }
174
def tensor_slicer(evals, evecs, scalar_colors=None, sphere=None, scale=2.2, norm=True, opacity=1.0):
175
"""
176
Visualize diffusion tensors as ellipsoids.
177
178
Parameters:
179
evals (array): tensor eigenvalues
180
evecs (array): tensor eigenvectors
181
scalar_colors (array): colors based on scalar values
182
sphere (Sphere): sphere for tessellation
183
scale (float): ellipsoid scaling factor
184
norm (bool): normalize tensor shapes
185
opacity (float): transparency
186
187
Returns:
188
vtkActor: tensor ellipsoid actor
189
"""
190
191
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):
192
"""
193
Visualize orientation distribution functions.
194
195
Parameters:
196
odfs (array): ODF values on sphere
197
affine (array): transformation matrix
198
mask (array): binary mask for display
199
sphere (Sphere): sphere for ODF sampling
200
scale (float): ODF scaling
201
norm (bool): normalize ODF amplitudes
202
radial_scale (bool): scale radially
203
opacity (float): transparency
204
colormap (str): colormap name
205
global_cm (bool): use global colormap scaling
206
207
Returns:
208
vtkActor: ODF rendering actor
209
"""
210
211
def peak_slicer(peaks_dirs, peaks_values=None, mask=None, affine=None, colors=(1, 0, 0), opacity=1.0, linewidth=1, lod=False):
212
"""
213
Visualize fiber peaks as line segments.
214
215
Parameters:
216
peaks_dirs (array): peak directions
217
peaks_values (array): peak magnitudes
218
mask (array): display mask
219
affine (array): transformation matrix
220
colors (tuple/array): peak colors
221
opacity (float): line opacity
222
linewidth (float): line thickness
223
lod (bool): level-of-detail rendering
224
225
Returns:
226
vtkActor: peak line actor
227
"""
228
```
229
230
### Interactive Widgets
231
232
Interactive UI components for data exploration and parameter adjustment.
233
234
```python { .api }
235
class SlicerWidget:
236
"""Interactive slice viewer widget."""
237
def __init__(self, scene, slicer_actor, interactor=None):
238
"""Initialize slice widget with scene and actor."""
239
240
def set_slice_index(self, axis, index):
241
"""Set slice position along axis."""
242
243
class PeakSlicerWidget:
244
"""Interactive peak slice viewer."""
245
def __init__(self, peaks, affine=None, mask=None, scene=None):
246
"""Initialize peak slice widget."""
247
248
class BundleWidget:
249
"""Interactive bundle visualization widget."""
250
def __init__(self, streamlines, clusters=None, colors=None, scene=None):
251
"""Initialize bundle interaction widget."""
252
```
253
254
### Colormaps and Styling
255
256
Utilities for color mapping and visual styling of diffusion data.
257
258
```python { .api }
259
def colormap_lookup_table(scale_range=(0, 1), hue_range=(0.8, 0), saturation_range=(1, 1), value_range=(0.8, 0.8)):
260
"""
261
Create lookup table for color mapping.
262
263
Parameters:
264
scale_range (tuple): data value range
265
hue_range (tuple): HSV hue range
266
saturation_range (tuple): HSV saturation range
267
value_range (tuple): HSV value range
268
269
Returns:
270
vtkLookupTable: VTK color lookup table
271
"""
272
273
def create_colormap(v, name='plasma', auto=True):
274
"""
275
Create colormap from data values.
276
277
Parameters:
278
v (array): data values for coloring
279
name (str): colormap name
280
auto (bool): automatic range scaling
281
282
Returns:
283
array: RGB colors for data points
284
"""
285
286
def distinguishable_colormap(bg=(0, 0, 0), exclude=None, nb_colors=None):
287
"""
288
Generate distinguishable colors for visualization.
289
290
Parameters:
291
bg (tuple): background color
292
exclude (list): colors to exclude
293
nb_colors (int): number of colors to generate
294
295
Returns:
296
array: RGB color array
297
"""
298
```
299
300
### Usage Examples
301
302
```python
303
# Basic streamline visualization
304
from dipy.viz import window, actor
305
from dipy.data import read_bundles_2_subjects
306
import numpy as np
307
308
# Load example streamlines
309
bundle1, bundle2 = read_bundles_2_subjects()
310
311
# Create scene and add streamlines
312
scene = window.Scene()
313
stream_actor = actor.line(bundle1, colors=(1, 0, 0), linewidth=2)
314
scene.add(stream_actor)
315
316
# Create interactive window
317
showm = window.ShowManager(scene, title='Streamlines', size=(800, 600))
318
showm.initialize()
319
showm.render()
320
showm.start()
321
322
# Volume slice visualization
323
from dipy.data import read_stanford_hardi
324
from dipy.reconst.dti import TensorModel
325
326
# Load and process data
327
img, gtab = read_stanford_hardi()
328
data = img.get_fdata()
329
330
# Compute FA
331
tensor_model = TensorModel(gtab)
332
tensor_fit = tensor_model.fit(data)
333
fa = tensor_fit.fa
334
335
# Create FA slicer
336
scene = window.Scene()
337
fa_actor = actor.slicer(fa, affine=img.affine)
338
scene.add(fa_actor)
339
340
# Add colorbar
341
from dipy.viz.colormap import colormap_lookup_table
342
lut = colormap_lookup_table(scale_range=(0, 1))
343
bar_actor = actor.scalar_bar(lut, title='Fractional Anisotropy')
344
scene.add(bar_actor)
345
346
# Display scene
347
showm = window.ShowManager(scene, size=(800, 600))
348
showm.initialize()
349
showm.render()
350
showm.start()
351
352
# ODF visualization
353
from dipy.reconst.csdeconv import ConstrainedSphericalDeconvModel, auto_response_ssst
354
from dipy.data import get_sphere
355
356
# Fit CSD model
357
response, ratio = auto_response_ssst(gtab, data)
358
csd_model = ConstrainedSphericalDeconvModel(gtab, response)
359
csd_fit = csd_model.fit(data)
360
361
# Get ODFs
362
sphere = get_sphere('symmetric724')
363
odfs = csd_fit.odf(sphere)
364
365
# Create ODF visualization
366
scene = window.Scene()
367
odf_actor = actor.odf_slicer(odfs, affine=img.affine, sphere=sphere,
368
colormap='plasma', scale=0.5)
369
scene.add(odf_actor)
370
371
# Record scene to image
372
window.record(scene, out_path='odfs.png', size=(1200, 800))
373
374
# Peak visualization
375
from dipy.direction import peaks_from_model
376
377
peaks = peaks_from_model(csd_model, data, sphere, npeaks=2)
378
379
scene = window.Scene()
380
peak_actor = actor.peak_slicer(peaks.peak_dirs, peaks.peak_values,
381
colors=(1, 0, 0), linewidth=2)
382
scene.add(peak_actor)
383
384
showm = window.ShowManager(scene)
385
showm.initialize()
386
showm.render()
387
showm.start()
388
389
# Tensor ellipsoid visualization
390
evals = tensor_fit.eigenvals
391
evecs = tensor_fit.eigenvecs
392
393
scene = window.Scene()
394
tensor_actor = actor.tensor_slicer(evals, evecs, scalar_colors=fa,
395
sphere=get_sphere('symmetric72'))
396
scene.add(tensor_actor)
397
398
showm = window.ShowManager(scene)
399
showm.initialize()
400
showm.render()
401
showm.start()
402
```