forked from fury-gl/fury
/
actor.py
2563 lines (2086 loc) · 84.5 KB
/
actor.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Module that provide actors to render."""
import os.path as op
import numpy as np
import vtk
from vtk.util import numpy_support
import fury.shaders as fs
from fury import layout
from fury.colormap import colormap_lookup_table, create_colormap, orient2rgb
from fury.utils import (lines_to_vtk_polydata, set_input, apply_affine,
set_polydata_vertices, set_polydata_triangles,
numpy_to_vtk_matrix, shallow_copy, rgb_to_vtk,
repeat_sources, get_actor_from_primitive)
from fury.io import load_image
import fury.primitive as fp
def slicer(data, affine=None, value_range=None, opacity=1.,
lookup_colormap=None, interpolation='linear', picking_tol=0.025):
"""Cut 3D scalar or rgb volumes into 2D images.
Parameters
----------
data : array, shape (X, Y, Z) or (X, Y, Z, 3)
A grayscale or rgb 4D volume as a numpy array. If rgb then values
expected on the range [0, 255].
affine : array, shape (4, 4)
Grid to space (usually RAS 1mm) transformation matrix. Default is None.
If None then the identity matrix is used.
value_range : None or tuple (2,)
If None then the values will be interpolated from (data.min(),
data.max()) to (0, 255). Otherwise from (value_range[0],
value_range[1]) to (0, 255).
opacity : float, optional
Opacity of 0 means completely transparent and 1 completely visible.
lookup_colormap : vtkLookupTable, optional
If None (default) then a grayscale map is created.
interpolation : string, optional
If 'linear' (default) then linear interpolation is used on the final
texture mapping. If 'nearest' then nearest neighbor interpolation is
used on the final texture mapping.
picking_tol : float, optional
The tolerance for the vtkCellPicker, specified as a fraction of
rendering window size.
Returns
-------
image_actor : ImageActor
An object that is capable of displaying different parts of the volume
as slices. The key method of this object is ``display_extent`` where
one can input grid coordinates and display the slice in space (or grid)
coordinates as calculated by the affine parameter.
"""
if value_range is None:
value_range = (data.min(), data.max())
if data.ndim != 3:
if data.ndim == 4:
if data.shape[3] != 3:
raise ValueError('Only RGB 3D arrays are currently supported.')
else:
nb_components = 3
else:
raise ValueError('Only 3D arrays are currently supported.')
else:
nb_components = 1
vol = data
im = vtk.vtkImageData()
I, J, K = vol.shape[:3]
im.SetDimensions(I, J, K)
# for now setting up for 1x1x1 but transformation comes later.
voxsz = (1., 1., 1.)
# im.SetOrigin(0,0,0)
im.SetSpacing(voxsz[2], voxsz[0], voxsz[1])
vtk_type = numpy_support.get_vtk_array_type(vol.dtype)
im.AllocateScalars(vtk_type, nb_components)
# im.AllocateScalars(vtk.VTK_UNSIGNED_CHAR, nb_components)
# copy data
# what I do below is the same as what is
# commented here but much faster
# for index in ndindex(vol.shape):
# i, j, k = index
# im.SetScalarComponentFromFloat(i, j, k, 0, vol[i, j, k])
vol = np.swapaxes(vol, 0, 2)
vol = np.ascontiguousarray(vol)
if nb_components == 1:
vol = vol.ravel()
else:
vol = np.reshape(vol, [np.prod(vol.shape[:3]), vol.shape[3]])
uchar_array = numpy_support.numpy_to_vtk(vol, deep=0)
im.GetPointData().SetScalars(uchar_array)
if affine is None:
affine = np.eye(4)
# Set the transform (identity if none given)
transform = vtk.vtkTransform()
transform_matrix = vtk.vtkMatrix4x4()
transform_matrix.DeepCopy((
affine[0][0], affine[0][1], affine[0][2], affine[0][3],
affine[1][0], affine[1][1], affine[1][2], affine[1][3],
affine[2][0], affine[2][1], affine[2][2], affine[2][3],
affine[3][0], affine[3][1], affine[3][2], affine[3][3]))
transform.SetMatrix(transform_matrix)
transform.Inverse()
# Set the reslicing
image_resliced = vtk.vtkImageReslice()
set_input(image_resliced, im)
image_resliced.SetResliceTransform(transform)
image_resliced.AutoCropOutputOn()
# Adding this will allow to support anisotropic voxels
# and also gives the opportunity to slice per voxel coordinates
RZS = affine[:3, :3]
zooms = np.sqrt(np.sum(RZS * RZS, axis=0))
image_resliced.SetOutputSpacing(*zooms)
image_resliced.SetInterpolationModeToLinear()
image_resliced.Update()
vtk_resliced_data = image_resliced.GetOutput()
ex1, ex2, ey1, ey2, ez1, ez2 = vtk_resliced_data.GetExtent()
resliced = numpy_support.vtk_to_numpy(
vtk_resliced_data.GetPointData().GetScalars())
# swap axes here
if data.ndim == 4:
if data.shape[-1] == 3:
resliced = resliced.reshape(ez2 + 1, ey2 + 1, ex2 + 1, 3)
if data.ndim == 3:
resliced = resliced.reshape(ez2 + 1, ey2 + 1, ex2 + 1)
class ImageActor(vtk.vtkImageActor):
def __init__(self):
self.picker = vtk.vtkCellPicker()
self.output = None
self.shape = None
self.outline_actor = None
def input_connection(self, output):
# outline only
outline = vtk.vtkOutlineFilter()
outline.SetInputData(vtk_resliced_data)
outline_mapper = vtk.vtkPolyDataMapper()
outline_mapper.SetInputConnection(outline.GetOutputPort())
self.outline_actor = vtk.vtkActor()
self.outline_actor.SetMapper(outline_mapper)
self.outline_actor.GetProperty().SetColor(1, 0.5, 0)
self.outline_actor.GetProperty().SetLineWidth(5)
self.outline_actor.GetProperty().SetRenderLinesAsTubes(True)
# crucial
self.GetMapper().SetInputConnection(output.GetOutputPort())
self.output = output
self.shape = (ex2 + 1, ey2 + 1, ez2 + 1)
def display_extent(self, x1, x2, y1, y2, z1, z2):
self.SetDisplayExtent(x1, x2, y1, y2, z1, z2)
self.Update()
# bounds = self.GetBounds()
# xmin, xmax, ymin, ymax, zmin, zmax = bounds
# line = np.array([[xmin, ymin, zmin]])
# self.outline_actor = actor.line()
def display(self, x=None, y=None, z=None):
if x is None and y is None and z is None:
self.display_extent(ex1, ex2, ey1, ey2, ez2//2, ez2//2)
if x is not None:
self.display_extent(x, x, ey1, ey2, ez1, ez2)
if y is not None:
self.display_extent(ex1, ex2, y, y, ez1, ez2)
if z is not None:
self.display_extent(ex1, ex2, ey1, ey2, z, z)
def resliced_array(self):
""" Returns resliced array as numpy array"""
resliced = numpy_support.vtk_to_numpy(
vtk_resliced_data.GetPointData().GetScalars())
# swap axes here
if data.ndim == 4:
if data.shape[-1] == 3:
resliced = resliced.reshape(ez2 + 1, ey2 + 1, ex2 + 1, 3)
if data.ndim == 3:
resliced = resliced.reshape(ez2 + 1, ey2 + 1, ex2 + 1)
resliced = np.swapaxes(resliced, 0, 2)
resliced = np.ascontiguousarray(resliced)
return resliced
def opacity(self, value):
self.GetProperty().SetOpacity(value)
def tolerance(self, value):
self.picker.SetTolerance(value)
def copy(self):
im_actor = ImageActor()
im_actor.input_connection(self.output)
im_actor.SetDisplayExtent(*self.GetDisplayExtent())
im_actor.opacity(self.GetOpacity())
im_actor.tolerance(self.picker.GetTolerance())
if interpolation == 'nearest':
im_actor.SetInterpolate(False)
else:
im_actor.SetInterpolate(True)
im_actor.GetMapper().BorderOn()
return im_actor
def shallow_copy(self):
# TODO rename copy to shallow_copy
self.copy()
r1, r2 = value_range
image_actor = ImageActor()
if nb_components == 1:
lut = lookup_colormap
if lookup_colormap is None:
# Create a black/white lookup table.
lut = colormap_lookup_table((r1, r2), (0, 0), (0, 0), (0, 1))
plane_colors = vtk.vtkImageMapToColors()
plane_colors.SetLookupTable(lut)
plane_colors.SetInputConnection(image_resliced.GetOutputPort())
plane_colors.Update()
image_actor.input_connection(plane_colors)
else:
image_actor.input_connection(image_resliced)
image_actor.display()
image_actor.opacity(opacity)
image_actor.tolerance(picking_tol)
if interpolation == 'nearest':
image_actor.SetInterpolate(False)
else:
image_actor.SetInterpolate(True)
image_actor.GetMapper().BorderOn()
return image_actor
def surface(vertices, faces=None, colors=None, smooth=None, subdivision=3):
"""Generates a surface actor from an array of vertices
The color and smoothness of the surface can be customized by specifying
the type of subdivision algorithm and the number of subdivisions.
Parameters
----------
vertices : array, shape (X, Y, Z)
The point cloud defining the surface.
faces : array
An array of precomputed triangulation for the point cloud.
It is an optional parameter, it is computed locally if None
colors : (N, 3) array
Specifies the colors associated with each vertex in the
vertices array.
Optional parameter, if not passed, all vertices
are colored white
smooth : string - "loop" or "butterfly"
Defines the type of subdivision to be used
for smoothing the surface
subdivision : integer, default = 3
Defines the number of subdivisions to do for
each triangulation of the point cloud.
The higher the value, smoother the surface
but at the cost of higher computation
Returns
-------
surface_actor : vtkActor
A vtkActor visualizing the final surface
computed from the point cloud is returned.
"""
from scipy.spatial import Delaunay
points = vtk.vtkPoints()
points.SetData(numpy_support.numpy_to_vtk(vertices))
triangle_poly_data = vtk.vtkPolyData()
triangle_poly_data.SetPoints(points)
if colors is not None:
triangle_poly_data.GetPointData().\
SetScalars(numpy_support.numpy_to_vtk(colors))
if faces is None:
tri = Delaunay(vertices[:, [0, 1]])
faces = np.array(tri.simplices, dtype='i8')
set_polydata_triangles(triangle_poly_data, faces)
clean_poly_data = vtk.vtkCleanPolyData()
clean_poly_data.SetInputData(triangle_poly_data)
mapper = vtk.vtkPolyDataMapper()
surface_actor = vtk.vtkActor()
if smooth is None:
mapper.SetInputData(triangle_poly_data)
surface_actor.SetMapper(mapper)
elif smooth == "loop":
smooth_loop = vtk.vtkLoopSubdivisionFilter()
smooth_loop.SetNumberOfSubdivisions(subdivision)
smooth_loop.SetInputConnection(clean_poly_data.GetOutputPort())
mapper.SetInputConnection(smooth_loop.GetOutputPort())
surface_actor.SetMapper(mapper)
elif smooth == "butterfly":
smooth_butterfly = vtk.vtkButterflySubdivisionFilter()
smooth_butterfly.SetNumberOfSubdivisions(subdivision)
smooth_butterfly.SetInputConnection(clean_poly_data.GetOutputPort())
mapper.SetInputConnection(smooth_butterfly.GetOutputPort())
surface_actor.SetMapper(mapper)
return surface_actor
def contour_from_roi(data, affine=None,
color=np.array([1, 0, 0]), opacity=1):
"""Generate surface actor from a binary ROI.
The color and opacity of the surface can be customized.
Parameters
----------
data : array, shape (X, Y, Z)
An ROI file that will be binarized and displayed.
affine : array, shape (4, 4)
Grid to space (usually RAS 1mm) transformation matrix. Default is None.
If None then the identity matrix is used.
color : (1, 3) ndarray
RGB values in [0,1].
opacity : float
Opacity of surface between 0 and 1.
Returns
-------
contour_assembly : vtkAssembly
ROI surface object displayed in space
coordinates as calculated by the affine parameter.
"""
if data.ndim != 3:
raise ValueError('Only 3D arrays are currently supported.')
nb_components = 1
data = (data > 0) * 1
vol = np.interp(data, xp=[data.min(), data.max()], fp=[0, 255])
vol = vol.astype('uint8')
im = vtk.vtkImageData()
di, dj, dk = vol.shape[:3]
im.SetDimensions(di, dj, dk)
voxsz = (1., 1., 1.)
# im.SetOrigin(0,0,0)
im.SetSpacing(voxsz[2], voxsz[0], voxsz[1])
im.AllocateScalars(vtk.VTK_UNSIGNED_CHAR, nb_components)
# copy data
vol = np.swapaxes(vol, 0, 2)
vol = np.ascontiguousarray(vol)
vol = vol.ravel()
uchar_array = numpy_support.numpy_to_vtk(vol, deep=0)
im.GetPointData().SetScalars(uchar_array)
if affine is None:
affine = np.eye(4)
# Set the transform (identity if none given)
transform = vtk.vtkTransform()
transform_matrix = vtk.vtkMatrix4x4()
transform_matrix.DeepCopy((
affine[0][0], affine[0][1], affine[0][2], affine[0][3],
affine[1][0], affine[1][1], affine[1][2], affine[1][3],
affine[2][0], affine[2][1], affine[2][2], affine[2][3],
affine[3][0], affine[3][1], affine[3][2], affine[3][3]))
transform.SetMatrix(transform_matrix)
transform.Inverse()
# Set the reslicing
image_resliced = vtk.vtkImageReslice()
set_input(image_resliced, im)
image_resliced.SetResliceTransform(transform)
image_resliced.AutoCropOutputOn()
# Adding this will allow to support anisotropic voxels
# and also gives the opportunity to slice per voxel coordinates
rzs = affine[:3, :3]
zooms = np.sqrt(np.sum(rzs * rzs, axis=0))
image_resliced.SetOutputSpacing(*zooms)
image_resliced.SetInterpolationModeToLinear()
image_resliced.Update()
skin_extractor = vtk.vtkContourFilter()
skin_extractor.SetInputData(image_resliced.GetOutput())
skin_extractor.SetValue(0, 1)
skin_normals = vtk.vtkPolyDataNormals()
skin_normals.SetInputConnection(skin_extractor.GetOutputPort())
skin_normals.SetFeatureAngle(60.0)
skin_mapper = vtk.vtkPolyDataMapper()
skin_mapper.SetInputConnection(skin_normals.GetOutputPort())
skin_mapper.ScalarVisibilityOff()
skin_actor = vtk.vtkActor()
skin_actor.SetMapper(skin_mapper)
skin_actor.GetProperty().SetColor(color[0], color[1], color[2])
skin_actor.GetProperty().SetOpacity(opacity)
return skin_actor
def contour_from_label(data, affine=None, color=None):
"""Generate surface actor from a labeled Array.
The color and opacity of individual surfaces can be customized.
Parameters
----------
data : array, shape (X, Y, Z)
A labeled array file that will be binarized and displayed.
affine : array, shape (4, 4)
Grid to space (usually RAS 1mm) transformation matrix. Default is None.
If None then the identity matrix is used.
color : (N, 3) or (N, 4) ndarray
RGB/RGBA values in [0,1]. Default is None.
If None then random colors are used.
Alpha channel is set to 1 by default.
Returns
-------
contour_assembly : vtkAssembly
Array surface object displayed in space
coordinates as calculated by the affine parameter
in the order of their roi ids.
"""
unique_roi_id = np.delete(np.unique(data), 0)
nb_surfaces = len(unique_roi_id)
unique_roi_surfaces = vtk.vtkAssembly()
if color is None:
color = np.random.rand(nb_surfaces, 3)
elif color.shape != (nb_surfaces, 3) and color.shape != (nb_surfaces, 4):
raise ValueError("Incorrect color array shape")
if color.shape == (nb_surfaces, 4):
opacity = color[:, -1]
color = color[:, :-1]
else:
opacity = np.ones((nb_surfaces, 1)).astype(np.float)
for i, roi_id in enumerate(unique_roi_id):
roi_data = np.isin(data, roi_id).astype(np.int)
roi_surface = contour_from_roi(roi_data, affine,
color=color[i],
opacity=opacity[i])
unique_roi_surfaces.AddPart(roi_surface)
return unique_roi_surfaces
def streamtube(lines, colors=None, opacity=1, linewidth=0.1, tube_sides=9,
lod=True, lod_points=10 ** 4, lod_points_size=3,
spline_subdiv=None, lookup_colormap=None):
"""Use streamtubes to visualize polylines
Parameters
----------
lines : list
list of N curves represented as 2D ndarrays
colors : array (N, 3), list of arrays, tuple (3,), array (K,)
If None or False, a standard orientation colormap is used for every
line.
If one tuple of color is used. Then all streamlines will have the same
colour.
If an array (N, 3) is given, where N is equal to the number of lines.
Then every line is coloured with a different RGB color.
If a list of RGB arrays is given then every point of every line takes
a different color.
If an array (K, 3) is given, where K is the number of points of all
lines then every point is colored with a different RGB color.
If an array (K,) is given, where K is the number of points of all
lines then these are considered as the values to be used by the
colormap.
If an array (L,) is given, where L is the number of streamlines then
these are considered as the values to be used by the colormap per
streamline.
If an array (X, Y, Z) or (X, Y, Z, 3) is given then the values for the
colormap are interpolated automatically using trilinear interpolation.
opacity : float, optional
Takes values from 0 (fully transparent) to 1 (opaque). Default is 1.
linewidth : float, optional
Default is 0.01.
tube_sides : int, optional
Default is 9.
lod : bool, optional
Use vtkLODActor(level of detail) rather than vtkActor. Default is True.
Level of detail actors do not render the full geometry when the
frame rate is low.
lod_points : int, optional
Number of points to be used when LOD is in effect. Default is 10000.
lod_points_size : int, optional
Size of points when lod is in effect. Default is 3.
spline_subdiv : int, optional
Number of splines subdivision to smooth streamtubes. Default is None.
lookup_colormap : vtkLookupTable, optional
Add a default lookup table to the colormap. Default is None which calls
:func:`fury.actor.colormap_lookup_table`.
Examples
--------
>>> import numpy as np
>>> from fury import actor, window
>>> scene = window.Scene()
>>> lines = [np.random.rand(10, 3), np.random.rand(20, 3)]
>>> colors = np.random.rand(2, 3)
>>> c = actor.streamtube(lines, colors)
>>> scene.add(c)
>>> #window.show(scene)
Notes
-----
Streamtubes can be heavy on GPU when loading many streamlines and
therefore, you may experience slow rendering time depending on system GPU.
A solution to this problem is to reduce the number of points in each
streamline. In Dipy we provide an algorithm that will reduce the number of
points on the straighter parts of the streamline but keep more points on
the curvier parts. This can be used in the following way::
from dipy.tracking.distances import approx_polygon_track
lines = [approx_polygon_track(line, 0.2) for line in lines]
Alternatively we suggest using the ``line`` actor which is much more
efficient.
See Also
--------
:func:`fury.actor.line`
"""
# Poly data with lines and colors
poly_data, color_is_scalar = lines_to_vtk_polydata(lines, colors)
next_input = poly_data
# Set Normals
poly_normals = set_input(vtk.vtkPolyDataNormals(), next_input)
poly_normals.ComputeCellNormalsOn()
poly_normals.ComputePointNormalsOn()
poly_normals.ConsistencyOn()
poly_normals.AutoOrientNormalsOn()
poly_normals.Update()
next_input = poly_normals.GetOutputPort()
# Spline interpolation
if (spline_subdiv is not None) and (spline_subdiv > 0):
spline_filter = set_input(vtk.vtkSplineFilter(), next_input)
spline_filter.SetSubdivideToSpecified()
spline_filter.SetNumberOfSubdivisions(spline_subdiv)
spline_filter.Update()
next_input = spline_filter.GetOutputPort()
# Add thickness to the resulting lines
tube_filter = set_input(vtk.vtkTubeFilter(), next_input)
tube_filter.SetNumberOfSides(tube_sides)
tube_filter.SetRadius(linewidth)
# TODO using the line above we will be able to visualize
# streamtubes of varying radius
# tube_filter.SetVaryRadiusToVaryRadiusByScalar()
tube_filter.CappingOn()
tube_filter.Update()
next_input = tube_filter.GetOutputPort()
# Poly mapper
poly_mapper = set_input(vtk.vtkPolyDataMapper(), next_input)
poly_mapper.ScalarVisibilityOn()
poly_mapper.SetScalarModeToUsePointFieldData()
poly_mapper.SelectColorArray("Colors")
poly_mapper.Update()
# Color Scale with a lookup table
if color_is_scalar:
if lookup_colormap is None:
lookup_colormap = colormap_lookup_table()
poly_mapper.SetLookupTable(lookup_colormap)
poly_mapper.UseLookupTableScalarRangeOn()
poly_mapper.Update()
# Set Actor
if lod:
actor = vtk.vtkLODActor()
actor.SetNumberOfCloudPoints(lod_points)
actor.GetProperty().SetPointSize(lod_points_size)
else:
actor = vtk.vtkActor()
actor.SetMapper(poly_mapper)
actor.GetProperty().SetInterpolationToPhong()
actor.GetProperty().BackfaceCullingOn()
actor.GetProperty().SetOpacity(opacity)
return actor
def line(lines, colors=None, opacity=1, linewidth=1,
spline_subdiv=None, lod=True, lod_points=10 ** 4, lod_points_size=3,
lookup_colormap=None, depth_cue=False, fake_tube=False):
""" Create an actor for one or more lines.
Parameters
------------
lines : list of arrays
colors : array (N, 3), list of arrays, tuple (3,), array (K,)
If None or False, a standard orientation colormap is used for every
line.
If one tuple of color is used. Then all streamlines will have the same
colour.
If an array (N, 3) is given, where N is equal to the number of lines.
Then every line is coloured with a different RGB color.
If a list of RGB arrays is given then every point of every line takes
a different color.
If an array (K, 3) is given, where K is the number of points of all
lines then every point is colored with a different RGB color.
If an array (K,) is given, where K is the number of points of all
lines then these are considered as the values to be used by the
colormap.
If an array (L,) is given, where L is the number of streamlines then
these are considered as the values to be used by the colormap per
streamline.
If an array (X, Y, Z) or (X, Y, Z, 3) is given then the values for the
colormap are interpolated automatically using trilinear interpolation.
opacity : float, optional
Takes values from 0 (fully transparent) to 1 (opaque). Default is 1.
linewidth : float, optional
Line thickness. Default is 1.
spline_subdiv : int, optional
Number of splines subdivision to smooth streamtubes. Default is None
which means no subdivision.
lod : bool, optional
Use vtkLODActor(level of detail) rather than vtkActor. Default is True.
Level of detail actors do not render the full geometry when the
frame rate is low.
lod_points : int, optional
Number of points to be used when LOD is in effect. Default is 10000.
lod_points_size : int
Size of points when lod is in effect. Default is 3.
lookup_colormap : vtkLookupTable, optional
Add a default lookup table to the colormap. Default is None which calls
:func:`fury.actor.colormap_lookup_table`.
depth_cue : boolean, optional
Add a size depth cue so that lines shrink with distance to the camera.
Works best with linewidth <= 1.
fake_tube: boolean, optional
Add shading to lines to approximate the look of tubes.
Returns
----------
v : vtkActor or vtkLODActor object
Line.
Examples
----------
>>> from fury import actor, window
>>> scene = window.Scene()
>>> lines = [np.random.rand(10, 3), np.random.rand(20, 3)]
>>> colors = np.random.rand(2, 3)
>>> c = actor.line(lines, colors)
>>> scene.add(c)
>>> #window.show(scene)
"""
# Poly data with lines and colors
poly_data, color_is_scalar = lines_to_vtk_polydata(lines, colors)
next_input = poly_data
# use spline interpolation
if (spline_subdiv is not None) and (spline_subdiv > 0):
spline_filter = set_input(vtk.vtkSplineFilter(), next_input)
spline_filter.SetSubdivideToSpecified()
spline_filter.SetNumberOfSubdivisions(spline_subdiv)
spline_filter.Update()
next_input = spline_filter.GetOutputPort()
poly_mapper = set_input(vtk.vtkPolyDataMapper(), next_input)
poly_mapper.ScalarVisibilityOn()
poly_mapper.SetScalarModeToUsePointFieldData()
poly_mapper.SelectColorArray("Colors")
poly_mapper.Update()
if depth_cue:
poly_mapper.SetGeometryShaderCode(fs.load("line.geom"))
@vtk.calldata_type(vtk.VTK_OBJECT)
def vtkShaderCallback(_caller, _event, calldata=None):
program = calldata
if program is not None:
program.SetUniformf("linewidth", linewidth)
poly_mapper.AddObserver(vtk.vtkCommand.UpdateShaderEvent,
vtkShaderCallback)
# Color Scale with a lookup table
if color_is_scalar:
if lookup_colormap is None:
lookup_colormap = colormap_lookup_table()
poly_mapper.SetLookupTable(lookup_colormap)
poly_mapper.UseLookupTableScalarRangeOn()
poly_mapper.Update()
# Set Actor
if lod:
actor = vtk.vtkLODActor()
actor.SetNumberOfCloudPoints(lod_points)
actor.GetProperty().SetPointSize(lod_points_size)
else:
actor = vtk.vtkActor()
actor.SetMapper(poly_mapper)
actor.GetProperty().SetLineWidth(linewidth)
actor.GetProperty().SetOpacity(opacity)
if fake_tube:
actor.GetProperty().SetRenderLinesAsTubes(True)
return actor
def scalar_bar(lookup_table=None, title=" "):
""" Default scalar bar actor for a given colormap (colorbar)
Parameters
----------
lookup_table : vtkLookupTable or None
If None then ``colormap_lookup_table`` is called with default options.
title : str
Returns
-------
scalar_bar : vtkScalarBarActor
See Also
--------
:func:`fury.actor.colormap_lookup_table`
"""
lookup_table_copy = vtk.vtkLookupTable()
if lookup_table is None:
lookup_table = colormap_lookup_table()
# Deepcopy the lookup_table because sometimes vtkPolyDataMapper deletes it
lookup_table_copy.DeepCopy(lookup_table)
scalar_bar = vtk.vtkScalarBarActor()
scalar_bar.SetTitle(title)
scalar_bar.SetLookupTable(lookup_table_copy)
scalar_bar.SetNumberOfLabels(6)
return scalar_bar
def axes(scale=(1, 1, 1), colorx=(1, 0, 0), colory=(0, 1, 0), colorz=(0, 0, 1),
opacity=1):
""" Create an actor with the coordinate's system axes where
red = x, green = y, blue = z.
Parameters
----------
scale : tuple (3,)
Axes size e.g. (100, 100, 100). Default is (1, 1, 1).
colorx : tuple (3,)
x-axis color. Default red (1, 0, 0).
colory : tuple (3,)
y-axis color. Default green (0, 1, 0).
colorz : tuple (3,)
z-axis color. Default blue (0, 0, 1).
opacity : float, optional
Takes values from 0 (fully transparent) to 1 (opaque). Default is 1.
Returns
-------
vtkActor
"""
centers = np.zeros((3, 3))
dirs = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
colors = np.array([colorx + (opacity,),
colory + (opacity,),
colorz + (opacity,)])
scales = np.asarray(scale)
return arrow(centers, dirs, colors, scales)
def odf_slicer(odfs, affine=None, mask=None, sphere=None, scale=2.2,
norm=True, radial_scale=True, opacity=1.,
colormap='blues', global_cm=False):
""" Slice spherical fields in native or world coordinates
Parameters
----------
odfs : ndarray
4D array of spherical functions
affine : array
4x4 transformation array from native coordinates to world coordinates
mask : ndarray
3D mask
sphere : Sphere
a sphere
scale : float
Distance between spheres.
norm : bool
Normalize `sphere_values`.
radial_scale : bool
Scale sphere points according to odf values.
opacity : float
Takes values from 0 (fully transparent) to 1 (opaque). Default is 1.
colormap : None or str
If None then white color is used. Otherwise the name of colormap is
given. Matplotlib colormaps are supported (e.g., 'inferno').
global_cm : bool
If True the colormap will be applied in all ODFs. If False
it will be applied individually at each voxel (default False).
Returns
---------
actor : vtkActor
Spheres
"""
if mask is None:
mask = np.ones(odfs.shape[:3], dtype=np.bool)
else:
mask = mask.astype(np.bool)
szx, szy, szz = odfs.shape[:3]
class OdfSlicerActor(vtk.vtkLODActor):
def __init__(self):
self.mapper = None
def display_extent(self, x1, x2, y1, y2, z1, z2):
tmp_mask = np.zeros(odfs.shape[:3], dtype=np.bool)
tmp_mask[x1:x2 + 1, y1:y2 + 1, z1:z2 + 1] = True
tmp_mask = np.bitwise_and(tmp_mask, mask)
self.mapper = _odf_slicer_mapper(odfs=odfs,
affine=affine,
mask=tmp_mask,
sphere=sphere,
scale=scale,
norm=norm,
radial_scale=radial_scale,
colormap=colormap,
global_cm=global_cm)
self.SetMapper(self.mapper)
def display(self, x=None, y=None, z=None):
if x is None and y is None and z is None:
self.display_extent(0, szx - 1, 0, szy - 1,
int(np.floor(szz/2)), int(np.floor(szz/2)))
if x is not None:
self.display_extent(x, x, 0, szy - 1, 0, szz - 1)
if y is not None:
self.display_extent(0, szx - 1, y, y, 0, szz - 1)
if z is not None:
self.display_extent(0, szx - 1, 0, szy - 1, z, z)
odf_actor = OdfSlicerActor()
odf_actor.display_extent(0, szx - 1, 0, szy - 1,
int(np.floor(szz/2)), int(np.floor(szz/2)))
odf_actor.GetProperty().SetOpacity(opacity)
return odf_actor
def _odf_slicer_mapper(odfs, affine=None, mask=None, sphere=None, scale=2.2,
norm=True, radial_scale=True, colormap='plasma',
global_cm=False):
""" Helper function for slicing spherical fields
Parameters
----------
odfs : ndarray
4D array of spherical functions
affine : array
4x4 transformation array from native coordinates to world coordinates
mask : ndarray
3D mask
sphere : Sphere
a sphere
scale : float
Distance between spheres.
norm : bool
Normalize `sphere_values`.
radial_scale : bool
Scale sphere points according to odf values.
colormap : None or str
If None then sphere vertices are used to compute orientation-based
color. Otherwise the name of colormap is given. Matplotlib colormaps
are supported (e.g., 'inferno').
global_cm : bool
If True the colormap will be applied in all ODFs. If False
it will be applied individually at each voxel (default False).
Returns
---------
mapper : vtkPolyDataMapper
Spheres mapper
"""
mask = np.ones(odfs.shape[:3]) if mask is None else mask
ijk = np.ascontiguousarray(np.array(np.nonzero(mask)).T)
if len(ijk) == 0:
return None
if affine is not None:
ijk = np.ascontiguousarray(apply_affine(affine, ijk))
faces = np.asarray(sphere.faces, dtype=int)
vertices = sphere.vertices
all_xyz = []
all_faces = []
all_ms = []
for (k, center) in enumerate(ijk):
m = odfs[tuple(center.astype(np.int))].copy()
if norm:
m /= np.abs(m).max()
if radial_scale:
xyz = vertices * m[:, None]
else:
xyz = vertices.copy()
all_xyz.append(scale * xyz + center)
all_faces.append(faces + k * xyz.shape[0])
all_ms.append(m)
all_xyz = np.ascontiguousarray(np.concatenate(all_xyz))
all_xyz_vtk = numpy_support.numpy_to_vtk(all_xyz, deep=True)
if global_cm:
all_ms = np.ascontiguousarray(
np.concatenate(all_ms), dtype='f4')
points = vtk.vtkPoints()
points.SetData(all_xyz_vtk)
all_faces = np.concatenate(all_faces)
if global_cm:
if colormap is None:
raise IOError("if global_cm=True, colormap must be defined")
else:
cols = create_colormap(all_ms.ravel(), colormap)
else:
cols = np.zeros((ijk.shape[0],) + sphere.vertices.shape,
dtype='f4')
for k in range(ijk.shape[0]):
if colormap is not None:
tmp = create_colormap(all_ms[k].ravel(), colormap)
else:
tmp = orient2rgb(sphere.vertices)
cols[k] = tmp.copy()
cols = np.ascontiguousarray(
np.reshape(cols, (cols.shape[0] * cols.shape[1],
cols.shape[2])), dtype='f4')
vtk_colors = numpy_support.numpy_to_vtk(
np.asarray(255 * cols),
deep=True,