-
Notifications
You must be signed in to change notification settings - Fork 164
/
utils.py
1441 lines (1124 loc) · 41 KB
/
utils.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
import numpy as np
from scipy.ndimage import map_coordinates
from fury.colormap import line_colors
from fury.lib import (numpy_support, PolyData, ImageData, Points,
CellArray, PolyDataNormals, Actor, PolyDataMapper,
Matrix4x4, Matrix3x3, Glyph3D, VTK_DOUBLE, VTK_FLOAT,
Transform, AlgorithmOutput, VTK_INT, VTK_UNSIGNED_CHAR,
TransformPolyDataFilter)
def remove_observer_from_actor(actor, id):
"""Remove the observer with the given id from the actor.
Parameters
----------
actor : vtkActor
id : int
id of the observer to remove
"""
if not hasattr(actor, "GetMapper"):
raise ValueError("Invalid actor")
mapper = actor.GetMapper()
if not hasattr(mapper, "RemoveObserver"):
raise ValueError("Invalid mapper")
mapper.RemoveObserver(id)
def set_input(vtk_object, inp):
"""Set Generic input function which takes into account VTK 5 or 6.
Parameters
----------
vtk_object: vtk object
inp: vtkPolyData or vtkImageData or vtkAlgorithmOutput
Returns
-------
vtk_object
Notes
-------
This can be used in the following way::
from fury.utils import set_input
poly_mapper = set_input(PolyDataMapper(), poly_data)
"""
if isinstance(inp, (PolyData, ImageData)):
vtk_object.SetInputData(inp)
elif isinstance(inp, AlgorithmOutput):
vtk_object.SetInputConnection(inp)
vtk_object.Update()
return vtk_object
def numpy_to_vtk_points(points):
"""Convert Numpy points array to a vtk points array.
Parameters
----------
points : ndarray
Returns
-------
vtk_points : vtkPoints()
"""
vtk_points = Points()
vtk_points.SetData(numpy_support.numpy_to_vtk(np.asarray(points),
deep=True))
return vtk_points
def numpy_to_vtk_colors(colors):
"""Convert Numpy color array to a vtk color array.
Parameters
----------
colors: ndarray
Returns
-------
vtk_colors : vtkDataArray
Notes
-----
If colors are not already in UNSIGNED_CHAR you may need to multiply by 255.
Examples
--------
>>> import numpy as np
>>> from fury.utils import numpy_to_vtk_colors
>>> rgb_array = np.random.rand(100, 3)
>>> vtk_colors = numpy_to_vtk_colors(255 * rgb_array)
"""
vtk_colors = numpy_support.numpy_to_vtk(np.asarray(colors), deep=True,
array_type=VTK_UNSIGNED_CHAR)
return vtk_colors
def numpy_to_vtk_cells(data, is_coords=True):
"""Convert numpy array to a vtk cell array.
Parameters
----------
data : ndarray
points coordinate or connectivity array (e.g triangles).
is_coords : ndarray
Select the type of array. default: True.
Returns
-------
vtk_cell : vtkCellArray
connectivity + offset information
"""
if isinstance(data, (list, np.ndarray)):
offsets_dtype = np.int64
else:
offsets_dtype = np.dtype(data._offsets.dtype)
if offsets_dtype.kind == 'u':
offsets_dtype = np.dtype(offsets_dtype.name[1:])
data = np.array(data, dtype=object)
nb_cells = len(data)
# Get lines_array in vtk input format
connectivity = data.flatten() if not is_coords else []
offset = [0, ]
current_position = 0
cell_array = CellArray()
for i in range(nb_cells):
current_len = len(data[i])
offset.append(offset[-1] + current_len)
if is_coords:
end_position = current_position + current_len
connectivity += list(range(current_position, end_position))
current_position = end_position
connectivity = np.array(connectivity, offsets_dtype)
offset = np.array(offset, dtype=offsets_dtype)
vtk_array_type = numpy_support.get_vtk_array_type(offsets_dtype)
cell_array.SetData(
numpy_support.numpy_to_vtk(offset, deep=True,
array_type=vtk_array_type),
numpy_support.numpy_to_vtk(connectivity, deep=True,
array_type=vtk_array_type))
cell_array.SetNumberOfCells(nb_cells)
return cell_array
def numpy_to_vtk_image_data(array, spacing=(1.0, 1.0, 1.0),
origin=(0.0, 0.0, 0.0), deep=True):
"""Convert numpy array to a vtk image data.
Parameters
----------
array : ndarray
pixel coordinate and colors values.
spacing : (float, float, float) (optional)
sets the size of voxel (unit of space in each direction x,y,z)
origin : (float, float, float) (optional)
sets the origin at the given point
deep : bool (optional)
decides the type of copy(ie. deep or shallow)
Returns
-------
vtk_image : vtkImageData
"""
if array.ndim not in [2, 3]:
raise IOError("only 2D (L, RGB, RGBA) or 3D image available")
vtk_image = ImageData()
depth = 1 if array.ndim == 2 else array.shape[2]
vtk_image.SetDimensions(array.shape[1], array.shape[0], depth)
vtk_image.SetExtent(0, array.shape[1] - 1,
0, array.shape[0] - 1,
0, 0)
vtk_image.SetSpacing(spacing)
vtk_image.SetOrigin(origin)
temp_arr = np.flipud(array)
temp_arr = temp_arr.reshape(array.shape[1] * array.shape[0], depth)
temp_arr = np.ascontiguousarray(temp_arr, dtype=array.dtype)
vtk_array_type = numpy_support.get_vtk_array_type(array.dtype)
uchar_array = numpy_support.numpy_to_vtk(temp_arr, deep=deep,
array_type=vtk_array_type)
vtk_image.GetPointData().SetScalars(uchar_array)
return vtk_image
def map_coordinates_3d_4d(input_array, indices):
"""Evaluate input_array at the given indices using trilinear interpolation.
Parameters
----------
input_array : ndarray,
3D or 4D array
indices : ndarray
Returns
-------
output : ndarray
1D or 2D array
"""
if input_array.ndim <= 2 or input_array.ndim >= 5:
raise ValueError("Input array can only be 3d or 4d")
if input_array.ndim == 3:
return map_coordinates(input_array, indices.T, order=1)
if input_array.ndim == 4:
values_4d = []
for i in range(input_array.shape[-1]):
values_tmp = map_coordinates(input_array[..., i],
indices.T, order=1)
values_4d.append(values_tmp)
return np.ascontiguousarray(np.array(values_4d).T)
def lines_to_vtk_polydata(lines, colors=None):
"""Create a vtkPolyData with lines and colors.
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.
Returns
-------
poly_data : vtkPolyData
color_is_scalar : bool, true if the color array is a single scalar
Scalar array could be used with a colormap lut
None if no color was used
"""
# Get the 3d points_array
if lines.__class__.__name__ == 'ArraySequence':
points_array = lines._data
else:
points_array = np.vstack(lines)
# Set Points to vtk array format
vtk_points = numpy_to_vtk_points(points_array)
# Set Lines to vtk array format
vtk_cell_array = numpy_to_vtk_cells(lines)
# Create the poly_data
poly_data = PolyData()
poly_data.SetPoints(vtk_points)
poly_data.SetLines(vtk_cell_array)
# Get colors_array (reformat to have colors for each points)
# - if/else tested and work in normal simple case
nb_points = len(points_array)
nb_lines = len(lines)
lines_range = range(nb_lines)
points_per_line = [len(lines[i]) for i in lines_range]
points_per_line = np.array(points_per_line, np.intp)
color_is_scalar = False
if points_array.size:
if colors is None or colors is False:
# set automatic rgb colors
cols_arr = line_colors(lines)
colors_mapper = np.repeat(lines_range, points_per_line, axis=0)
vtk_colors = numpy_to_vtk_colors(255 * cols_arr[colors_mapper])
else:
cols_arr = np.asarray(colors)
if cols_arr.dtype == object: # colors is a list of colors
vtk_colors = numpy_to_vtk_colors(255 * np.vstack(colors))
else:
if len(cols_arr) == nb_points:
if cols_arr.ndim == 1: # values for every point
vtk_colors = numpy_support.numpy_to_vtk(cols_arr,
deep=True)
color_is_scalar = True
elif cols_arr.ndim == 2: # map color to each point
vtk_colors = numpy_to_vtk_colors(255 * cols_arr)
elif cols_arr.ndim == 1:
if len(cols_arr) == nb_lines: # values for every streamline
cols_arrx = []
for (i, value) in enumerate(colors):
cols_arrx += lines[i].shape[0]*[value]
cols_arrx = np.array(cols_arrx)
vtk_colors = numpy_support.numpy_to_vtk(cols_arrx,
deep=True)
color_is_scalar = True
else: # the same colors for all points
vtk_colors = numpy_to_vtk_colors(
np.tile(255 * cols_arr, (nb_points, 1)))
elif cols_arr.ndim == 2: # map color to each line
colors_mapper = np.repeat(lines_range, points_per_line,
axis=0)
vtk_colors = numpy_to_vtk_colors(255 * cols_arr[colors_mapper])
else: # colormap
# get colors for each vertex
cols_arr = map_coordinates_3d_4d(cols_arr, points_array)
vtk_colors = numpy_support.numpy_to_vtk(cols_arr, deep=True)
color_is_scalar = True
vtk_colors.SetName("colors")
poly_data.GetPointData().SetScalars(vtk_colors)
return poly_data, color_is_scalar
def get_polydata_lines(line_polydata):
"""Convert vtk polydata to a list of lines ndarrays.
Parameters
----------
line_polydata : vtkPolyData
Returns
-------
lines : list
List of N curves represented as 2D ndarrays
"""
lines_vertices = numpy_support.vtk_to_numpy(line_polydata.GetPoints().
GetData())
lines_idx = numpy_support.vtk_to_numpy(line_polydata.GetLines().GetData())
lines = []
current_idx = 0
while current_idx < len(lines_idx):
line_len = lines_idx[current_idx]
next_idx = current_idx + line_len + 1
line_range = lines_idx[current_idx + 1: next_idx]
lines += [lines_vertices[line_range]]
current_idx = next_idx
return lines
def get_polydata_triangles(polydata):
"""Get triangles (ndarrays Nx3 int) from a vtk polydata.
Parameters
----------
polydata : vtkPolyData
Returns
-------
output : array (N, 3)
triangles
"""
vtk_polys = numpy_support.vtk_to_numpy(polydata.GetPolys().GetData())
# test if its really triangles
if not (vtk_polys[::4] == 3).all():
raise AssertionError("Shape error: this is not triangles")
return np.vstack([vtk_polys[1::4], vtk_polys[2::4], vtk_polys[3::4]]).T
def get_polydata_vertices(polydata):
"""Get vertices (ndarrays Nx3 int) from a vtk polydata.
Parameters
----------
polydata : vtkPolyData
Returns
-------
output : array (N, 3)
points, represented as 2D ndarrays
"""
return numpy_support.vtk_to_numpy(polydata.GetPoints().GetData())
def get_polydata_normals(polydata):
"""Get vertices normal (ndarrays Nx3 int) from a vtk polydata.
Parameters
----------
polydata : vtkPolyData
Returns
-------
output : array (N, 3)
Normals, represented as 2D ndarrays (Nx3). None if there are no normals
in the vtk polydata.
"""
vtk_normals = polydata.GetPointData().GetNormals()
if vtk_normals is None:
return None
return numpy_support.vtk_to_numpy(vtk_normals)
def get_polydata_tangents(polydata):
"""Get vertices tangent (ndarrays Nx3 int) from a vtk polydata.
Parameters
----------
polydata : vtkPolyData
Returns
-------
output : array (N, 3)
Tangents, represented as 2D ndarrays (Nx3). None if there are no
tangents in the vtk polydata.
"""
vtk_tangents = polydata.GetPointData().GetTangents()
if vtk_tangents is None:
return None
return numpy_support.vtk_to_numpy(vtk_tangents)
def get_polydata_colors(polydata):
"""Get points color (ndarrays Nx3 int) from a vtk polydata.
Parameters
----------
polydata : vtkPolyData
Returns
-------
output : array (N, 3)
Colors. None if no normals in the vtk polydata.
"""
vtk_colors = polydata.GetPointData().GetScalars()
if vtk_colors is None:
return None
return numpy_support.vtk_to_numpy(vtk_colors)
def get_polydata_field(polydata, field_name, as_vtk=False):
"""Get a field from a vtk polydata.
Parameters
----------
polydata : vtkPolyData
field_name : str
as_vtk : optional
By default, ndarray is returned.
Returns
-------
output : ndarray or vtkDataArray
Field data. The return type depends on the value of the as_vtk
parameter. None if the field is not found.
"""
vtk_field_data = polydata.GetFieldData().GetArray(field_name)
if vtk_field_data is None:
return None
if as_vtk:
return vtk_field_data
return numpy_support.vtk_to_numpy(vtk_field_data)
def add_polydata_numeric_field(polydata, field_name, field_data,
array_type=VTK_INT):
"""Add a field to a vtk polydata.
Parameters
----------
polydata : vtkPolyData
field_name : str
field_data : bool, int, float, double, numeric array or ndarray
array_type : vtkArrayType
"""
vtk_field_data = numpy_support.numpy_to_vtk(field_data, deep=True,
array_type=array_type)
vtk_field_data.SetName(field_name)
polydata.GetFieldData().AddArray(vtk_field_data)
return polydata
def set_polydata_triangles(polydata, triangles):
"""Set polydata triangles with a numpy array (ndarrays Nx3 int).
Parameters
----------
polydata : vtkPolyData
triangles : array (N, 3)
triangles, represented as 2D ndarrays (Nx3)
"""
vtk_cells = CellArray()
vtk_cells = numpy_to_vtk_cells(triangles, is_coords=False)
polydata.SetPolys(vtk_cells)
return polydata
def set_polydata_vertices(polydata, vertices):
"""Set polydata vertices with a numpy array (ndarrays Nx3 int).
Parameters
----------
polydata : vtkPolyData
vertices : vertices, represented as 2D ndarrays (Nx3)
"""
vtk_points = Points()
vtk_points.SetData(numpy_support.numpy_to_vtk(vertices, deep=True))
polydata.SetPoints(vtk_points)
return polydata
def set_polydata_normals(polydata, normals):
"""Set polydata normals with a numpy array (ndarrays Nx3 int).
Parameters
----------
polydata : vtkPolyData
normals : normals, represented as 2D ndarrays (Nx3) (one per vertex)
"""
vtk_normals = numpy_support.numpy_to_vtk(normals, deep=True)
# VTK does not require a specific name for the normals array, however, for
# readability purposes, we set it to "Normals"
vtk_normals.SetName('Normals')
polydata.GetPointData().SetNormals(vtk_normals)
return polydata
def set_polydata_tangents(polydata, tangents):
"""Set polydata tangents with a numpy array (ndarrays Nx3 int).
Parameters
----------
polydata : vtkPolyData
tangents : tangents, represented as 2D ndarrays (Nx3) (one per vertex)
"""
vtk_tangents = numpy_support.numpy_to_vtk(tangents, deep=True,
array_type=VTK_FLOAT)
# VTK does not require a specific name for the tangents array, however, for
# readability purposes, we set it to "Tangents"
vtk_tangents.SetName('Tangents')
polydata.GetPointData().SetTangents(vtk_tangents)
return polydata
def set_polydata_colors(polydata, colors, array_name="colors"):
"""Set polydata colors with a numpy array (ndarrays Nx3 int).
Parameters
----------
polydata : vtkPolyData
colors : colors, represented as 2D ndarrays (Nx3)
colors are uint8 [0,255] RGB for each points
"""
vtk_colors = numpy_support.numpy_to_vtk(colors, deep=True,
array_type=VTK_UNSIGNED_CHAR)
nb_components = colors.shape[1]
vtk_colors.SetNumberOfComponents(nb_components)
vtk_colors.SetName(array_name)
polydata.GetPointData().SetScalars(vtk_colors)
return polydata
def update_polydata_normals(polydata):
"""Generate and update polydata normals.
Parameters
----------
polydata : vtkPolyData
"""
normals_gen = set_input(PolyDataNormals(), polydata)
normals_gen.ComputePointNormalsOn()
normals_gen.ComputeCellNormalsOn()
normals_gen.SplittingOff()
# normals_gen.FlipNormalsOn()
# normals_gen.ConsistencyOn()
# normals_gen.AutoOrientNormalsOn()
normals_gen.Update()
vtk_normals = normals_gen.GetOutput().GetPointData().GetNormals()
polydata.GetPointData().SetNormals(vtk_normals)
def get_polymapper_from_polydata(polydata):
"""Get vtkPolyDataMapper from a vtkPolyData.
Parameters
----------
polydata : vtkPolyData
Returns
-------
poly_mapper : vtkPolyDataMapper
"""
poly_mapper = set_input(PolyDataMapper(), polydata)
poly_mapper.ScalarVisibilityOn()
poly_mapper.InterpolateScalarsBeforeMappingOn()
poly_mapper.Update()
poly_mapper.StaticOn()
return poly_mapper
def get_actor_from_polymapper(poly_mapper):
"""Get actor from a vtkPolyDataMapper.
Parameters
----------
poly_mapper : vtkPolyDataMapper
Returns
-------
actor : actor
"""
actor = Actor()
actor.SetMapper(poly_mapper)
actor.GetProperty().BackfaceCullingOn()
actor.GetProperty().SetInterpolationToPhong()
return actor
def get_actor_from_polydata(polydata):
"""Get actor from a vtkPolyData.
Parameters
----------
polydata : vtkPolyData
Returns
-------
actor : actor
"""
poly_mapper = get_polymapper_from_polydata(polydata)
return get_actor_from_polymapper(poly_mapper)
def get_actor_from_primitive(vertices, triangles, colors=None,
normals=None, backface_culling=True):
"""Get actor from a vtkPolyData.
Parameters
----------
vertices : (Mx3) ndarray
XYZ coordinates of the object
triangles: (Nx3) ndarray
Indices into vertices; forms triangular faces.
colors: (Nx3) or (Nx4) ndarray
RGB or RGBA (for opacity) R, G, B and A should be at the range [0, 1]
N is equal to the number of vertices.
normals: (Nx3) ndarray
normals, represented as 2D ndarrays (Nx3) (one per vertex)
backface_culling: bool
culling of polygons based on orientation of normal with respect to
camera. If backface culling is True, polygons facing away from camera
are not drawn. Default: True
Returns
-------
actor : actor
"""
# Create a Polydata
pd = PolyData()
set_polydata_vertices(pd, vertices)
set_polydata_triangles(pd, triangles)
if isinstance(colors, np.ndarray):
if len(colors) != len(vertices):
msg = "Vertices and Colors should have the same size."
msg += " Please, update your color array or use the function "
msg += "``fury.primitive.repeat_primitives`` to normalize your "
msg += "color array before calling this function. e.g."
raise ValueError(msg)
set_polydata_colors(pd, colors, array_name="colors")
if isinstance(normals, np.ndarray):
set_polydata_normals(pd, normals)
current_actor = get_actor_from_polydata(pd)
current_actor.GetProperty().SetBackfaceCulling(backface_culling)
return current_actor
def repeat_sources(centers, colors, active_scalars=1., directions=None,
source=None, vertices=None, faces=None, orientation=None):
"""Transform a vtksource to glyph."""
if source is None and faces is None:
raise IOError("A source or faces should be defined")
if np.array(colors).ndim == 1:
colors = np.tile(colors, (len(centers), 1))
pts = numpy_to_vtk_points(np.ascontiguousarray(centers))
cols = numpy_to_vtk_colors(255 * np.ascontiguousarray(colors))
cols.SetName('colors')
if isinstance(active_scalars, (float, int)):
active_scalars = np.tile(active_scalars, (len(centers), 1))
if isinstance(active_scalars, np.ndarray):
ascalars = numpy_support.numpy_to_vtk(np.asarray(active_scalars),
deep=True,
array_type=VTK_DOUBLE)
ascalars.SetName('active_scalars')
if directions is not None:
directions_fa = numpy_support.numpy_to_vtk(np.asarray(directions),
deep=True,
array_type=VTK_DOUBLE)
directions_fa.SetName('directions')
polydata_centers = PolyData()
polydata_geom = PolyData()
if faces is not None:
set_polydata_vertices(polydata_geom, vertices)
set_polydata_triangles(polydata_geom, faces)
polydata_centers.SetPoints(pts)
polydata_centers.GetPointData().AddArray(cols)
if directions is not None:
polydata_centers.GetPointData().AddArray(directions_fa)
polydata_centers.GetPointData().SetActiveVectors('directions')
if isinstance(active_scalars, np.ndarray):
polydata_centers.GetPointData().AddArray(ascalars)
polydata_centers.GetPointData().SetActiveScalars('active_scalars')
glyph = Glyph3D()
if faces is None:
if orientation is not None:
transform = Transform()
transform.SetMatrix(numpy_to_vtk_matrix(orientation))
rtrans = TransformPolyDataFilter()
rtrans.SetInputConnection(source.GetOutputPort())
rtrans.SetTransform(transform)
source = rtrans
glyph.SetSourceConnection(source.GetOutputPort())
else:
glyph.SetSourceData(polydata_geom)
glyph.SetInputData(polydata_centers)
glyph.SetOrient(True)
glyph.SetScaleModeToScaleByScalar()
glyph.SetVectorModeToUseVector()
glyph.Update()
mapper = PolyDataMapper()
mapper.SetInputData(glyph.GetOutput())
mapper.SetScalarModeToUsePointFieldData()
mapper.SelectColorArray('colors')
actor = Actor()
actor.SetMapper(mapper)
return actor
def apply_affine_to_actor(act, affine):
"""Apply affine matrix `affine` to the actor `act`.
Parameters
----------
act: Actor
affine: (4, 4) array-like
Homogenous affine, for 3D object.
Returns
-------
transformed_act: Actor
"""
act.SetUserMatrix(numpy_to_vtk_matrix(affine))
return act
def apply_affine(aff, pts):
"""Apply affine matrix `aff` to points `pts`.
Returns result of application of `aff` to the *right* of `pts`. The
coordinate dimension of `pts` should be the last.
For the 3D case, `aff` will be shape (4,4) and `pts` will have final axis
length 3 - maybe it will just be N by 3. The return value is the
transformed points, in this case::
res = np.dot(aff[:3,:3], pts.T) + aff[:3,3:4]
transformed_pts = res.T
This routine is more general than 3D, in that `aff` can have any shape
(N,N), and `pts` can have any shape, as long as the last dimension is for
the coordinates, and is therefore length N-1.
Parameters
----------
aff : (N, N) array-like
Homogenous affine, for 3D points, will be 4 by 4. Contrary to first
appearance, the affine will be applied on the left of `pts`.
pts : (..., N-1) array-like
Points, where the last dimension contains the coordinates of each
point. For 3D, the last dimension will be length 3.
Returns
-------
transformed_pts : (..., N-1) array
transformed points
Notes
-----
Copied from nibabel to remove dependency.
Examples
--------
>>> aff = np.array([[0,2,0,10],[3,0,0,11],[0,0,4,12],[0,0,0,1]])
>>> pts = np.array([[1,2,3],[2,3,4],[4,5,6],[6,7,8]])
>>> apply_affine(aff, pts) #doctest: +ELLIPSIS
array([[14, 14, 24],
[16, 17, 28],
[20, 23, 36],
[24, 29, 44]]...)
Just to show that in the simple 3D case, it is equivalent to:
>>> (np.dot(aff[:3,:3], pts.T) + aff[:3,3:4]).T #doctest: +ELLIPSIS
array([[14, 14, 24],
[16, 17, 28],
[20, 23, 36],
[24, 29, 44]]...)
But `pts` can be a more complicated shape:
>>> pts = pts.reshape((2,2,3))
>>> apply_affine(aff, pts) #doctest: +ELLIPSIS
array([[[14, 14, 24],
[16, 17, 28]],
<BLANKLINE>
[[20, 23, 36],
[24, 29, 44]]]...)
"""
aff = np.asarray(aff)
pts = np.asarray(pts)
shape = pts.shape
pts = pts.reshape((-1, shape[-1]))
# rzs == rotations, zooms, shears
rzs = aff[:-1, :-1]
trans = aff[:-1, -1]
res = np.dot(pts, rzs.T) + trans[None, :]
return res.reshape(shape)
def asbytes(s):
if isinstance(s, bytes):
return s
return s.encode('latin1')
def vtk_matrix_to_numpy(matrix):
"""Convert VTK matrix to numpy array."""
if matrix is None:
return None
size = (4, 4)
if isinstance(matrix, Matrix3x3):
size = (3, 3)
mat = np.zeros(size)
for i in range(mat.shape[0]):
for j in range(mat.shape[1]):
mat[i, j] = matrix.GetElement(i, j)
return mat
def numpy_to_vtk_matrix(array):
"""Convert a numpy array to a VTK matrix."""
if array is None:
return None
if array.shape == (4, 4):
matrix = Matrix4x4()
elif array.shape == (3, 3):
matrix = Matrix3x3()
else:
raise ValueError("Invalid matrix shape: {0}".format(array.shape))
for i in range(array.shape[0]):
for j in range(array.shape[1]):
matrix.SetElement(i, j, array[i, j])
return matrix
def get_bounding_box_sizes(actor):
"""Get the bounding box sizes of an actor."""
X1, X2, Y1, Y2, Z1, Z2 = actor.GetBounds()
return (X2-X1, Y2-Y1, Z2-Z1)
def get_grid_cells_position(shapes, aspect_ratio=16/9., dim=None):
"""Construct a XY-grid based on the cells content shape.
This function generates the coordinates of every grid cell. The width and
height of every cell correspond to the largest width and the largest height
respectively. The grid dimensions will automatically be adjusted to respect
the given aspect ratio unless they are explicitly specified.
The grid follows a row-major order with the top left corner being at
coordinates (0,0,0) and the bottom right corner being at coordinates
(nb_cols*cell_width, -nb_rows*cell_height, 0). Note that the X increases
while the Y decreases.
Parameters
----------
shapes : list of tuple of int
The shape (width, height) of every cell content.
aspect_ratio : float (optional)
Aspect ratio of the grid (width/height). Default: 16:9.
dim : tuple of int (optional)
Dimension (nb_rows, nb_cols) of the grid, if provided.
Returns
-------
ndarray
3D coordinates of every grid cell.
"""
cell_shape = np.r_[np.max(shapes, axis=0), 0]
cell_aspect_ratio = cell_shape[0] / cell_shape[1]
count = len(shapes)
if dim is None:
# Compute the number of rows and columns.
n_cols = np.ceil(np.sqrt(count*aspect_ratio / cell_aspect_ratio))
n_rows = np.ceil(count / n_cols)
else:
n_rows, n_cols = dim
if n_cols * n_rows < count:
msg = "Size is too small, it cannot contain at least {} elements."
raise ValueError(msg.format(count))
# Use indexing="xy" so the cells are in row-major (C-order). Also,
# the Y coordinates are negative so the cells are order from top to bottom.
X, Y, Z = np.meshgrid(np.arange(n_cols), -np.arange(n_rows),
[0], indexing="xy")
return cell_shape * np.array([X.flatten(), Y.flatten(), Z.flatten()]).T
def shallow_copy(vtk_object):
"""Create a shallow copy of a given `vtkObject` object."""
copy = vtk_object.NewInstance()
copy.ShallowCopy(vtk_object)
return copy
def rotate(actor, rotation=(90, 1, 0, 0)):
"""Rotate actor around axis by angle.
Parameters
----------
actor : actor or other prop
rotation : tuple
Rotate with angle w around axis x, y, z. Needs to be provided
in the form (w, x, y, z).
"""
prop3D = actor
center = np.array(prop3D.GetCenter())
oldMatrix = prop3D.GetMatrix()
orig = np.array(prop3D.GetOrigin())
newTransform = Transform()
newTransform.PostMultiply()