-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmesh_funcs.py
3706 lines (2877 loc) · 133 KB
/
mesh_funcs.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 vtk import *
import sys, os
import math
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import Image
from vtk.util import numpy_support
from mpl_toolkits.mplot3d.axes3d import Axes3D
from descartes import PolygonPatch
import pylab as pl
import shapely.geometry as geometry
import ipyvolume.pylab as p3
from numpy import random, nanmax, argmax, unravel_index
from scipy.spatial.distance import pdist, squareform
import glob
import os
import hickle as hkl
import networkx as nx
from sklearn.decomposition import PCA
from scipy.signal import argrelmin
from scipy.signal import find_peaks
import scipy.optimize
import scipy
from scipy import interpolate
import networkx as nx
from networkx.algorithms.components.connected import connected_components
from shapely import geometry, ops
class mesh():
def __init__(self, opt):
self.pers_var = None # personal option that will be used to facilitate debugging
self.opt = opt # type of data (CT or US)
self.mesh_reader = None
self.meshActor = None
self.mesh_poly = None
self.endoActor = None
self.epiActor = None
self.irActor = None
self.orActor = None
self.points = None
self.triangles = None
self.npts = None
self.n_endo = None
self.n_epi = None
self.endoFilter = None
self.epiFilter = None
self.epi_poly = None
self.endo_poly = None
self.epi_apex_node = None
self.endo_apex_node = None
self.inner_rim_poly = None
self.inner_rim_points = None
self.inner_num_rim_pts = None
self.outer_rim_poly = None
self.outer_rim_points = None
self.outer_num_rim_pts = None
self.C = None # center point of the rim
self.P_fitcircle = None
self.aorticValvePts = None
self.mitralValvePts = None
self.combinedPoints = None # points that contains both the ring and the centerline
self.aortic_line = None # aortic points + line that divides aortic and mitral valve
self.mitral_line = None
self.aortic_cent = None
self.mitral_cent = None
self.com = None # center of mass of the entire mesh
self.plane_pts = None # the 3 points that define the 3rd chamber view
self.original_planes = None
self.axis_of_rot_normalized = None
self.orig_view_angles = None #4 -> 2,3 rot angles (1D vector)
self.orig_cut_poly_array = None #2D array: rows is 4ch--> 2ch--> 3ch and cols is endo, epi
self.orig_planeActor = None #2D array: rows is 4ch--> 2ch--> 3ch and cols is endo, epi
self.numSamples = None # number of horizontal lines
self.actual_num_samples = None
self.L = None
self.ideal_vol = None
self.ground_truth_vol = None
# the horizontal points computed from the ideal angles
self.ideal_horiz_2ch_a = None
self.ideal_horiz_2ch_b = None
self.ideal_horiz_4ch_a = None
self.ideal_horiz_4ch_b = None
self.ideal_lowest_point_2ch = None
self.ideal_lowest_point_4ch = None
self.thickness = None
self.rv_dir = None
self.plane_colors = [(0, 255, 0), (0, 0, 255), (0.9100, 0.4100, 0.1700)] #4,2,3
# save pca vectors
self.pca1 = None
self.pca2 = None
self.pca3 = None
# import mesh and read files ..
def input_mesh(self, vtkFile, display_opt):
self.mesh_reader = vtk.vtkDataSetReader()
self.mesh_reader.SetFileName(vtkFile)
self.mesh_reader.ReadAllScalarsOn() # Activate the reading of all scalars
self.mesh_reader.Update()
self.mesh_reader.GetHeader()
self.mesh_poly = self.mesh_reader.GetOutput()
meshMapper = vtk.vtkPolyDataMapper()
meshMapper.SetInputConnection(self.mesh_reader.GetOutputPort())
self.meshActor = vtk.vtkActor()
self.meshActor.SetMapper(meshMapper)
self.meshActor.GetProperty().SetColor(1.0, 0.0, 0.0)
if (display_opt):
axes = get_axes_actor([80,80,80], [0,0,0])
renderer = vtk.vtkRenderer()
renderer.SetBackground(1.0, 1.0, 1.0)
renderer.AddActor(self.meshActor)
renderer.AddActor(axes)
vtk_show(renderer)
def view_meshActor(self):
axes = get_axes_actor([80,80,80], [0,0,0])
ren = vtk.vtkRenderer()
ren.AddActor(self.meshActor)
ren.AddActor(axes)
vtk_show(ren)
def set_points_verts(self):
self.triangles = self.mesh_poly.GetPolys().GetData()
self.points = self.mesh_poly.GetPoints()
def align_meshes_pca(self, display_opt):
"""
Aligns mesh into the main pcs.
!! This makes x-axis the first pc !!
"""
# convert vtk points to numpy first
vtk_pts = self.points
numpy_pts = numpy_support.vtk_to_numpy(vtk_pts.GetData())
# perform pca
pca = PCA(n_components=3)
trans_coords = pca.fit_transform(numpy_pts)
eigenvectors = pca.components_
eigenvalues = pca.explained_variance_ratio_
# save pca vectors as global variables
self.pca1 = eigenvectors[0]
self.pca2 = eigenvectors[1]
self.pca3 = eigenvectors[2]
if display_opt:
axes = get_axes_actor([80,80,80], [0,0,0])
trans_act = include_points(trans_coords, trans_coords.shape[0], 4, (0,1,0))
self.meshActor.GetProperty().SetOpacity(0.6)
ren = vtk.vtkRenderer()
ren.AddActor(self.meshActor)
ren.AddActor(trans_act)
ren.AddActor(axes)
vtk_show(ren)
# reset the self.attributes with transformed coordinates
trans_vtk_pts = MakevtkPoints(trans_coords, deep=True)
self.points = trans_vtk_pts
self.mesh_poly.SetPoints(trans_vtk_pts)
meshMapper = vtk.vtkPolyDataMapper()
meshMapper.SetInputData(self.mesh_poly)
self.meshActor = vtk.vtkActor()
self.meshActor.SetMapper(meshMapper)
self.meshActor.GetProperty().SetColor(1.0, 0.0, 0.0)
def add_endo_epi_labels(self):
if (self.opt != 'US'):
print('Please use "get_endo_epi_rim_data()" for CT data.')
filename = 'D:\\Documents\\UNI\\MRes in Medical Imaging\\PhD Project\\Esther functions\\epiendo_icl.txt'
endo_epi_arr = np.loadtxt(filename)
self.npts = self.mesh_poly.GetNumberOfPoints()
# check that the epi_endo_labels correspond to the icl vtk file format (number of points should match)
if len(endo_epi_arr) != self.npts:
print('epiendo data does not correspond to the current vtk file!')
# label each point with endo or epi
endo_epi_labels = numpy_support.numpy_to_vtk(
num_array=endo_epi_arr, deep=True, array_type=vtk.VTK_DOUBLE)
endo_epi_labels.SetName("endoepilabels")
self.mesh_poly.GetPointData().AddArray(endo_epi_labels)
# how to extract specific label values with the indexing of the original pts array
arr = vtk.vtkDoubleArray()
arr = self.mesh_poly.GetPointData().GetAbstractArray("endoepilabels")
self.n_endo = int(np.sum(endo_epi_arr)) # number of endo points
self.n_epi = int(self.npts - self.n_endo) # number of epi point
def separate_endo_epi(self, threshold, display_opt):
epi_thresh = vtk.vtkThreshold() # for smooth surface that includes triangulation data
# epi_thresh = vtk.vtkThresholdPoints()
epi_thresh.ThresholdByLower(threshold) # epi = 0
epi_thresh.SetInputArrayToProcess(0, 0, 0, 0, "endoepilabels")
epi_thresh.SetInputData(self.mesh_poly)
epi_thresh.Update()
# create geometry filter
self.epiFilter = vtk.vtkGeometryFilter()
self.epiFilter.SetInputData(epi_thresh.GetOutput())
self.epiFilter.Update()
# epi_poly
self.epi_poly = self.epiFilter.GetOutput()
# create poly data mapper
epiMapper = vtk.vtkPolyDataMapper()
epiMapper.SetInputConnection(self.epiFilter.GetOutputPort())
# create actor
epiActor = vtk.vtkActor()
epiActor.SetMapper(epiMapper)
epiActor.GetProperty().SetColor(1.0, 0.0, 0.0)
epiActor.GetProperty().SetLineWidth(2)
#######################################################################################################################
# create thresholder for ENDO
endo_thresh = vtk.vtkThreshold() # for smooth surface that includes triangulation data
# endo_thresh = vtk.vtkThresholdPoints() # for points rather than smooth surface
endo_thresh.ThresholdByUpper(threshold) # endo = 1
endo_thresh.SetInputArrayToProcess(0, 0, 0, 0, "endoepilabels")
endo_thresh.SetInputData(self.mesh_poly)
endo_thresh.Update()
# create geometry filter
self.endoFilter = vtk.vtkGeometryFilter()
self.endoFilter.SetInputData(endo_thresh.GetOutput())
self.endoFilter.Update()
self.endo_poly = self.endoFilter.GetOutput()
# create poly data mapper
endoMapper = vtk.vtkPolyDataMapper()
endoMapper.SetInputConnection(self.endoFilter.GetOutputPort())
# create actor
endoActor = vtk.vtkActor()
endoActor.SetMapper(endoMapper)
endoActor.GetProperty().SetColor(0.0, 1.0, 0.0)
endoActor.GetProperty().SetLineWidth(2)
########################################################################################################################
# generate renderer
ren = vtk.vtkRenderer()
ren.SetBackground(1.0, 1.0, 1.0)
ren.AddActor(epiActor)
ren.AddActor(endoActor)
# display
if (display_opt):
vtk_show(ren)
def set_apex_node(self):
"""
Sets epi and endo apex nodes based on prior knowledge.
"""
if self.opt == 'CT':
self.epi_apex_node = self.mesh_poly.GetPoints().GetPoint(3604)
self.endo_apex_node = self.mesh_poly.GetPoints().GetPoint(3579)
else:
self.endo_apex_node = None # we do not know this
self.epi_apex_node = self.mesh_poly.GetPoints().GetPoint(0)
def compute_apex_nodes(self, display_opt):
"""
Function to compute apex nodes (for both endo and epi).
For these, we need to align the pca.
Finds the points with the lowest x-component (corresponding to pca1)
"""
# convert endo and epi poly to numpys for faster processing:
numpy_endo = numpy_support.vtk_to_numpy(self.endo_poly.GetPoints().GetData())
numpy_epi = numpy_support.vtk_to_numpy(self.epi_poly.GetPoints().GetData())
# simply find lowest pca1 component since they all aligned
min_endo_idx = np.argmin(numpy_endo[:,0])
min_epi_idx = np.argmin(numpy_epi[:,0])
endo_minima = numpy_endo[min_endo_idx]
epi_minima = numpy_epi[min_epi_idx]
if display_opt:
minima_endo_act = include_points(list(endo_minima), 1, 10, (1,1,1))
minima_epi_act = include_points(list(epi_minima), 1, 10, (1,1,1))
self.endoActor.GetProperty().SetOpacity(0.6)
self.epiActor.GetProperty().SetOpacity(1)
axes = get_axes_actor([200,50,50], [-0.51,0,0])
ren = vtk.vtkRenderer()
ren.SetBackground(0,0,0)
ren.AddActor(self.endoActor)
ren.AddActor(self.epiActor)
ren.AddActor(minima_endo_act)
ren.AddActor(minima_epi_act)
ren.AddActor(axes)
vtk_show(ren)
self.endo_apex_node = endo_minima
self.epi_apex_node = epi_minima
def get_endo_epi_rim_data(self, fnms):
if (self.opt != 'CT'):
print('Please use "add_endo_epi_labels()" for US mesh.')
endo_fnm = fnms[0]
epi_fnm = fnms[1]
inner_rim_fnm = fnms[2]
outer_rim_fnm = fnms[3]
# import the text file and set all numbers as int (since we only have ids)
endo_arr = np.genfromtxt(endo_fnm, delimiter=",", skip_header=1, dtype=int)
epi_arr = np.genfromtxt(epi_fnm, delimiter=",", skip_header=1, dtype=int)
inner_rim_arr = np.genfromtxt(inner_rim_fnm, delimiter=",", skip_header=1, dtype=int)
outer_rim_arr = np.genfromtxt(outer_rim_fnm, delimiter=",", skip_header=1, dtype=int)
# delete the first column of endo and epi arrays
endo_arr = endo_arr[:, 4:]
epi_arr = epi_arr[:, 4:]
inner_rim_arr = inner_rim_arr[:, 3:]
self.inner_num_rim_pts = inner_rim_arr.shape[0]
outer_rim_arr = outer_rim_arr[:, 3:]
# create the polydata from these arrays
self.endo_poly, self.inner_rim_poly = self.create_polydata_from_id_array(endo_arr, inner_rim_arr)
self.epi_poly, self.outer_rim_poly = self.create_polydata_from_id_array(epi_arr, outer_rim_arr)
def endo_epi_rim_model(self, fnms):
if (self.opt != 'model'):
print('Please check what type of mesh you have. This function only works for model meshes.')
epi_fnm = fnms[0]
endo_fnm = fnms[1]
inner_rim_fnm = fnms[2]
# import the text file and set all numbers as int (since we only have ids)
epi_arr = np.genfromtxt(epi_fnm, delimiter=",", skip_header=1, dtype=int)
endo_arr = np.genfromtxt(endo_fnm, delimiter=",", skip_header=1, dtype=int)
inner_rim_arr = np.genfromtxt(inner_rim_fnm, delimiter=",", skip_header=1, dtype=int)
# delete all but first and last columns
epi_arr = epi_arr[:, [9, 10]]
endo_arr = endo_arr[:, [9, 10]]
inner_rim_arr = inner_rim_arr[:, [7, 8]]
self.inner_num_rim_pts = inner_rim_arr.shape[0]
# create the polydata from these arrays
self.epi_poly = self.create_polydata_from_id_array(epi_arr, 0)
self.endo_poly = self.create_polydata_from_id_array(endo_arr, 0)
self.inner_rim_poly = self.create_polydata_from_id_array(inner_rim_arr, 1)
def create_polydata_from_id_array(self, arr, rim_arr):
""" This functions creates polydata objects
Inputs:
arr : the information on cell ids and point ids
typ : 0 is polygons are required (for endo and epi poly)
1 means only points are required (for rim)
rim_arr : contains pointid information (rather than cellid)
Output:
polydata (labelled for endo/epi_poly)
"""
# for endo/epi_poly (using cellid data in arr)
tot_num_cells = arr.shape[0]
selected_idx = []
for i in range(tot_num_cells):
if arr[i, 1] == 1: # if vtkIsSelected == True
selected_idx.append(arr[i, 0])
num_selected = len(selected_idx)
polydata = vtk.vtkPolyData()
points = self.points # you need to include all the points from the original data set, the only thing that differs is which triangles are shown
triangles = vtk.vtkCellArray()
for i in range(num_selected):
cellId = selected_idx[i]
cell = self.mesh_poly.GetCell(cellId)
triangles.InsertNextCell(cell)
# create the polydata
# you need to put it ALL the points of the mesh (not just the ones labelled)
polydata.SetPoints(points)
polydata.SetPolys(triangles)
# make sure now you clean the polydata to remove unused points
cpd = vtk.vtkCleanPolyData()
cpd.SetInputData(polydata)
cpd.Update()
polydata = cpd.GetOutput() #endo_poly or epi_poly
# now label endo or epi_poly with rim_poly points
labels = vtk.vtkIntArray()
labels.SetNumberOfComponents(1)
labels.SetName("rim labels")
# for rim points
tot_num_cells = rim_arr.shape[0]
selected_idx = []
for i in range(tot_num_cells):
if rim_arr[i, 1] == 1: # if vtkIsSelected == True
selected_idx.append(rim_arr[i, 0])
num_selected = len(selected_idx)
rimpoly = vtk.vtkPolyData() # rim polydata
points = vtk.vtkPoints()
for i in range(num_selected):
pointId = selected_idx[i]
pt = self.mesh_poly.GetPoints().GetPoint(pointId)
points.InsertNextPoint(pt)
labels.InsertNextValue(23)
# insert label as field data
polydata.GetFieldData().AddArray(labels)
rimpoly.SetPoints(points)
return polydata, rimpoly
def actor_from_segment(self, polydata, typ, display_opt):
"""
Converts polydata segment (e.g. epi_poly, endo_poly, inner_rim_poly, ...etc.)
into actor and displays it.
"""
# if opt = 0: polydata has only point data (i.e. requires vertex filter)
# if opt = 1: polydata has point + cell data
self.meshActor.GetProperty().SetOpacity(0.3)
if typ == 0: # point data
# add vertex at each point (so no need to insert vertices manually)
vertexFilter = vtk.vtkVertexGlyphFilter()
vertexFilter.SetInputData(polydata)
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputConnection(vertexFilter.GetOutputPort())
actor = vtk.vtkActor()
actor.SetMapper(mapper)
actor.GetProperty().SetColor(1, 0, 0)
actor.GetProperty().SetPointSize(7)
if display_opt:
axes = get_axes_actor([80,80,80], [0,0,0])
ren = vtk.vtkRenderer()
ren.SetBackground(1.0, 1.0, 1.0)
ren.AddActor(self.meshActor)
ren.AddActor(axes)
ren.AddActor(actor)
vtk_show(ren)
else: # point data + cell data
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputData(polydata)
actor = vtk.vtkActor()
actor.SetMapper(mapper)
actor.GetProperty().SetColor(0, 1, 0)
actor.GetProperty().SetPointSize(7)
if display_opt:
axes = get_axes_actor([80,80,80], [0,0,0])
ren = vtk.vtkRenderer()
ren.SetBackground(1.0, 1.0, 1.0)
ren.AddActor(actor)
ren.AddActor(self.meshActor)
ren.AddActor(axes)
vtk_show(ren)
return actor
# extract the rim, aortic and mitral valve centers ..
def extract_rim(self, display_opt):
fe = vtk.vtkFeatureEdges()
fe.SetInputData(self.epi_poly)
fe.BoundaryEdgesOn()
fe.FeatureEdgesOff()
fe.ManifoldEdgesOff()
fe.NonManifoldEdgesOff()
fe.Update()
self.inner_rim_poly = fe.GetOutput()
self.inner_rim_points = self.inner_rim_poly.GetPoints()
self.inner_num_rim_pts = self.inner_rim_points.GetNumberOfPoints()
eM = vtk.vtkPolyDataMapper()
eM.SetInputConnection(fe.GetOutputPort())
eA = vtk.vtkActor()
eA.GetProperty().SetColor(0.0, 0.0, 1.0)
eA.GetProperty().SetLineWidth(5)
eA.SetMapper(eM)
# create poly data mapper to display the epi layer
epiMapper = vtk.vtkPolyDataMapper()
epiMapper.SetInputData(self.epi_poly)
# create actor
epiActor = vtk.vtkActor()
epiActor.SetMapper(epiMapper)
epiActor.GetProperty().SetColor(0.0, 1.0, 0.0)
epiActor.GetProperty().SetLineWidth(2)
ren = vtk.vtkRenderer()
ren.SetBackground(1.0, 1.0, 1.0)
ren.AddActor(epiActor)
ren.AddActor(eA)
if (display_opt):
vtk_show(ren)
def circle_fit(self, display):
# -------------------------------------------------------------------------------
# (1) Fitting plane by SVD for the mean-centered data
# Eq. of plane is <p,n> + d = 0, where p is a point on plane and n is normal vector
# -------------------------------------------------------------------------------
x_rim, y_rim, z_rim = get_xyz_vecs(self.inner_rim_points, self.inner_num_rim_pts)
P = np.vstack((x_rim, y_rim, z_rim))
P = np.transpose(P)
P_mean = P.mean(axis=0)
P_centered = P - P_mean
U, s, V = np.linalg.svd(P_centered)
# Normal vector of fitting plane is given by 3rd column in V
# Note linalg.svd returns V^T, so we need to select 3rd row from V^T
normal = V[2, :]
d = -np.dot(P_mean, normal) # d = -<p,n>
# -------------------------------------------------------------------------------
# (2) Project points to coords X-Y in 2D plane
# -------------------------------------------------------------------------------
P_xy = rodrigues_rot(P_centered, normal, [0, 0, 1])
# -------------------------------------------------------------------------------
# (3) Fit circle in new 2D coords
# -------------------------------------------------------------------------------
xc, yc, r = fit_circle_2d(P_xy[:, 0], P_xy[:, 1])
# --- Generate circle points in 2D
t = np.linspace(0, 2*np.pi, 100)
xx = xc + r*np.cos(t)
yy = yc + r*np.sin(t)
# -------------------------------------------------------------------------------
# (4) Transform circle center back to 3D coords
# -------------------------------------------------------------------------------
C = rodrigues_rot(np.array([xc, yc, 0]), [0, 0, 1], normal) + P_mean
C = C.flatten()
# --- Generate points for fitting circle
t = np.linspace(0, 2*np.pi, 100)
u = P[0] - C
P_fitcircle = generate_circle_by_vectors(t, C, r, normal, u)
# --- Generate points for fitting arc
u = P[0] - C
v = P[-1] - C
theta = angle_between(u, v, normal)
if display:
fig = plt.figure(figsize=(15, 11))
alpha_pts = 0.5
figshape = (2, 3)
ax = [None]*4
ax[0] = plt.subplot2grid(figshape, loc=(0, 0), colspan=2)
ax[1] = plt.subplot2grid(figshape, loc=(1, 0))
ax[2] = plt.subplot2grid(figshape, loc=(1, 1))
ax[3] = plt.subplot2grid(figshape, loc=(1, 2))
i = 0
ax[i].set_title('Fitting circle in 2D coords projected onto fitting plane')
ax[i].set_xlabel('x')
ax[i].set_ylabel('y')
ax[i].set_aspect('equal', 'datalim')
ax[i].margins(.1, .1)
ax[i].grid()
i = 1
ax[i].scatter(P[:, 0], P[:, 1], alpha=alpha_pts, label='Cluster points P')
ax[i].set_title('View X-Y')
ax[i].set_xlabel('x')
ax[i].set_ylabel('y')
ax[i].set_aspect('equal', 'datalim')
ax[i].margins(.1, .1)
ax[i].grid()
i = 2
ax[i].scatter(P[:, 0], P[:, 2], alpha=alpha_pts, label='Cluster points P')
ax[i].set_title('View X-Z')
ax[i].set_xlabel('x')
ax[i].set_ylabel('z')
ax[i].set_aspect('equal', 'datalim')
ax[i].margins(.1, .1)
ax[i].grid()
i = 3
ax[i].scatter(P[:, 1], P[:, 2], alpha=alpha_pts, label='Cluster points P')
ax[i].set_title('View Y-Z')
ax[i].set_xlabel('y')
ax[i].set_ylabel('z')
ax[i].set_aspect('equal', 'datalim')
ax[i].margins(.1, .1)
ax[i].grid()
ax[0].scatter(P_xy[:, 0], P_xy[:, 1], alpha=alpha_pts, label='Projected points')
ax[0].plot(xx, yy, 'k--', lw=2, label='Fitting circle')
ax[0].plot(xc, yc, 'k+', ms=10)
ax[0].legend()
ax[1].plot(P_fitcircle[:, 0], P_fitcircle[:, 1], 'k--', lw=2, label='Fitting circle')
ax[2].plot(P_fitcircle[:, 0], P_fitcircle[:, 2], 'k--', lw=2, label='Fitting circle')
ax[3].plot(P_fitcircle[:, 1], P_fitcircle[:, 2], 'k--', lw=2, label='Fitting circle')
ax[3].legend()
ax[1].plot(C[0], C[1], 'k+', ms=10)
ax[2].plot(C[0], C[2], 'k+', ms=10)
ax[3].plot(C[1], C[2], 'k+', ms=10)
ax[3].legend()
fig = plt.figure(figsize=(15, 15))
ax = fig.add_subplot(1, 1, 1, projection='3d')
ax.plot(*P.T, ls='', marker='o', alpha=0.5, label='Cluster points P')
# --- Plot fitting plane
xx, yy = np.meshgrid(np.linspace(-40, 20, 100), np.linspace(-40, 40, 100))
zz = (-normal[0]*xx - normal[1]*yy - d) / normal[2]
ax.plot_surface(xx, yy, zz, rstride=2, cstride=2, color='y', alpha=0.2, shade=False)
# --- Plot fitting circle
ax.plot(*P_fitcircle.T, color='k', ls='--', lw=2, label='Fitting circle')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.legend()
ax.set_aspect('equal', 'datalim')
set_axes_equal_3d(ax)
self.C = C
self.P_fitcircle = P_fitcircle
def set_combinedPoints(self, display_opt):
spec1 = [self.inner_rim_points.GetPoint(69)[0], self.inner_rim_points.GetPoint(69)[
1], self.inner_rim_points.GetPoint(69)[2]]
spec2 = [self.inner_rim_points.GetPoint(110)[0], self.inner_rim_points.GetPoint(110)[
1], self.inner_rim_points.GetPoint(110)[2]]
# generate random points between the points (rather than creating a line)
samp = np.random.uniform(low=0, high=1, size=(100,))
x_samp = spec1[0] + samp*(spec2[0] - spec1[0])
y_samp = spec1[1] + samp*(spec2[1] - spec1[1])
z_samp = spec1[2] + samp*(spec2[2] - spec1[2])
self.combinedPoints = vtk.vtkPoints()
for i in range(self.inner_num_rim_pts): # third add the points from the rim points
self.combinedPoints.InsertNextPoint(self.inner_rim_points.GetPoint(i))
# create polydata for the combined points
combinedPoly = vtk.vtkPolyData()
combinedPoly.SetPoints(self.combinedPoints)
# add vertex at each point (so no need to insert vertices manually)
vertexFilter = vtk.vtkVertexGlyphFilter()
vertexFilter.SetInputData(combinedPoly)
# create pipeline for display
lineMapper = vtk.vtkPolyDataMapper()
lineMapper.SetInputConnection(vertexFilter.GetOutputPort())
lineActor = vtk.vtkActor()
lineActor.SetMapper(lineMapper)
lineActor.GetProperty().SetLineWidth(5)
lineActor.GetProperty().SetPointSize(5)
lineActor.GetProperty().SetColor(0, 0, 0)
ren = vtk.vtkRenderer()
ren.SetBackground(1.0, 1.0, 1.0)
ren.AddActor(lineActor)
if (display_opt):
vtk_show(ren)
def sort_mitral_aortic_valve_points(self):
self.aorticValvePts = vtk.vtkPoints()
aortic_idx = np.arange(42)
aortic_idx = np.append(aortic_idx, np.arange(70, 78))
aortic_idx = np.append(aortic_idx, 112)
for i in range(aortic_idx.shape[0]):
self.aorticValvePts.InsertNextPoint(self.combinedPoints.GetPoint(aortic_idx[i]))
self.mitralValvePts = vtk.vtkPoints()
mitral_idx = np.arange(42, 70)
mitral_idx = np.append(mitral_idx, np.arange(78, 110))
mitral_idx = np.append(mitral_idx, [110, 111, 113, 114, 115, 116, 117, 118])
for i in range(mitral_idx.shape[0]):
self.mitralValvePts.InsertNextPoint(self.combinedPoints.GetPoint(mitral_idx[i]))
def set_line_pts(self):
self.aortic_line = vtk.vtkPoints() # DO FOR AORTIC
spec1 = [self.inner_rim_points.GetPoint(69)[0], self.inner_rim_points.GetPoint(69)[
1], self.inner_rim_points.GetPoint(69)[2]]
spec2 = [self.inner_rim_points.GetPoint(110)[0], self.inner_rim_points.GetPoint(110)[
1], self.inner_rim_points.GetPoint(110)[2]]
# generate random points between the points (rather than creating a line)
samp = np.random.uniform(low=0, high=1, size=(50,))
x_samp = spec1[0] + samp*(spec2[0] - spec1[0])
y_samp = spec1[1] + samp*(spec2[1] - spec1[1])
z_samp = spec1[2] + samp*(spec2[2] - spec1[2])
self.aortic_line.InsertNextPoint(spec1) # first add the special point 1 (69)
self.aortic_line.InsertNextPoint(spec2) # first add the special point 2 (110)
for i in range(x_samp.shape[0]): # second add the points from the random sampling of the line
self.aortic_line.InsertNextPoint([x_samp[i], y_samp[i], z_samp[i]])
for i in range(self.aorticValvePts.GetNumberOfPoints()): # third add the points from the rim points
self.aortic_line.InsertNextPoint(self.aorticValvePts.GetPoint(i))
# DO FOR MITRAL
self.mitral_line = vtk.vtkPoints()
spec1 = [self.inner_rim_points.GetPoint(69)[0], self.inner_rim_points.GetPoint(69)[
1], self.inner_rim_points.GetPoint(69)[2]]
spec2 = [self.inner_rim_points.GetPoint(110)[0], self.inner_rim_points.GetPoint(110)[
1], self.inner_rim_points.GetPoint(110)[2]]
# generate random points between the points (rather than creating a line)
samp = np.random.uniform(low=0, high=1, size=(50,))
x_samp = spec1[0] + samp*(spec2[0] - spec1[0])
y_samp = spec1[1] + samp*(spec2[1] - spec1[1])
z_samp = spec1[2] + samp*(spec2[2] - spec1[2])
self.mitral_line.InsertNextPoint(spec1) # first add the special point 1 (69)
self.mitral_line.InsertNextPoint(spec2) # first add the special point 2 (110)
for i in range(x_samp.shape[0]): # second add the points from the random sampling of the line
self.mitral_line.InsertNextPoint([x_samp[i], y_samp[i], z_samp[i]])
for i in range(self.mitralValvePts.GetNumberOfPoints()): # third add the points from the rim points
self.mitral_line.InsertNextPoint(self.mitralValvePts.GetPoint(i))
def convex_hull_center(self, display_opt):
mtN = int(self.aortic_line.GetNumberOfPoints()) # do for aortic line first
mt_x = np.zeros((mtN), dtype=float)
mt_y = np.zeros((mtN), dtype=float)
mt_z = np.zeros((mtN), dtype=float)
for i in range(mtN):
mt_x[i] = self.aortic_line.GetPoint(i)[0]
mt_y[i] = self.aortic_line.GetPoint(i)[1]
mt_z[i] = self.aortic_line.GetPoint(i)[2]
mtX = np.column_stack((mt_x, mt_y, mt_z))
point_collection = geometry.MultiPoint(list(np.column_stack((mtX[:, 0], mtX[:, 1]))))
point_collection.envelope
convex_hull_polygon = point_collection.convex_hull
cent = np.array(convex_hull_polygon.centroid)
if display_opt:
_ = plot_polygon(convex_hull_polygon)
_ = pl.plot(mtX[:, 0], mtX[:, 1], 'o', color='#f16824')
_ = pl.plot(cent[0], cent[1], 'o', color='red')
# for z-component of polygon center, just take the average (avcent[2]) (a bit inaccurate but acceptable since rim is almost flat)
# tkae x and x components from (cent) as it is more accurate
self.aortic_cent = np.array([cent[0], cent[1], np.mean(mtX[:, 2])])
# do for mitral line first
mtN = int(self.mitral_line.GetNumberOfPoints())
mt_x = np.zeros((mtN), dtype=float)
mt_y = np.zeros((mtN), dtype=float)
mt_z = np.zeros((mtN), dtype=float)
for i in range(mtN):
mt_x[i] = self.mitral_line.GetPoint(i)[0]
mt_y[i] = self.mitral_line.GetPoint(i)[1]
mt_z[i] = self.mitral_line.GetPoint(i)[2]
mtX = np.column_stack((mt_x, mt_y, mt_z))
point_collection = geometry.MultiPoint(list(np.column_stack((mtX[:, 0], mtX[:, 1]))))
point_collection.envelope
convex_hull_polygon = point_collection.convex_hull
cent = np.array(convex_hull_polygon.centroid)
if display_opt:
_ = plot_polygon(convex_hull_polygon)
_ = pl.plot(mtX[:, 0], mtX[:, 1], 'o', color='#f16824')
_ = pl.plot(cent[0], cent[1], 'o', color='red')
self.mitral_cent = np.array([cent[0], cent[1], np.mean(mtX[:, 2])])
def set_rv_dir(self, rv_dirs, iter):
if np.isscalar(rv_dirs):
print('no rv_dir given, using +y axis as RV dir ..')
self.rv_dir = np.array([0,1,0])
else:
self.rv_dir = rv_dirs[iter]
print('rv given : ', self.rv_dir)
# extract 2,3 and 4 apical chamber views..
def mesh_slicer(self, plane, opt):
"""Function to obtain slice of 3D mesh from given plane (using intersection of point to plane)
Args:
mesh_reader (vtkObject) : the mesh read from using vtk pipeline
plane (tuple) : coefficients of the plane (a,b,c,d)
points (list of tuples) : nodes of the mesh
opt (string) : {'cut','all'} --> display only the cut slice or the mesh with outline of cut through plane
Returns:
rot_plane : the rotated plane
"""
# get plane coefficients
a = plane[0]
b = plane[1]
c = plane[2]
# create vtk plane object
VTKplane = vtk.vtkPlane()
# for now we choose the center point as the point of rotation
VTKplane.SetOrigin(self.mesh_poly.GetCenter())
VTKplane.SetNormal(a, b, c)
VTKplane.SetOrigin(self.epi_apex_node)
# create cutter
cutEdges = vtk.vtkCutter()
cutEdges.SetInputData(self.mesh_poly)
cutEdges.SetCutFunction(VTKplane)
cutEdges.GenerateCutScalarsOn()
cutEdges.SetValue(0, 0.5)
# create renderer
ren = vtk.vtkRenderer()
ren.SetBackground(0.0, 0.0, 0.0)
# create mapper
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputConnection(cutEdges.GetOutputPort())
# create actor
actor = vtk.vtkActor()
actor.SetMapper(mapper)
actor.GetProperty().SetColor(0.0, 0.0, 1.0)
actor.GetProperty().SetLineWidth(2)
# display apex point
apexA = include_points(list(self.epi_apex_node), 1, 15, (0, 0, 1))
if (opt == 'mesh'):
meshMapper = vtk.vtkPolyDataMapper()
meshMapper.SetInputData(self.mesh_poly)
meshActor = vtk.vtkActor()
meshActor.SetMapper(meshMapper)
meshActor.GetProperty().SetColor(1.0, 0.0, 0.0)
# generate renderer
ren.AddActor(self.meshActor)
ren.AddActor(actor)
ren.AddActor(apexA)
else:
ren.AddActor(actor)
ren.AddActor(apexA)
# display
vtk_show(ren)
def set_orig_view_angles(self, orig_view_angles):
self.orig_view_angles = orig_view_angles
def set_center_irp(self):
# step 1: find center of inner rim poly
numpy_irp = numpy_support.vtk_to_numpy(self.inner_rim_poly.GetPoints().GetData())
self.C = np.mean(numpy_irp, axis=0)
def find_4ch_view(self, display_opt):
""" +y dir points towards RV -> use this as 4ch view
more reliable than finding mitral and aortic valve points
the three points on the 4ch view are:
1) center of inner rim poly
2) apex point
3) the y direction
"""
# step 1: check if self.C exists
if self.C is None:
print('Center of inner rim poly is not set! exiting..')
sys.exit()
# step 2: find y direction
pt_rv_dir = 50.0*self.rv_dir
# set plane_pts :
self.plane_pts = np.vstack((self.C, pt_rv_dir, self.epi_apex_node))
# construct plane using p1, p2 and the apex node
four_ch_view_plane_normal = find_plane_eq(self.C, pt_rv_dir, self.epi_apex_node)
if display_opt:
# display x-y-z actor
axes = get_axes_actor([50,50,50], [0,0,0])
c_irp_act = include_points(self.C, 1, 10, (1,0,1))
pt_rv_dir_act = include_points(pt_rv_dir, 1, 10, (1,1,0))
epi_apex_act = include_points(list(self.epi_apex_node), 1, 10, (1,0,1))
ren = vtk.vtkRenderer()
ren.AddActor(self.meshActor)
ren.AddActor(c_irp_act)
ren.AddActor(epi_apex_act)
ren.AddActor(pt_rv_dir_act)
ren.AddActor(axes)
vtk_show(ren)
# # step 1: find center of endo_poly
# endo_numpy = numpy_support.vtk_to_numpy(self.endo_poly.GetPoints().GetData())
# com = np.mean(endo_numpy, 0)
#
# # step 2: construct line rv_dir that is translated at position com
# pSource = com - 100*self.rv_dir
# pTarget = com + 100*self.rv_dir
# # step 3: find intersection of line with endo_poly
# bspTree = vtk.vtkModifiedBSPTree()
# bspTree.SetDataSet(self.endo_poly) # cut through endo polydata (not mesh)
# bspTree.BuildLocator()
#
# # set these as plane_pts
# p1 = pSource
# p2 = pTarget
#
# four_ch_valve_pts = [p1, p2]
# self.plane_pts = np.vstack((p1, p2, self.epi_apex_node))
#
# # construct plane using p1, p2 and the apex node
# four_ch_view_plane_normal = find_plane_eq(p1, p2, self.epi_apex_node)
# if display_opt:
# # display x-y-z actor
# axes = get_axes_actor([80,80,80], [0,0,0])
#
# p1_act = include_points(p1, 1, 10, (1,0,1))
# p2_act = include_points(p2, 1, 10, (1,1,0))
# epi_apex_act = include_points(list(self.epi_apex_node), 1, 10, (1,0,1))
# endo_apex_act = include_points(list(self.endo_apex_node), 1, 10, (1,0,1))
#
# ren = vtk.vtkRenderer()
# ren.AddActor(self.meshActor)
# ren.AddActor(p1_act)