forked from megdec/vascularmd
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEditor.py
More file actions
3155 lines (2252 loc) · 109 KB
/
Copy pathEditor.py
File metadata and controls
3155 lines (2252 loc) · 109 KB
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
####################################################################################################
# Author: Meghane Decroocq
#
# This file is part of vascularmd project (https://github.com/megdec/vascularmd)
#
# This program is free software: you can redistribute it and/or modify it under the terms of the
# GNU General Public License as published by the Free Software Foundation, version 3 of the License.
#
####################################################################################################
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as imt
import pickle
import pyvista as pv
from vpython import *
from numpy.linalg import norm
import copy
import nibabel as nib
import os
from Nfurcation import Nfurcation
from ArterialTree import ArterialTree
from Spline import Spline
from Model import Model
from utils import *
class Editor:
""" Class to edit vascular networks with a vpython GUI """
def __init__(self, tree, width=1200, height=600):
"""
Keyword argument:
tree -- Arterial Tree object
"""
self.tree = tree
self.barycenter = self.barycenter_finder()
# Scene set up
scene.caption = ""
self.text_output = wtext(text="")
self.output_message("Zoom in using mouse middle button, rotate by right clicking and moving the mouse and translate by pressing the shift key.")
scene.background = color.white
scene.width = width
scene.height = height
#scene.range = 75
scene.center = vector(self.barycenter[0], self.barycenter[1], self.barycenter[2])
slider_length = 300
slider_width = 5
slider_right_margin = 90
self.scene = scene
self.elements = {'full' : {}, 'topo' : {}, 'model' : {}, 'mesh' : {}, 'pathology' : {}}
scene.append_to_caption('\n\nEdit ')
self.edition_menu = menu(choices = ['off', 'data', 'topo', 'model', 'crop', 'mesh', 'pathology'], selected = 'off', index=0, bind = self.update_edition_mode)
self.edition_mode = 'off'
self.mesh_selection = []
self.crop_selection = []
scene.append_to_caption('\nImport centerline ')
self.centerline_file_winput = winput(text="", bind = self.reset_scene, width=200)
scene.append_to_caption('\nImport image ')
self.slice_button = button(text= "Cut slice " , bind=self.compute_slice, disabled = True)
self.cursor_checkbox = checkbox(text= "Show origin " , bind=self.update_visibility_cursor, checked = False)
self.slice_checkbox = checkbox(text= "Show slice" , bind=self.update_visibility_slice, checked = False)
self.slice_checkbox.disabled = True
self.cursor = sphere(pos=scene.center, color=color.yellow, radius=2, mode = "cursor", visible = False, locked = False)
self.slice = None
self.slice_plane = [None, None]
scene.append_to_caption('\tPath ')
self.image_file_winput = winput(text="", bind = self.load_image, width=200)
scene.append_to_caption('\tOpacity ')
self.slice_opacity_slider = slider(bind = self.slice_opacity, value = 1, length = 150, width = slider_width)
scene.append_to_caption('\nExport ')
self.save_button = button(text = "Save", bind=self.save)
self.save_menu = menu(choices = ['centerline', 'model', 'surface mesh', 'volume mesh'], selected = 'centerline', index=0, bind = self.do_nothing)
self.save_directory = ""
scene.append_to_caption('\tOutput directory ')
self.save_winput = winput(text="", bind = self.update_save_directory, width=200)
self.save_filename = "vascular_network"
scene.append_to_caption('\tOutput filename ')
self.save_filename_winput = winput(text="vascular_network", bind = self.update_save_filename, width=200)
scene.append_to_caption('\n\n')
# Check boxes
self.checkboxes = {'full' : checkbox(text= "Data ", bind=self.update_visibility_state, checked=True, mode = "full")}
self.update_buttons = {'full' : button(text = "Apply", bind=self.update_graph, mode = 'full')}
scene.append_to_caption('\t\t\t\t\t\t\t')
self.checkboxes['topo'] = checkbox(text= "Topology ", bind=self.update_visibility_state, checked = False, mode = "topo")
self.update_buttons['topo'] = button(text = "Apply", bind=self.update_graph, mode = 'topo')
self.crop_button = button(text = " Crop ", bind=self.crop_network, mode = 'topo', activated = False)
scene.append_to_caption('\t\t\t\t\t')
self.checkboxes['model'] = checkbox(text= "Model ", bind=self.update_visibility_state, mode = "model", checked = False)
self.update_buttons['model'] = button(text = "Apply", bind=self.update_graph, mode = 'model')
self.extension_button = button(text="Extend", bind=self.manage_extensions)
self.extension_state = False
scene.append_to_caption('\t\t\t\t\t')
self.checkboxes['mesh'] = checkbox(text= "Mesh " , bind=self.update_visibility_state, mode="mesh", checked = False)
self.surface_button = button(text="Surface", bind=self.mesh_surface)
self.deform_mesh_button = button(text="Deform", bind=self.deform_mesh)
self.check_mesh_button = button(text="Check", bind=self.check_mesh)
self.check_state = False
self.close_mesh_button = button(text="Close", bind=self.close_mesh)
self.closing_state = False
self.volume_button = button(text="Volume", bind=self.mesh_volume)
scene.append_to_caption("\n\nOpacity\t\t\t\t\t\t\t\t\t")
self.angle_checkbox_topo = checkbox(text="Show angles", bind=self.update_visibility_angle, checked=False, mode = "topo")
scene.append_to_caption("\t\t\t\t\t\t\t")
# Display bifurcations and control points
self.angle_checkbox_model = checkbox(text="Show angles", bind=self.update_visibility_angle, checked=False, mode = "model")
scene.append_to_caption("\t")
self.furcation_checkbox = checkbox(text="Show furcations", bind=self.update_visibility_furcations, checked=False)
scene.append_to_caption('\t\tDisplay ')
self.mesh_representation_menu = menu(choices = ['default', 'wireframe', 'sections', 'solid'], selected = 'default', index=0, bind = self.update_mesh_representation)
scene.append_to_caption('\n')
# Transparency slides
self.opacity_sliders = {'full' : slider(bind = self.update_opacity_state, value = 1, length = slider_length, width = slider_width, right = slider_right_margin)}
#self.opacity_sliders['topo'] = slider(bind = self.update_opacity_state, value = 1, length = slider_length, width = slider_width, right = slider_right_margin - 3)
scene.append_to_caption('\t\t\t\t\t\t\t\t\t\t')
self.opacity_value = {'full' : 1}
self.control_pts_checkbox = checkbox(text="Show ctrl pts", bind=self.update_visibility_control_pts, checked=False)
scene.append_to_caption("\t")
self.control_radius_checkbox = checkbox(text="Show ctrl radius", bind=self.update_visibility_control_radius, checked=False)
# Size sliders
scene.append_to_caption('\nEdge radius\t\t\t\t\t\t\t\tEdge radius\t\t\t\t\t\t\t\tEdge radius\t\t\t\t\t\t\t\tEdge radius\n')
self.edge_size_sliders = {'full' : slider(bind = self.update_edge_size, value = 0.2, min=0, max = 0.5, length=slider_length, width = slider_width, right = slider_right_margin, mode = "full")}
self.edge_size_sliders['topo'] = slider(bind = self.update_edge_size, value = 0.2, min=0, max = 0.5, length=slider_length, width = slider_width, right = slider_right_margin, mode = "topo")
self.edge_size_sliders['model'] = slider(bind = self.update_edge_size, value = 0.2, min=0, max = 0.5, length=slider_length, width = slider_width, right = slider_right_margin, mode = "model")
self.edge_size_sliders['mesh'] = slider(bind = self.update_edge_size, value = 0.02, min=0, max = 0.1, length=slider_length, width = slider_width, right = slider_right_margin, mode = "mesh")
self.edge_size = {'full' : 0.2, 'topo' : 0.2, 'model': 0.2, 'mesh' : 0.02}
scene.append_to_caption('\nResample\t\t\t\t\t\t\t\tNode radius\t\t\t\t\t\t\t\tNode radius\n')
self.node_size_sliders = {'full' : slider(bind = self.resample_nodes, value = 1, min=0, max = 1, length=slider_length, width = slider_width, left= 10, right = slider_right_margin -10, mode = "full")}
self.node_size_sliders['topo'] = slider(bind = self.update_node_size, value = 0.5, min=0, max = 1, length=slider_length, width = slider_width, left= 10, right = slider_right_margin -10, mode = "topo")
self.node_size_sliders['model'] = slider(bind = self.update_node_size, value = 0.5, min=0, max = 1, length=slider_length, width = slider_width, right = slider_right_margin, mode = "model")
self.node_size = {'topo' : 0.5, 'model' : 0.5}
scene.append_to_caption('Nb nodes (nx8) ')
self.parameters_winput = {'N' : winput(text=str(48), bind = self.update_mesh_parameters, width=50, parameter = 'N')}
scene.append_to_caption('\tSection density [0,1] ')
self.parameters_winput['d'] = winput(text=str(0.25), bind = self.update_mesh_parameters, width=50, parameter = 'd')
scene.append_to_caption('\n')
scene.append_to_caption('\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t')
self.smooth_checkboxes = {'spatial' : checkbox(text= "Smooth spatial ", bind = self.select_smooth_parameter, checked = False, parameter = 'spatial')}
self.smooth_checkboxes['radius'] = checkbox(text= "Smooth radius", bind = self.select_smooth_parameter, checked = False, parameter = 'radius')
scene.append_to_caption('\t\t\t Layer size : a ')
self.parameters_winput['a'] = winput(text=str(0.2), bind = self.update_mesh_parameters, width=50, parameter = 'a')
scene.append_to_caption(' b ')
self.parameters_winput['b'] = winput(text=str(0.4), bind = self.update_mesh_parameters, width=50, parameter = 'b')
scene.append_to_caption(' c ')
self.parameters_winput['c'] = winput(text=str(0.4), bind = self.update_mesh_parameters, width=50, parameter = 'c')
scene.append_to_caption('\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t')
self.lbds = 0
scene.append_to_caption('Lbd spatial : ')
self.lbds_text = wtext(text="")
self.lbdr = 0
scene.append_to_caption('\t\tLbd radius : ')
self.lbdr_text = wtext(text="")
scene.append_to_caption('\t\t\t\t Nb layers : num_a ')
self.parameters_winput['num_a'] = winput(text=str(4), bind = self.update_mesh_parameters, width=50, parameter = 'num_a')
scene.append_to_caption(' num_b ')
self.parameters_winput['num_b'] = winput(text=str(4), bind = self.update_mesh_parameters, width=50, parameter = 'num_b')
scene.append_to_caption('\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t')
# Widget to add pathologies to the network
self.pathology_checkbox = checkbox(text= "Add pathology", bind = self.locate_pathology, checked = False)
self.pathology_markers = [sphere(pos=scene.center, color=color.yellow, radius=0.3, mode = "marker", visible = False, locked = False), sphere(pos=scene.center, color=color.yellow, radius=0.3, mode = "marker", visible = False, locked = False)]
self.pathology_edg = None
scene.append_to_caption(' ')
self.pathology_directory_winput = winput(text="pathology_templates/default/", bind = self.load_pathology_template, width=200)
self.template = None
self.load_pathology_template() # Load the default pathology
self.pathology = []
self.pathology_output_dir = "pathology_templates/new_template/"
scene.append_to_caption('\t Target mesh path ')
self.parameters_winput['path'] = winput(text="", bind = self.update_mesh_parameters, width=200, parameter = 'path')
self.target_mesh = None
scene.append_to_caption('\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t')
scene.append_to_caption('Max distance : coords ')
self.parameters_winput['max_coords'] = winput(text=str(6), bind = self.update_mesh_parameters, width=50, parameter = 'max_coords')
scene.append_to_caption(' radius ')
self.parameters_winput['max_radius'] = winput(text=str(1), bind = self.update_mesh_parameters, width=50, parameter = 'max_radius')
# Model default parameters
self.max_coords = 6
self.max_radius = 1
# Meshing default parameters
self.N = 48 # Number of nodes in one cross section (nx8)
self.d = 0.25 # Density of cross sections
self.a = 0.2
self.b = 0.4
self.c = 0.4
self.num_a = 4
self.num_b = 4
self.mesh_display_limit = 40000
# Display parameters
self.display_spline_step = 10 # Step for displaying spline points
self.temp_num_nds = 50 # Number of nodes in the template for pathology
self.temp_num_crsec = 10 # Number of crsec in the template for pathology
self.temp_rad = 10 # Radius of the template cross sections
self.temp_center = scene.center # position of the center
# Link actions to functions
scene.bind('click', self.select)
scene.bind('mousemove', self.move)
scene.bind('mouseup', self.drop)
scene.bind('keydown', self.keyboard_control)
# Storing the selected edges and nodes
self.selected_node = None
self.selected_edge = None
# Draging and running state attributes
self.drag = False
self.running = False
self.edge_drag = False
self.edge_n_id = None
# Storing of the elements to display
self.trash_elements = {'curves' : [], 'quads' : []}
self.modified_elements = {'splines' : []}
self.modified = {"off" : False, "full" : False, "topo" : False, "model" : False, "mesh" : False, "pathology" : False, "crop" : False}
# Disable elements
self.disable(True, checkboxes = False)
# Generate full graph
self.create_elements('full')
self.disable(False, ["full"])
self.create_template_pathology()
###########################################
################ VISIBILITY ###############
###########################################
def reset_scene(self):
# Import tree
file = self.centerline_file_winput.text
if file[-4:] == ".swc" or file[-4:] == ".vtp" or file[-4:] == ".txt":
tree = ArterialTree("Unknown", "Unknown", file)
elif file[-4:] == ".obj":
f = open(file, 'rb')
tree = pickle.load(f)
else:
tree = None
self.output_message("The input centerline file does not exist or have a wrong extension. The extension supported are .swc, .vtp, .txt, .obj.", "error")
if tree is not None:
self.tree = tree
# Erase objects
self.hide("full")
self.hide("topo")
self.hide("model")
self.hide("mesh")
# Reset buttons
self.tree = tree
self.barycenter = self.barycenter_finder()
scene.center = vector(self.barycenter[0], self.barycenter[1], self.barycenter[2])
self.elements = {'full' : {}, 'topo' : {}, 'model' : {}, 'mesh' : {}}
self.edition_menu.selected = 'off'
self.edition_mode = 'off'
self.checkboxes['full'].checked = True
self.checkboxes['topo'].checked = False
self.checkboxes['model'].checked = False
self.checkboxes['mesh'].checked = False
self.node_size_sliders['topo'].value = 0.5
self.node_size_sliders['model'].value = 0.5
self.node_size = {'topo' : 0.5, 'model' : 0.5}
self.disable(True, checkboxes = False)
# Generate full graph
self.create_elements('full')
self.disable(False, ["full"])
self.output_message("Input centerline successfully imported from " + file + ".")
def do_nothing(self):
pass
def node_color(self, n, mode):
""" Returns the node color, depending on the mode"""
try:
if mode == 'full' or mode=="data":
res = color.red
else:
if mode =='topo':
G = self.tree.get_topo_graph()
else:
G = self.tree.get_model_graph()
typ = G.nodes[n]['type']
if typ == 'end' and G.in_degree(n) == 0:
typ = 'inlet'
col = {'end' : color.blue, 'inlet' : color.orange, 'bif' : color.red, 'reg' : color.green, 'sep': color.purple, 'sink' : color.green}
res = col[typ]
except:
res = color.black
return res
def barycenter_finder(self, edg = []):
""" Finds the scene barycenter by averaging the network nodes """
if len(edg) == 0:
coords = list(nx.get_node_attributes(self.tree.get_full_graph(), 'coords').values())
barycenter = sum(coords) / len(coords)
return barycenter[:3]
else:
topo = self.tree.get_topo_graph()
sm = np.array([0,0,0,0])
num = 0
for e in edg:
sm = sm + np.sum(topo.edges[e]['coords'], axis=0)
num += len(topo.edges[e]['coords'])
return sm[:3]/num
def crop_network(self, b):
""" Crop network to the selected edges TMP VERSION """
if not b.activated:
# Lock everything
if len(self.crop_selection) == 0:
self.output_message("Please select one or more edges from the crop menu first.", "warning")
else:
self.lock("full")
#self.lock("topo")
# Unlock only the selected edges, if the representation checkbox is checked
for e in self.crop_selection:
topo_edg = [t for t in self.tree.get_topo_graph().edges()]
if e not in topo_edg:
print("This edge does not exist.")
#self.elements['topo']['nodes'][e[0]].locked = False
#self.elements['topo']['nodes'][e[1]].locked = False
#self.elements['topo']['edges'][e].locked = False
# Get full id
ids = self.tree.get_topo_graph().edges[e]['full_id']
id0 = self.tree.get_topo_graph().nodes[e[0]]['full_id']
id1 = self.tree.get_topo_graph().nodes[e[1]]['full_id']
self.elements['full']['nodes'][id0].locked = False
self.elements['full']['edges'][(id0, ids[0])].locked = False
for i in range(len(ids)-1):
self.elements['full']['nodes'][ids[i]].locked = False
self.elements['full']['edges'][(ids[i], ids[i+1])].locked = False
self.elements['full']['nodes'][ids[len(ids)-1]].locked = False
self.elements['full']['edges'][(ids[len(ids)-1], id1)].locked = False
self.elements['full']['nodes'][id1].locked = False
# Hide and show all
self.hide("full")
#self.hide("topo")
if self.checkboxes["full"].checked:
self.show("full")
#if self.checkboxes["topo"].checked:
#self.show("topo")
# Recompute barycenter
barycenter = self.barycenter_finder(edg = self.crop_selection)
scene.center = vector(barycenter[0], barycenter[1], barycenter[2])
self.cursor.pos=scene.center
b.activated = True
b.text = "Uncrop"
else:
self.unlock("full")
#self.unlock("topo")
if self.checkboxes["full"].checked:
self.show("full")
#if self.checkboxes["topo"].checked:
# self.show("topo")
scene.center = vector(self.barycenter[0], self.barycenter[1], self.barycenter[2])
self.cursor.pos=scene.center
b.activated = False
#self.crop_selection = []
b.text = " Crop "
def get_closest_data_point(self, coords, n):
# Get the id of the closest data point AMONG THE VISIBLE NODES after projection on the plane of given normal
pos = []
ids = []
for sph in self.elements["full"]["nodes"].values():
if not sph.locked:
pos.append([sph.pos.x, sph.pos.y, sph.pos.z])
ids.append(sph.id)
pos = np.array(pos)
# Project all coords to the same plane
tmp = np.array([0,0,1])
u1 = cross(n, tmp)
u2 = cross(u1, n)
# u1 and u2 are a basis of the plane
proj = np.zeros((pos.shape[0], 2))
for i in range(pos.shape[0]):
proj[i, 0] = dot(pos[i, :], u1)
proj[i, 1] = dot(pos[i, :], u2)
proj_pt = np.array([dot(coords, u1), dot(coords, u2)])
kdtree = KDTree(proj)
d, idx = kdtree.query(proj_pt)
idx = ids[idx]
return self.elements["full"]["nodes"][idx]
def update_visibility_state(self, b):
""" Show / hide network representation when the corresponding checkbox is checked / unchecked. """
mode = b.mode
if self.modified[mode] and not b.checked:
# Do nothing as the changes must be validated
b.checked = True
self.output_message("Please apply the modifications by clicking 'Apply' before leaving this representation mode.","error")
else:
if mode == 'model':
categories = ['edges', 'nodes']
elif mode == 'topo':
categories = ['edges', 'nodes']
else:
categories = []
if b.checked:
self.show(mode, categories)
if mode == "model":
self.update_visibility_furcations()
self.update_visibility_control_pts()
self.update_visibility_control_radius()
if self.angle_checkbox_model.checked:
self.update_visibility_angle(self.angle_checkbox_model)
if mode == "topo":
if self.angle_checkbox_topo.checked:
self.update_visibility_angle(self.angle_checkbox_topo)
self.disable(False, [mode], checkboxes = False)
else:
self.hide(mode)
self.disable(True, [mode], checkboxes = False)
def show_mesh_selection(self, show):
""" Show / hide the edges selected for meshing. """
for e in self.mesh_selection:
if show:
self.elements['model']['edges'][e].color = color.red
else:
self.elements['model']['edges'][e].color = color.black
def show_crop_selection(self, show):
""" Show / hide the edges selected for meshing. """
for e in self.crop_selection:
if show:
self.elements['topo']['edges'][e].color = color.red
else:
self.elements['topo']['edges'][e].color = color.black
def update_visibility_cursor(self):
self.cursor.visible = self.cursor_checkbox.checked
def update_visibility_slice(self):
self.slice.visible = self.slice_checkbox.checked
def load_image(self):
filename = self.image_file_winput.text
try:
if len(filename) == 0:
self.output_message("No image directory found. Please write the path in the text box and hit enter.", "warning")
else:
# Load image
self.image = nib.load(filename)
self.output_message("Image loaded from " + filename + ".")
self.slice_button.disabled = False
except FileNotFoundError:
self.output_message("The output directory does not exist.", "error")
def compute_slice(self):
""" Return a MRA image patch oriented normally to the artery tangent.
Keyword arguments:
img -- image volume as np array
pix_dim -- dimension of img (mm)
pt -- origin coordinates (mm)
tg -- unit tangent vector
dim -- patch dimension (vx)
dist -- patch dimension (mm)
"""
outfolder = "img/"
try:
os.makedirs(outfolder)
except OSError as error:
pass
def fill_patch(img, c):
if c[0] > 0 and c[0]<img.shape[0] and c[1] > 0 and c[1] < img.shape[1] and c[2] > 0 and c[2] < img.shape[2]:
return img[c[0], c[1], c[2]]
else:
return 0
self.output_message("Cutting slice in the medical image.")
self.disable(True, checkboxes = True)
img = np.array(self.image.dataobj)
pix_dim = self.image.header['pixdim'][1:4]
dim = 20
dist = 20
if self.selected_node is None:
center = self.cursor.pos
else:
center = self.selected_node.pos
vec_norm = scene.camera.axis
self.slice_plane[0] = vec_norm
self.slice_plane[1] = center
pt = np.array([center.x, center.y, center.z])
tg = np.array([vec_norm.x, vec_norm.y, vec_norm.z])
tg = tg/norm(tg)
nr = cross(np.array([0, 0.1, 0.9]), tg) # Normal vector
bnr = cross(tg, nr) # Binormal vector
nr = nr / norm(nr) # Normalize
bnr = bnr / norm(bnr)
# Coord conversion
patch_pix = np.array([float(dist) / float(dim)]*2)
step = np.linspace(0, dist, dim + 1)[1:]
patch = np.zeros((dim * 2 + 1, dim * 2 + 1))
ct = (pt / pix_dim).astype(int)
patch[dim, dim] = img[ct[0], ct[1], ct[2]]
# Fill patch
for j in range(dim):
# Fill cross
c1 = ((pt - nr * step[::-1][j]) / pix_dim).astype(int)
c2 = ((pt + nr * step[j]) / pix_dim).astype(int)
c3 = ((pt - bnr * step[::-1][j]) / pix_dim).astype(int)
c4 = ((pt + bnr * step[j]) / pix_dim).astype(int)
patch[dim, j] = fill_patch(img, c1)
patch[dim, dim + 1 + j] = fill_patch(img, c2)
patch[j, dim] = fill_patch(img, c3)
patch[dim + 1 + j, dim] = fill_patch(img, c4)
for j in range(dim):
c1mm = (pt - nr * step[::-1][j])
c2mm = (pt + nr * step[j])
c1 = (c1mm / pix_dim).astype(int)
c2 = (c2mm / pix_dim).astype(int)
patch[dim + 1, j] = fill_patch(img, c1)
patch[dim + 1, dim + 1 + j] = fill_patch(img, c2)
for k in range(dim):
c3 = ((c1mm - bnr * step[::-1][k]) / pix_dim).astype(int)
c4 = ((c1mm + bnr * step[k]) / pix_dim).astype(int)
c5 = ((c2mm - bnr * step[::-1][k]) / pix_dim).astype(int)
c6 = ((c2mm + bnr * step[k]) / pix_dim).astype(int)
patch[k, j] = fill_patch(img, c3)
patch[dim + 1 + k, j] = fill_patch(img, c4)
patch[k, dim + 1 + j] = fill_patch(img, c5)
patch[dim + 1 + k, dim + 1 + j] = fill_patch(img, c6)
# Write the image
pos1 = pt - bnr * dist - nr * dist
pos2 = pt + bnr * dist - nr * dist
pos3 = pt + bnr * dist + nr * dist
pos4 = pt - bnr * dist + nr * dist
if self.slice is None:
imt.imsave(outfolder + "image.jpg", patch, cmap='gray')
v1 = vertex(pos=vector(pos1[0],pos1[1],pos1[2]), normal=vector(0,0,1), texpos=vector(0,1,0), shininess= 0, opacity = self.slice_opacity_slider.value)
v2 = vertex(pos=vector(pos2[0],pos2[1],pos2[2]), normal=vector(0,0,1), texpos=vector(0,0,0), shininess= 0, opacity = self.slice_opacity_slider.value)
v3 = vertex(pos=vector(pos3[0],pos3[1],pos3[2]), normal=vector(0,0,1), texpos=vector(1,0,0), shininess= 0, opacity = self.slice_opacity_slider.value)
v4 = vertex(pos=vector(pos4[0],pos4[1],pos4[2]), normal=vector(0,0,1), texpos=vector(1,1,0), shininess= 0, opacity = self.slice_opacity_slider.value)
Q = quad(vs=[v1, v2, v3, v4], texture=outfolder + "image.jpg", locked = False)
self.slice = Q
self.nb_im = 0
else:
self.nb_im = self.nb_im + 1
imt.imsave(outfolder + "image" + str(self.nb_im) +".jpg", patch, cmap='gray')
self.slice.vs[0].pos = vector(pos1[0],pos1[1],pos1[2])
self.slice.vs[1].pos = vector(pos2[0],pos2[1],pos2[2])
self.slice.vs[2].pos = vector(pos3[0],pos3[1],pos3[2])
self.slice.vs[3].pos = vector(pos4[0],pos4[1],pos4[2])
self.slice.texture = outfolder + "image" + str(self.nb_im) +".jpg"
#self.slice = quad(vs=self.slice.vs, texture='image2.jpg')
self.disable(False, checkboxes = True)
self.slice_checkbox.disabled = False
self.slice_checkbox.checked = True
def slice_opacity(self):
alpha = self.slice_opacity_slider.value
self.slice.vs[0].opacity = alpha
self.slice.vs[1].opacity = alpha
self.slice.vs[2].opacity = alpha
self.slice.vs[3].opacity = alpha
def create_template_pathology(self):
# Create image slice (as mesh in pyvista)
# Use barycenter as center and camera axis as normal
# Create the crsec outline with a curve + prec curve + baseline curve
center = np.array([self.temp_center.x, self.temp_center.y, self.temp_center.z])
outline_coords = np.zeros((self.temp_num_nds,3))
angle = 2 * pi / self.temp_num_nds
angle_list = angle * np.arange(self.temp_num_nds)
nds = np.zeros((self.temp_num_nds, 3))
for i in range(self.temp_num_nds):
vec = rotate_vector(np.array([0,1,0]), np.array([0,0,1]), angle_list[i])
outline_coords[i, :] = center + vec * (self.temp_rad)
outline = curve(color = color.black, radius = 0.1, mode = "pathology", visible = False, locked = False, category = "outline")
previous = []
current = curve(color = color.red, radius = 0.1, mode = "pathology", visible = False, locked = False, category = "current")
gray_color = np.linspace(0.1, 1, self.temp_num_crsec)[::-1]
for i in range(self.temp_num_crsec):
previous.append(curve(color = color.gray(gray_color[i]), radius = 0.1, mode = "pathology", visible = True, locked = False, category = "previous"))
current_point = []
for i in range(len(outline_coords)):
pos = vector(outline_coords[i, 0], outline_coords[i, 1], outline_coords[i, 2])
outline.append(pos)
current.append(pos)
current_point.append(sphere(pos=pos, color=color.red, radius=0.2, mode = "pathology", category = "current", id = i, visible = False, locked = False))
outline.append(outline.point(0)['pos'])
current.append(current.point(0)['pos'])
self.pathology.append(np.vstack((outline_coords,outline_coords[0, :]))) # The stenosis start with a cicle shape to preserve the smoothness
self.elements['pathology']['edges'] = [outline, previous, current]
self.elements['pathology']['nodes'] = current_point
self.elements['pathology']['text'] = [label(pos=scene.center, text="crsec number " + str(len(self.pathology)) + " / " + str(self.temp_num_crsec), box = False, visible = False, locked = False)]
def show_hide_template(self, show = True):
if show:
# Hide everything (without unchecking boxes)
self.hide("full")
self.hide("topo")
self.hide("model")
self.hide("mesh")
if self.slice is not None:
self.slice.visible = False
self.cursor.visible = False
# Show the template
self.show("pathology")
self.output_message("Move the points to edit the current cross section. Press 'n' to move to the next cross section.")
else:
# Hide the slice
self.hide("pathology")
# Show the elements if the boxes are checked
for mode in ["full", "topo", "model", "mesh"]:
if self.checkboxes[mode].checked:
self.show(mode)
if mode == "model":
self.update_visibility_furcations()
self.update_visibility_control_pts()
self.update_visibility_control_radius()
if self.angle_checkbox_model.checked:
self.update_visibility_angle(self.angle_checkbox_model)
if mode == "topo":
if self.angle_checkbox_topo.checked:
self.update_visibility_angle(self.angle_checkbox_topo)
# Show the slice and cursor if the boxes are checked
if self.slice_checkbox.checked:
self.update_visibility_slice()
if self.cursor_checkbox.checked:
self.update_visibility_cursor()
def save_pathology_template(self):
# If the directory doesn't exist, create it
try:
os.makedirs(self.pathology_output_dir)
self.output_message("Saving the pathology template in " + self.pathology_output_dir)
except OSError as error:
self.output_message("Overwriting the pathology template in " + self.pathology_output_dir, "warning")
for i in range(len(self.pathology)):
num = str(i)
if len(num) == 1:
num = "0" + num
if len(num) == 2:
num = "0" + num
f = open(self.pathology_output_dir+ "crsec_" + num + ".txt", 'w')
# Write coordinates in file
for j in range(len(self.pathology[i])):
f.write(str(self.pathology[i][j, 0]) + "\t" + str(self.pathology[i][j, 1]) + "\t" + str(self.pathology[i][j, 2]) + "\n")
f.close()
# Write info file
f = open(self.pathology_output_dir + "info.txt", 'w')
f.write("center_x\tcenter_y\tcenter_z\tradius\n")
f.write(str(self.temp_center.x) + "\t" + str(self.temp_center.y) + "\t" + str(self.temp_center.z) +"\t" + str(self.temp_rad) + "\n")
f.close()
def next_template(self):
self.unselect("node")
def curve_to_coords(c):
n = c.npoints
coords = np.zeros((n, 3))
for i in range(c.npoints):
pos = c.point(i)["pos"]
coords[i,:] = np.array([pos.x, pos.y, pos.z])
return coords
def coords_to_curve(coords, c):
c.clear()
for i in range(len(coords)):
c.append(vec(coords[i, 0], coords[i, 1], coords[i, 2]))
if len(self.pathology) == self.temp_num_crsec:
self.show_hide_template(False)
# Reset all the curves
for i in range(self.temp_num_crsec):
self.elements["pathology"]["edges"][1][i].clear()
outline_coords = curve_to_coords(self.elements["pathology"]["edges"][0])
coords_to_curve(outline_coords, self.elements["pathology"]["edges"][-1])
self.elements['pathology']['text'][0].text = "crsec number " + str(1) + " / " + str(self.temp_num_crsec)
self.pathology.append(np.vstack((outline_coords,outline_coords[0, :])))
self.save_pathology_template()
self.pathology = [self.pathology[0]]
self.edition_mode = "off"
self.edition_menu.selected = "off"
self.unselect("node")
self.disable(disabled = False, checkboxes = True)
else:
# Save the current outline coords
current_coords = curve_to_coords(self.elements["pathology"]["edges"][-1])
self.pathology.append(current_coords)
# Modify the prec curve to keep track of previous outline
coords_to_curve(current_coords, self.elements["pathology"]["edges"][1][len(self.pathology)-2])
self.elements['pathology']['text'][0].text = "crsec number " + str(len(self.pathology)) + " / " + str(self.temp_num_crsec)
def locate_pathology(self, b):
if b.checked :
# Check if crsec graph exist
if self.tree.get_model_graph() is None:
self.output_message("Please compute the mesh before adding pathology.", "warning")
else:
if self.pathology_edg!= self.selected_edge.id:
self.pathology_edg = self.selected_edge.id
spl = self.tree.get_model_graph().edges[self.pathology_edg]["spline"]
pos1 = spl.point(0.2)
pos2 = spl.point(0.8)
self.pathology_markers[0].pos = vec(pos1[0], pos1[1], pos1[2])
self.pathology_markers[1].pos = vec(pos2[0], pos2[1], pos2[2])
self.pathology_markers[0].visible = True
self.pathology_markers[1].visible = True
self.modified["model"] = True
else:
self.pathology_markers[0].visible = False
self.pathology_markers[1].visible = False
def add_pathology(self):
pt0 = self.pathology_markers[0].pos
pt0 = np.array([pt0.x, pt0.y, pt0.z])
pt1 = self.pathology_markers[1].pos
pt1 = np.array([pt1.x, pt1.y, pt1.z])
spl = self.tree.get_model_graph().edges[self.pathology_edg]["spline"]
t0 = spl.project_point_to_centerline(pt0)
t1 = spl.project_point_to_centerline(pt1)
print(t0,t1)
self.tree.deform_surface_to_template(self.pathology_edg, t0, t1, self.template[0], self.template[1], self.template[2], rotate = 120)
def update_visibility_angle(self, checkbox):
if checkbox.checked: # Create angles labels
angles = self.tree.angle(None, mode=checkbox.mode)
if "angles" not in self.elements[checkbox.mode].keys():
self.elements[checkbox.mode]["angles"] = []
for a in angles:
L = label(pos=vec(a[1][0], a[1][1], a[1][2]), text=str(a[2])+ "°", box = False, locked = False)
self.elements[checkbox.mode]["angles"].append(L)
else:
for i in range(len(angles)):
a = angles[i]
if i < len(self.elements[checkbox.mode]["angles"]):
self.elements[checkbox.mode]["angles"][i].visible = True
self.elements[checkbox.mode]["angles"][i].pos = vec(a[1][0], a[1][1], a[1][2])
self.elements[checkbox.mode]["angles"][i].text = str(a[2])+ "°"
else:
L = label(pos=vec(a[1][0], a[1][1], a[1][2]), text=str(a[2])+ "°", box = False, locked = False)
self.elements[checkbox.mode]["angles"].append(L)
else: # Hide angle labels
for elt in self.elements[checkbox.mode]["angles"]:
elt.visible = False
def update_visibility_control_pts(self):
""" Show/ hide model control points """
if self.control_pts_checkbox.checked:
self.control_radius_checkbox.disabled = False
self.show('model', ['control_edges', 'control_nodes'])
else:
# Control point radius can be displayed only if the control points are already displayed
self.control_radius_checkbox.disabled = True
self.control_radius_checkbox.checked = False
self.hide('model',['control_edges', 'control_nodes'])
for k in self.elements["model"]["control_nodes"].keys():
for i in range(len(self.elements["model"]["control_nodes"][k])):
self.elements["model"]["control_nodes"][k][i].radius = 0.5
def update_visibility_control_radius(self):
""" Show/ hide model control points radius """
if self.control_radius_checkbox.checked: