-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbasefunctions.py
1418 lines (1166 loc) · 44.5 KB
/
basefunctions.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
# from __future__ import division
import sys
import math
import vtk
import numpy as np
from colormaps import *
from vtk.util.numpy_support import numpy_to_vtk, vtk_to_numpy
from vmtk import vmtkscripts
#------------------------------------------------------------------------------
# Linear algebra
#------------------------------------------------------------------------------
def angle(v1, v2):
return math.acos(dot(v1, v2) / (normvector(v1) * normvector(v2)))
def acumvectors(point1, point2):
return [point1[0] + point2[0],
point1[1] + point2[1],
point1[2] + point2[2]]
def subtractvectors(point1, point2):
return [point1[0] - point2[0],
point1[1] - point2[1],
point1[2] - point2[2]]
def dividevector(point, n):
nr = float(n)
return [point[0]/nr, point[1]/nr, point[2]/nr]
def multiplyvector(point, n):
nr = float(n)
return [nr*point[0], nr*point[1], nr*point[2]]
def sumvectors(vect1, scalar, vect2):
return [vect1[0] + scalar*vect2[0],
vect1[1] + scalar*vect2[1],
vect1[2] + scalar*vect2[2]]
def cross(v1, v2):
return [v1[1]*v2[2] - v1[2]*v2[1],
v1[2]*v2[0] - v1[0]*v2[2],
v1[0]*v2[1] - v1[1]*v2[0]]
def dot(v1, v2):
return sum((a*b) for a, b in zip(v1, v2))
def euclideandistance(point1, point2):
return math.sqrt((point1[0] - point2[0])**2 +
(point1[1] - point2[1])**2 +
(point1[2] - point2[2])**2)
def normvector(v):
return math.sqrt(dot(v, v))
def normalizevector(v):
norm = normvector(v)
return [v[0] / norm,
v[1] / norm,
v[2] / norm]
def polar2cart(r, theta, center):
theta_r = np.deg2rad(theta)
x = r * np.cos(theta_r) + center[0]
y = r * np.sin(theta_r) + center[1]
return x, y
#------------------------------------------------------------------------------
# VTK
#------------------------------------------------------------------------------
def compute_nonzeromean(polydata,inarrayname,pointdata=True):
if polydata.GetNumberOfPoints() > 0 :
if pointdata:
array = vtk_to_numpy(polydata.GetPointData().GetArray(inarrayname))
else:
array = vtk_to_numpy(polydata.GetCellData().GetArray(inarrayname))
array_masked = np.ma.array( array, mask = (array <= 0) )
array_nonan = array_masked[~np.isnan(array_masked)]
return array_nonan.mean()
else:
return 0.
def transfer_labels(surface,ref,arrayname,value):
# initiate point locator
locator = vtk.vtkPointLocator()
locator.SetDataSet(surface)
locator.BuildLocator()
# get array from surface
array = surface.GetPointData().GetArray(arrayname)
# go through each point of ref surface, determine closest point on surface,
for i in range(ref.GetNumberOfPoints()):
point = ref.GetPoint(i)
closestpoint_id = locator.FindClosestPoint(point)
array.SetValue(closestpoint_id, value)
surface.GetPoints().Modified()
return surface
def generatecover(edges, cover, arrayname=''):
"""Create caps for capping a surface with holes."""
# create the building blocks of polydata.
polys = vtk.vtkCellArray()
points = vtk.vtkPoints()
surfilt = vtk.vtkCleanPolyData()
surfilt.SetInputData( edges )
surfilt.Update()
points.DeepCopy(surfilt.GetOutput().GetPoints())
npoints = points.GetNumberOfPoints()
if arrayname:
# keep pre existing array
array = surfilt.GetOutput().GetPointData().GetArray(arrayname)
arraynp = vtk_to_numpy(array)
array.InsertNextValue(np.mean(arraynp))
# add centroid
centr = np.zeros(3)
for i in range( npoints ):
pt = np.zeros(3)
points.GetPoint(i,pt)
centr = centr + pt
centr = centr / npoints
cntpt = points.InsertNextPoint(centr)
# add cells
for i in range(surfilt.GetOutput().GetNumberOfCells()):
cell = surfilt.GetOutput().GetCell(i)
polys.InsertNextCell(3)
polys.InsertCellPoint(cell.GetPointId(0))
polys.InsertCellPoint(cell.GetPointId(1))
polys.InsertCellPoint(cntpt)
# assign the pieces to the polydata
cover.SetPoints(points)
cover.SetPolys(polys)
if arrayname:
cover.GetPointData().AddArray(array)
def pointset_centreofmass(polydata):
centre = [0, 0, 0]
for i in range(polydata.GetNumberOfPoints()):
point = [polydata.GetPoints().GetPoint(i)[0],
polydata.GetPoints().GetPoint(i)[1],
polydata.GetPoints().GetPoint(i)[2]]
centre = acumvectors(centre,point)
return dividevector(centre, polydata.GetNumberOfPoints())
def pointset_normal(polydata):
# estimate the normal for a given set of points which are supposedly in a plane
com = pointset_centreofmass(polydata)
normal = [0, 0, 0]
n = 0
for i in range(polydata.GetNumberOfPoints()):
point = [polydata.GetPoints().GetPoint(i)[0],
polydata.GetPoints().GetPoint(i)[1],
polydata.GetPoints().GetPoint(i)[2]]
if n==0:
vect = subtractvectors(point, com)
else:
vect2 = subtractvectors(point, com)
crossprod = cross(vect, vect2)
crossprod = normalizevector(crossprod)
# make sure each normal is oriented coherently ...
if n==1:
normal2 = crossprod
else:
if dot(crossprod,normal2) < 0:
crossprod = [-crossprod[0],-crossprod[1],-crossprod[2]]
normal = acumvectors(normal, crossprod)
n += 1
return normalizevector(normal)
def delaunay2D(polydata):
delny = vtk.vtkDelaunay2D()
delny.SetInputData(polydata)
delny.SetTolerance(0.1)
delny.SetAlpha(0.0)
delny.BoundingTriangulationOff()
delny.SetProjectionPlaneMode(vtk.VTK_BEST_FITTING_PLANE)
delny.Update()
return delny.GetOutput()
def smooth(polydata,iterations,factor):
smoother = vtk.vtkSmoothPolyDataFilter()
smoother.SetInputData(polydata)
smoother.SetNumberOfIterations(iterations)
smoother.FeatureEdgeSmoothingOn()
smoother.SetRelaxationFactor(factor)
smoother.Update()
return smoother.GetOutput()
def add_cell_array(polydata,name,value):
# create array and add a label
array = vtk.vtkDoubleArray()
array.SetName(name)
array.SetNumberOfTuples(polydata.GetNumberOfCells())
for i in range(polydata.GetNumberOfCells()):
array.SetValue(i,value)
polydata.GetCellData().AddArray(array)
return polydata
def add_point_array(polydata,name,value):
# create array and add a label
array = vtk.vtkDoubleArray()
array.SetName(name)
array.SetNumberOfTuples(polydata.GetNumberOfPoints())
for i in range(polydata.GetNumberOfPoints()):
array.SetValue(i,value)
polydata.GetPointData().AddArray(array)
return polydata
def append(polydata1,polydata2):
appender = vtk.vtkAppendPolyData()
appender.AddInputData(polydata1)
appender.AddInputData(polydata2)
appender.Update()
return appender.GetOutput()
def cellthreshold(polydata, arrayname, start=0, end=1):
threshold = vtk.vtkThreshold()
threshold.SetInputData(polydata)
threshold.SetInputArrayToProcess(0,0,0,vtk.vtkDataObject.FIELD_ASSOCIATION_CELLS,arrayname)
threshold.ThresholdBetween(start,end)
threshold.Update()
surfer = vtk.vtkDataSetSurfaceFilter()
surfer.SetInputConnection(threshold.GetOutputPort())
surfer.Update()
return surfer.GetOutput()
def centroidofcentroids(edges):
# compute centroids of each edge
# find average point
acumvector = [0,0,0]
rn = countregions(edges)
for r in range(rn):
oneedge = extractconnectedregion(edges,r)
onecentroid = pointset_centreofmass(oneedge)
acumvector = acumvectors(acumvector,onecentroid)
finalcentroid = dividevector(acumvector,rn)
return finalcentroid
def cleanpolydata(polydata):
cleaner = vtk.vtkCleanPolyData()
cleaner.SetInputData(polydata)
cleaner.Update()
return cleaner.GetOutput()
def computelengthalongvector(polydata,refpoint,vector):
# polydata should be a closed surface
# intersect with line
point1 = refpoint
point2 = sumvectors(refpoint,1000,vector) # far away point
intersectpoints = intersectwithline(polydata,point1,point2)
furthestpoint1 = furthest_point_to_polydata(intersectpoints,refpoint)
# intersect with line the other way
point1 = refpoint
point2 = sumvectors(refpoint,-1000,vector) # far away point
intersectpoints = intersectwithline(polydata,point1,point2)
furthestpoint2 = furthest_point_to_polydata(intersectpoints,furthestpoint1)
length = euclideandistance(furthestpoint1,furthestpoint2)
return length
def countregions(polydata):
# NOTE: preventive measures: clean before connectivity filter
# to avoid artificial regionIds
# It slices the surface down the middle
surfer = vtk.vtkDataSetSurfaceFilter()
surfer.SetInputData(polydata)
surfer.Update()
cleaner = vtk.vtkCleanPolyData()
cleaner.SetInputConnection(surfer.GetOutputPort())
cleaner.Update()
connect = vtk.vtkPolyDataConnectivityFilter()
connect.SetInputConnection(cleaner.GetOutputPort())
connect.Update()
return connect.GetNumberOfExtractedRegions()
def cutdataset(dataset, point, normal):
cutplane = vtk.vtkPlane()
cutplane.SetOrigin(point)
cutplane.SetNormal(normal)
cutter = vtk.vtkCutter()
cutter.SetInputData(dataset)
cutter.SetCutFunction(cutplane)
cutter.Update()
return cutter.GetOutput()
def cylinderclip(dataset, point0, point1,normal,radius):
"""Define cylinder. The cylinder is infinite in extent. We therefore have
to truncate the cylinder using vtkImplicitBoolean in combination with
2 clipping planes located at point0 and point1. The radius of the
cylinder is set to be slightly larger than 'maxradius'."""
rotationaxis = cross([0, 1, 0], normal)
rotationangle = (180 / math.pi) * angle([0, 1, 0], normal)
transform = vtk.vtkTransform()
transform.Translate(point0)
transform.RotateWXYZ(rotationangle, rotationaxis)
transform.Inverse()
cylinder = vtk.vtkCylinder()
cylinder.SetRadius(radius)
cylinder.SetTransform(transform)
plane0 = vtk.vtkPlane()
plane0.SetOrigin(point0)
plane0.SetNormal([-x for x in normal])
plane1 = vtk.vtkPlane()
plane1.SetOrigin(point1)
plane1.SetNormal(normal)
clipfunction = vtk.vtkImplicitBoolean()
clipfunction.SetOperationTypeToIntersection()
clipfunction.AddFunction(cylinder)
clipfunction.AddFunction(plane0)
clipfunction.AddFunction(plane1)
clipper = vtk.vtkClipPolyData()
clipper.SetInputData(dataset)
clipper.SetClipFunction(clipfunction)
clipper.Update()
return extractlargestregion(clipper.GetOutput())
def furthest_point_to_polydata(pointset,refpoint):
# visist each point in pointset
# selecte point furthest from reference point
refdist = 0
for i in range(pointset.GetNumberOfPoints()):
dist = euclideandistance(pointset.GetPoint(i),refpoint)
if dist > refdist:
refdist = dist
selectedpointid = i
return pointset.GetPoint(selectedpointid)
def transfer_array_by_pointid(ref,target,arrayname,targetarrayname):
# get array from reference
refarray = ref.GetPointData().GetArray(arrayname)
# create new array
numberofpoints = target.GetNumberOfPoints()
newarray = vtk.vtkDoubleArray()
newarray.SetName(targetarrayname)
newarray.SetNumberOfTuples(numberofpoints)
# go through each point of target surface,
for i in range(target.GetNumberOfPoints()):
value = refarray.GetValue(i)
newarray.SetValue(i, value)
target.GetPointData().AddArray(newarray)
return target
def extractboundaryedge(polydata):
edge = vtk.vtkFeatureEdges()
edge.SetInputData(polydata)
edge.FeatureEdgesOff()
edge.NonManifoldEdgesOff()
edge.Update()
return edge.GetOutput()
def extractcells(polydata, idlist):
"""Extract cells from polydata whose cellid is in idlist."""
cellids = vtk.vtkIdList() # specify cellids
cellids.Initialize()
for i in idlist:
cellids.InsertNextId(i)
extract = vtk.vtkExtractCells() # extract cells with specified cellids
extract.SetInputData(polydata)
extract.AddCellList(cellids)
geometry = vtk.vtkGeometryFilter() # unstructured grid to polydata
geometry.SetInputConnection(extract.GetOutputPort())
geometry.Update()
return geometry.GetOutput()
def skippoints(polydata,nskippoints):
"""Generate a single cell line from points in idlist."""
# derive number of nodes
numberofnodes = polydata.GetNumberOfPoints() - nskippoints
# define points and line
points = vtk.vtkPoints()
polyline = vtk.vtkPolyLine()
polyline.GetPointIds().SetNumberOfIds(numberofnodes)
# assign id and x,y,z coordinates
for i in range(nskippoints,polydata.GetNumberOfPoints()):
pointid = i - nskippoints
polyline.GetPointIds().SetId(pointid,pointid)
point = polydata.GetPoint(i)
points.InsertNextPoint(point)
# define cell
cells = vtk.vtkCellArray()
cells.InsertNextCell(polyline)
# add to polydata
polyout = vtk.vtkPolyData()
polyout.SetPoints(points)
polyout.SetLines(cells)
return polyout
def extractclosestpointregion(polydata, point=[0, 0, 0]):
# NOTE: preventive measures: clean before connectivity filter
# to avoid artificial regionIds
# It slices the surface down the middle
surfer = vtk.vtkDataSetSurfaceFilter()
surfer.SetInputData(polydata)
surfer.Update()
cleaner = vtk.vtkCleanPolyData()
cleaner.SetInputConnection(surfer.GetOutputPort())
cleaner.Update()
connect = vtk.vtkPolyDataConnectivityFilter()
connect.SetInputConnection(cleaner.GetOutputPort())
connect.SetExtractionModeToClosestPointRegion()
connect.SetClosestPoint(point)
connect.Update()
return connect.GetOutput()
def extractconnectedregion(polydata, regionid):
# NOTE: preventive measures: clean before connectivity filter
# to avoid artificial regionIds
# It slices the surface down the middle
surfer = vtk.vtkDataSetSurfaceFilter()
surfer.SetInputData(polydata)
surfer.Update()
cleaner = vtk.vtkCleanPolyData()
cleaner.SetInputConnection(surfer.GetOutputPort())
cleaner.Update()
connect = vtk.vtkPolyDataConnectivityFilter()
connect.SetInputConnection(cleaner.GetOutputPort())
connect.SetExtractionModeToAllRegions()
connect.ColorRegionsOn()
connect.Update()
surface = pointthreshold(connect.GetOutput(),'RegionId',float(regionid),float(regionid))
return surface
def extractlargestregion(polydata):
# NOTE: preventive measures: clean before connectivity filter
# to avoid artificial regionIds
# It slices the surface down the middle
surfer = vtk.vtkDataSetSurfaceFilter()
surfer.SetInputData(polydata)
surfer.Update()
cleaner = vtk.vtkCleanPolyData()
cleaner.SetInputConnection(surfer.GetOutputPort())
cleaner.Update()
connect = vtk.vtkPolyDataConnectivityFilter()
connect.SetInputConnection(cleaner.GetOutputPort())
connect.SetExtractionModeToLargestRegion()
connect.Update()
# leaves phantom points ....
cleaner = vtk.vtkCleanPolyData()
cleaner.SetInputConnection(connect.GetOutputPort())
cleaner.Update()
return cleaner.GetOutput()
def extractsurface(polydata):
surfer = vtk.vtkDataSetSurfaceFilter()
surfer.SetInputData(polydata)
surfer.Update()
return surfer.GetOutput()
def fillholes(polydata,size):
filler = vtk.vtkFillHolesFilter()
filler.SetInputData(polydata)
filler.SetHoleSize(size)
filler.Update()
return filler.GetOutput()
def getregionslabels():
"""Return dictionary linking regionids to anatomical locations."""
regionslabels = {'body': 36,
'laa': 37,
'pv2': 76,
'pv1': 77,
'pv3': 78,
'pv4': 79}
return regionslabels
def getflatregionslabels():
"""Return dictionary linking SUM regionids to anatomical locations."""
regionslabels = {'ant': 1,
'lat': 2,
'lattop': 2,
'laa_around': 3,
'laa_bridge_left': 3,
'laa_bridge_right': 3,
'roof': 4,
'roof_addon': 4,
'post': 5,
'isthmus': 6,
'floor': 7,
'floor_addon': 7,
'septum': 8,
'lpv_sup_q1': 9,
'lpv_sup_q2': 10,
'lpv_sup_q3': 11,
'lpv_sup_q4': 12,
'lpv_inf_q1': 13,
'lpv_inf_q2': 14,
'lpv_inf_q3': 15,
'lpv_inf_q4': 16,
'rpv_sup_q1': 17,
'rpv_sup_q2': 18,
'rpv_sup_q3': 19,
'rpv_sup_q4': 20,
'rpv_inf_q1': 21,
'rpv_inf_q2': 22,
'rpv_inf_q3': 23,
'rpv_inf_q4': 24}
return regionslabels
def generateglyph(polyIn,scalefactor=2):
vertexGlyphFilter = vtk.vtkGlyph3D()
sphereSource = vtk.vtkSphereSource()
vertexGlyphFilter.SetSourceData(sphereSource.GetOutput())
vertexGlyphFilter.SetInputData(polyIn)
vertexGlyphFilter.SetColorModeToColorByScalar()
vertexGlyphFilter.SetSourceConnection(sphereSource.GetOutputPort())
vertexGlyphFilter.ScalingOn()
vertexGlyphFilter.SetScaleFactor(scalefactor)
vertexGlyphFilter.Update()
return vertexGlyphFilter.GetOutput()
def intersectwithline(surface,p1,p2):
# Create the locator
tree = vtk.vtkOBBTree()
tree.SetDataSet(surface)
tree.BuildLocator()
intersectPoints = vtk.vtkPoints()
intersectCells = vtk.vtkIdList()
tolerance=1.e-3
tree.SetTolerance(tolerance)
tree.IntersectWithLine(p1,p2,intersectPoints,intersectCells)
return intersectPoints
def linesource(p1,p2):
source = vtk.vtkLineSource()
source.SetPoint1(p1[0],p1[1],p1[2])
source.SetPoint2(p2[0],p2[1],p2[2])
return source.GetOutput()
def planeclip(surface, point, normal, insideout=1):
clipplane = vtk.vtkPlane()
clipplane.SetOrigin(point)
clipplane.SetNormal(normal)
clipper = vtk.vtkClipPolyData()
clipper.SetInputData(surface)
clipper.SetClipFunction(clipplane)
if insideout == 1:
clipper.InsideOutOn()
else:
clipper.InsideOutOff()
clipper.Update()
return clipper.GetOutput()
def point2vertexglyph(point):
points = vtk.vtkPoints()
points.InsertNextPoint(point[0],point[1],point[2])
poly = vtk.vtkPolyData()
poly.SetPoints(points)
glyph = vtk.vtkVertexGlyphFilter()
glyph.SetInputData(poly)
glyph.Update()
return glyph.GetOutput()
def pointthreshold(polydata, arrayname, start=0, end=1,alloff=0):
threshold = vtk.vtkThreshold()
threshold.SetInputData(polydata)
threshold.SetInputArrayToProcess(0,0,0,vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS,arrayname)
threshold.ThresholdBetween(start,end)
if (alloff):
threshold.AllScalarsOff()
threshold.Update()
surfer = vtk.vtkDataSetSurfaceFilter()
surfer.SetInputConnection(threshold.GetOutputPort())
surfer.Update()
return surfer.GetOutput()
def scalepolydata(polydata, scalefactor, inorigin=False):
surfacecenter = polydata.GetCenter()
toorigin = [0,0,0]
toorigin[0] = -1*surfacecenter[0]
toorigin[1] = -1*surfacecenter[1]
toorigin[2] = -1*surfacecenter[2]
# bring to origin + rotate + bring back
transform = vtk.vtkTransform()
transform.PostMultiply()
transform.Translate(toorigin)
transform.Scale(scalefactor,scalefactor,scalefactor)
if not inorigin:
transform.Translate(surfacecenter)
transformfilter = vtk.vtkTransformFilter()
transformfilter.SetTransform(transform)
transformfilter.SetInputData(polydata)
transformfilter.Update()
return transformfilter.GetOutput()
def surfacearea(polydata):
properties = vtk.vtkMassProperties()
properties.SetInputData(polydata)
properties.Update()
return properties.GetSurfaceArea()
def triangulate(polydata):
trianglefilter = vtk.vtkTriangleFilter()
trianglefilter.SetInputData(polydata)
trianglefilter.Update()
return trianglefilter.GetOutput()
def transform_lmk(sourcepoints,targetpoints,surface,similarityon=False):
lmktransform = vtk.vtkLandmarkTransform()
lmktransform.SetSourceLandmarks(sourcepoints)
lmktransform.SetTargetLandmarks(targetpoints)
if similarityon:
lmktransform.SetModeToSimilarity()
else:
lmktransform.SetModeToAffine()
lmktransform.Update()
transformfilter = vtk.vtkTransformPolyDataFilter()
transformfilter.SetInputData(surface)
transformfilter.SetTransform(lmktransform)
transformfilter.Update()
return transformfilter.GetOutput()
def round_labels_array(surface,arrayname,labels):
"""Any value that is not part of the labels is rounded to minvalue."""
# threshold range step = 1
minval = min(labels)
maxval = max(labels)
dif = np.zeros(len(labels))
for val in range(minval,maxval+1):
mindif = 10000
closestlabel = 0
patch = pointthreshold(surface,arrayname,val-0.5,val+0.5,1) # all off
if patch.GetNumberOfPoints()>0:
for l in range(0,len(labels)):
dif[l] = val - labels[l]
mindif = min(abs(dif))
if (mindif > 0.01):
# found points to round
transfer_labels(surface,patch,arrayname,minval)
return surface
def visualise_default(surface,ref,case,arrayname,mini,maxi):
"""Visualise surface with a default parameters."""
#Create a lookup table to map cell data to colors
lut = vtk.vtkLookupTable()
lut.SetNumberOfTableValues(255)
lut.SetValueRange(0, 255)
# qualitative data from colorbrewer --> matching qualitative colormap of Paraview
lut.SetTableValue(0 , 0 , 0 , 0, 1) #Black
lut.SetTableValue(mini, 1,1,1, 1) # white
lut.SetTableValue(mini+1, 77/255.,175/255., 74/255. , 1) # green
lut.SetTableValue(maxi-3, 152/255.,78/255.,163/255., 1) # purple
lut.SetTableValue(maxi-2, 255/255.,127/255., 0., 1) # orange
lut.SetTableValue(maxi-1, 55/255., 126/255., 184/255., 1) # blue
lut.SetTableValue(maxi, 166/255.,86/255.,40/255., 1) # brown
lut.Build()
# create a text actor
txt = vtk.vtkTextActor()
txt.SetInput(case)
txtprop=txt.GetTextProperty()
txtprop.SetFontFamilyToArial()
txtprop.SetFontSize(18)
txtprop.SetColor(0, 0, 0)
txt.SetDisplayPosition(20, 30)
# create a rendering window, renderer, and renderwindowinteractor
ren = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren)
iren = vtk.vtkRenderWindowInteractor()
style = vtk.vtkInteractorStyleTrackballCamera()
iren.SetInteractorStyle(style)
iren.SetRenderWindow(renWin)
# surface mapper and actor
surfacemapper = vtk.vtkPolyDataMapper()
surfacemapper.SetInputData(surface)
surfacemapper.SetScalarModeToUsePointFieldData()
surfacemapper.SelectColorArray(arrayname)
surfacemapper.SetLookupTable(lut)
surfacemapper.SetScalarRange(0,255)
surfaceactor = vtk.vtkActor()
surfaceactor.SetMapper(surfacemapper)
# refsurface mapper and actor
refmapper = vtk.vtkPolyDataMapper()
refmapper.SetInputData(ref)
refmapper.SetScalarModeToUsePointFieldData()
refmapper.SelectColorArray(arrayname)
refmapper.SetLookupTable(lut)
refmapper.SetScalarRange(0,255)
refactor = vtk.vtkActor()
refactor.GetProperty().SetOpacity(0.7)
refactor.SetMapper(refmapper)
# Remove existing lights and add lightkit lights
ren.RemoveAllLights()
lightkit = vtk.vtkLightKit()
lightkit.AddLightsToRenderer(ren)
# assign actors to the renderer
ren.AddActor(refactor)
ren.AddActor(surfaceactor)
ren.AddActor(txt)
# set the background and size; zoom in; and render
ren.SetBackground(1, 1, 1)
renWin.SetSize(1280, 960)
ren.ResetCamera()
ren.GetActiveCamera().Zoom(1)
# enable user interface interactor
iren.Initialize()
renWin.Render()
iren.Start()
outcam = ren.GetActiveCamera()
def visualise_default_continuous(surface,overlay,case,arrayname,edges=0,flip=0,colormap='BlYl',
interact=1,filename='./screenshot.png',LegendTitle='',mini='',maxi='',mag=2):
"""Visualise surface with a continuos colormap according to 'arrayname'."""
# surface mapper and actor
surfacemapper = vtk.vtkPolyDataMapper()
surfacemapper.SetInputData(surface)
surfacemapper.SelectColorArray(arrayname)
#Create a lookup table to map cell data to colors
if surface.GetPointData().GetArray(arrayname):
array = vtk_to_numpy(surface.GetPointData().GetArray(arrayname))
surfacemapper.SetScalarModeToUsePointFieldData()
else:
array = vtk_to_numpy(surface.GetCellData().GetArray(arrayname))
surfacemapper.SetScalarModeToUseCellFieldData()
if not maxi:
maxi = np.nanmax(array)
if not mini:
# mini might be zero, and is true
if mini == 0:
mini = mini
else:
mini = np.nanmin(array)
colors = getcolors(colormap)
numcolors = int(len(colors))
if colormap == '24_regions':
lut = vtk.vtkLookupTable()
lut.SetNumberOfTableValues(24)
# don't interpolate
for c in range(len(colors)):
this = colors[c]
lut.SetTableValue(this[0], this[1], this[2], this[3])
lut.Build()
surfacemapper.SetLookupTable(lut)
surfacemapper.SetScalarRange(1,24)
surfacemapper.InterpolateScalarsBeforeMappingOn()
else:
lut = vtk.vtkColorTransferFunction()
lut.SetColorSpaceToHSV()
lut.SetNanColor(0.5,0.5,0.5)
lut.AllowDuplicateScalarsOn()
for c in range(len(colors)):
cmin = colors[0][0]
cmax = colors[numcolors-1][0]
this = colors[c]
rat = (this[0] - cmin) / (cmax - cmin)
t = (maxi - mini) * rat + mini
lut.AddRGBPoint(t, this[1], this[2], this[3])
lut.Build()
surfacemapper.SetLookupTable(lut)
surfacemapper.SetScalarRange(mini,maxi)
surfacemapper.InterpolateScalarsBeforeMappingOn()
# create a text actor
txt = vtk.vtkTextActor()
txt.SetInput(case)
txtprop=txt.GetTextProperty()
txtprop.SetFontFamilyToArial()
txtprop.SetFontSize(30)
txtprop.SetColor(0, 0, 0)
txt.SetDisplayPosition(20, 30)
# create a rendering window, renderer, and renderwindowinteractor
ren = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren)
iren = vtk.vtkRenderWindowInteractor()
style = vtk.vtkInteractorStyleTrackballCamera()
iren.SetInteractorStyle(style)
iren.SetRenderWindow(renWin)
surfaceactor = vtk.vtkActor()
surfaceactor.SetMapper(surfacemapper)
# overlay mapper and actor
refmapper = vtk.vtkPolyDataMapper()
refmapper.SetInputData(overlay)
refmapper.SetScalarModeToUsePointFieldData()
if edges == 1:
refactor = vtk.vtkActor()
refactor.GetProperty().SetOpacity(1)
if colormap == 'erdc_rainbow_grey':
refactor.GetProperty().SetColor(1,1,1)
else:
refactor.GetProperty().SetColor(0,0,0)
refactor.GetProperty().SetRepresentationToWireframe()
refactor.GetProperty().SetLineWidth(6.)
refactor.SetMapper(refmapper)
else:
refactor = vtk.vtkActor()
refactor.GetProperty().SetOpacity(0.5)
refactor.GetProperty().SetColor(1, 0, 0)
refactor.SetMapper(refmapper)
ren.AddActor(surfaceactor)
ren.AddActor(refactor)
if LegendTitle:
ScalarBarActor = vtk.vtkScalarBarActor()
# colormap
ScalarBarActor.SetLookupTable(surfaceactor.GetMapper().GetLookupTable())
#labels format
ScalarBarActor.GetLabelTextProperty().ItalicOff()
ScalarBarActor.GetLabelTextProperty().BoldOn()
ScalarBarActor.GetLabelTextProperty().ShadowOff()
ScalarBarActor.GetLabelTextProperty().SetFontFamilyToArial()
ScalarBarActor.GetLabelTextProperty().SetFontSize(100)
ScalarBarActor.GetLabelTextProperty().SetColor(0.,0.,0.)
ScalarBarActor.SetLabelFormat('%.2f')
if colormap == '24_regions':
ScalarBarActor.GetLabelTextProperty().BoldOff()
ScalarBarActor.GetLabelTextProperty().SetFontSize(100)
ScalarBarActor.SetNumberOfLabels(24)
ScalarBarActor.SetLabelFormat('%.0f')
# orientation
ScalarBarActor.SetMaximumWidthInPixels(175)
ScalarBarActor.SetPosition(0.90,0.075)
ren.AddActor(ScalarBarActor)
else:
ren.AddActor(txt)
# set the background and size; zoom in; and render
ren.SetBackground(1, 1, 1)
renWin.SetSize(875, 800)
ren.ResetCamera()
if flip ==1:
# flip to foot to head position
# default values from paraview
aCamera = vtk.vtkCamera()
aCamera.SetViewUp(0, 1, 0)
aCamera.SetPosition(0,0,-3.17)
aCamera.SetFocalPoint(0,0,0)
aCamera.SetClippingRange(3.14,3.22)
aCamera.SetParallelScale(0.83)
ren.SetActiveCamera(aCamera)
ren.GetActiveCamera().Zoom(1.4)
iren.Initialize()
renWin.Render()
# Remove existing lights and add lightkit lights
ren.RemoveAllLights()
lightkit = vtk.vtkLightKit()
if colormap == 'fibrosis':
lightkit.SetKeyLightIntensity(0.95)
else:
lightkit.SetKeyLightIntensity(0.85)
lightkit.AddLightsToRenderer(ren)
# enable user interface interactor
if interact ==1:
iren.Start()
else:
# save as png
## Screenshot
windowToImageFilter = vtk.vtkWindowToImageFilter()
windowToImageFilter.SetInput(renWin)
windowToImageFilter.SetMagnification(mag) #set the resolution of the output image (3 times the current resolution of vtk render window)
windowToImageFilter.SetInputBufferTypeToRGBA() #also record the alpha (transparency) channel
windowToImageFilter.Update()
pngwriter = vtk.vtkPNGWriter()
pngwriter.SetFileName(filename)
pngwriter.SetInputConnection(windowToImageFilter.GetOutputPort())
pngwriter.Write()
def visualise_nan_glyph(surface,glyph,overlay,case,arrayname,edges=0,flip=0,colormap='BlYl',
interact=1,filename='./screenshot.png',LegendTitle='',mini='',maxi=''):
"""Visualise surface with glyphs colormapped according to 'arrayname'."""
# glyph mapper
glyphmapper = vtk.vtkPolyDataMapper()
glyphmapper.SetInputData(glyph)
glyphmapper.SelectColorArray(arrayname)
# only pointdata
array = vtk_to_numpy(surface.GetPointData().GetArray(arrayname))
glyphmapper.SetScalarModeToUsePointFieldData()
if not maxi:
maxi = np.nanmax(array)
if not mini:
# mini might be zero, and is true
if mini == 0:
mini = mini
else:
mini = np.nanmin(array)
colors = getcolors(colormap)
numcolors = int(len(colors))
if colormap == '24_regions':