-
Notifications
You must be signed in to change notification settings - Fork 0
/
demo.py
1866 lines (1548 loc) · 72.7 KB
/
demo.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 turtle import width
import pandas as pd
import numpy as np
import customtkinter as ctk
from tkinter import filedialog, messagebox
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.art3d import Line3D
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from Pose2Sim.skeletons import *
from Pose2Sim.filtering import *
from matplotlib.figure import Figure
import matplotlib
import os
from utils.data_loader import read_data_from_c3d, read_data_from_trc
from utils.data_saver import save_to_trc, save_to_c3d
from gui.EditWindow import EditWindow
from gui.marker_plot import MarkerPlot
from utils.mouse_handler import MouseHandler
from utils.trajectory import MarkerTrajectory
# Interactive mode on
plt.ion()
matplotlib.use('TkAgg')
class TRCViewer(ctk.CTk):
def __init__(self):
super().__init__()
self.title("TRC Viewer")
self.geometry("1920x1080")
# GUI 요소 초기화
self.top_bar = ctk.CTkFrame(self)
self.top_bar.pack(fill='x')
self.left_button_frame = ctk.CTkFrame(self.top_bar)
self.left_button_frame.pack(side='left')
self.main_content = ctk.CTkFrame(self)
self.main_content.pack(fill='both', expand=True, padx=10, pady=(0, 10))
# 기본 변수 초기화
self.marker_names = []
self.data = None
self.original_data = None
self.num_frames = 0
self.frame_idx = 0
self.canvas = None
self.selection_in_progress = False
self.outliers = {}
self.view_limits = None
self.is_z_up = True
# 마커 관련 속성 초기화
self.marker_last_pos = None
self.marker_pan_enabled = False
self.marker_canvas = None
self.marker_axes = []
self.marker_lines = []
self.show_names = False
self.pattern_selection_mode = False
self.pattern_markers = set()
self.current_marker = None
# 궤적 관련 속성 초기화
self.show_trajectory = False
self.trajectory_length = 10
self.trajectory_line = None
# 필터 타입 변수 초기화
self.filter_type_var = ctk.StringVar(value='butterworth')
# 초기화 순서 중요: mouse_handler는 marker_plotter보다 먼저 생성되어야 함
self.mouse_handler = MouseHandler(self)
self.marker_plotter = MarkerPlot(self)
# 보간 메소드 리스트 추가
self.interp_methods = [
'linear',
'polynomial',
'spline',
'nearest',
'zero',
'slinear',
'quadratic',
'cubic',
'pattern-based' # 11/05
]
# 보간 메소드 변수 초기화
self.interp_method_var = ctk.StringVar(value='linear')
self.order_var = ctk.StringVar(value='3')
self.available_models = {
'No skeleton': None,
'BODY_25B': BODY_25B,
'BODY_25': BODY_25,
'BODY_135': BODY_135,
'BLAZEPOSE': BLAZEPOSE,
'HALPE_26': HALPE_26,
'HALPE_68': HALPE_68,
'HALPE_136': HALPE_136,
'COCO_133': COCO_133,
'COCO': COCO,
'MPII': MPII,
'COCO_17': COCO_17
}
self.current_model = None
self.skeleton_pairs = []
self.pan_enabled = False
self.last_mouse_pos = None
self.is_playing = False
self.playback_speed = 1.0
self.animation_job = None
self.fps_var = ctk.StringVar(value="60")
self.current_frame_line = None
self.bind('<space>', lambda e: self.toggle_animation())
self.bind('<Return>', lambda e: self.toggle_animation())
self.bind('<Escape>', lambda e: self.stop_animation())
self.bind('<Left>', lambda e: self.prev_frame())
self.bind('<Right>', lambda e: self.next_frame())
self.create_widgets()
# initialize plot
self.create_plot()
self.update_plot()
self.edit_window = None
# Initialize trajectory handler
self.trajectory_handler = MarkerTrajectory()
# Keep these for compatibility with existing code
self.show_trajectory = False
self.trajectory_length = 10
self.trajectory_line = None
self.marker_lines = []
def create_widgets(self):
button_frame = ctk.CTkFrame(self.top_bar)
button_frame.pack(pady=10, padx=10, fill='x')
button_style = {
"fg_color": "#333333",
"hover_color": "#444444"
}
left_button_frame = ctk.CTkFrame(button_frame, fg_color="transparent")
left_button_frame.pack(side='left', fill='x')
self.reset_view_button = ctk.CTkButton(
left_button_frame,
text="🎥",
width=30,
command=self.reset_main_view,
**button_style
)
self.reset_view_button.pack(side='left', padx=5)
self.open_button = ctk.CTkButton(
left_button_frame,
text="Open TRC File",
command=self.open_file,
**button_style
)
self.open_button.pack(side='left', padx=5)
self.coord_button = ctk.CTkButton(
button_frame,
text="Switch to Y-up",
command=self.toggle_coordinates,
**button_style
)
self.coord_button.pack(side='left', padx=5)
self.names_button = ctk.CTkButton(
button_frame,
text="Hide Names",
command=self.toggle_marker_names,
**button_style
)
self.names_button.pack(side='left', padx=5)
self.trajectory_button = ctk.CTkButton(
button_frame,
text="Show Trajectory",
command=self.toggle_trajectory,
**button_style
)
self.trajectory_button.pack(side='left', padx=5)
self.save_button = ctk.CTkButton(
button_frame,
text="Save As...",
command=self.save_as,
**button_style
)
self.save_button.pack(side='left', padx=5)
self.model_var = ctk.StringVar(value='No skeleton')
self.model_combo = ctk.CTkComboBox(
button_frame,
values=list(self.available_models.keys()),
variable=self.model_var,
command=self.on_model_change
)
self.model_combo.pack(side='left', padx=5)
self.view_frame = ctk.CTkFrame(self.main_content, fg_color="black")
self.view_frame.pack(side='left', fill='both', expand=True)
self.right_panel = ctk.CTkFrame(self.main_content, fg_color="black")
self.right_panel.pack_forget() # 처음에는 숨김
self.right_panel.pack_propagate(False) # 크기 고정
viewer_top_frame = ctk.CTkFrame(self.view_frame)
viewer_top_frame.pack(fill='x', pady=(5, 0))
self.title_label = ctk.CTkLabel(viewer_top_frame, text="", font=("Arial", 14))
self.title_label.pack(side='left', expand=True)
canvas_container = ctk.CTkFrame(self.view_frame)
canvas_container.pack(fill='both', expand=True)
self.canvas_frame = ctk.CTkFrame(canvas_container)
self.canvas_frame.pack(expand=True, fill='both')
self.canvas_frame.pack_propagate(False)
self.control_frame = ctk.CTkFrame(
self,
border_width=1,
fg_color="#1A1A1A" # background color
)
self.control_frame.pack(fill='x', padx=10, pady=(0, 10))
# control button style
control_style = {
"width": 30,
"fg_color": "#333333",
"hover_color": "#444444"
}
# control button frame
button_frame = ctk.CTkFrame(self.control_frame, fg_color="transparent")
button_frame.pack(side='left', padx=5)
# play control buttons
self.play_pause_button = ctk.CTkButton(
button_frame,
text="▶",
command=self.toggle_animation,
**control_style
)
self.play_pause_button.pack(side='left', padx=2)
self.stop_button = ctk.CTkButton(
button_frame,
text="■",
command=self.stop_animation,
# state='disabled',
**control_style
)
self.stop_button.pack(side='left', padx=2)
# loop checkbox style
checkbox_style = {
"width": 60,
"fg_color": "#1A1A1A", # transparent instead of background color
"border_color": "#666666", # border color
"hover_color": "#1A1A1A", # hover color
"checkmark_color": "#00A6FF", # checkmark color
"border_width": 2 # border width
}
# loop checkbox
self.loop_var = ctk.BooleanVar(value=False)
self.loop_checkbox = ctk.CTkCheckBox(
button_frame,
text="Loop",
variable=self.loop_var,
text_color="#FFFFFF",
**checkbox_style
)
self.loop_checkbox.pack(side='left', padx=5)
# timeline menu frame
timeline_menu_frame = ctk.CTkFrame(self.control_frame, fg_color="transparent")
timeline_menu_frame.pack(side='left', padx=(5, 10))
# current frame/time display label
self.current_info_label = ctk.CTkLabel(
timeline_menu_frame,
text="0.00s",
font=("Arial", 14),
text_color="#FFFFFF"
)
self.current_info_label.pack(side='left', padx=5)
# mode selection button frame
mode_frame = ctk.CTkFrame(timeline_menu_frame, fg_color="#222222", corner_radius=6)
mode_frame.pack(side='left', padx=2)
# time/frame mode button
button_style = {
"width": 60,
"height": 24,
"corner_radius": 4,
"font": ("Arial", 11),
"fg_color": "transparent",
"text_color": "#888888",
"hover_color": "#333333"
}
self.timeline_display_var = ctk.StringVar(value="time")
self.time_btn = ctk.CTkButton(
mode_frame,
text="Time",
command=lambda: self.change_timeline_mode("time"),
**button_style
)
self.time_btn.pack(side='left', padx=2, pady=2)
self.frame_btn = ctk.CTkButton(
mode_frame,
text="Frame",
command=lambda: self.change_timeline_mode("frame"),
**button_style
)
self.frame_btn.pack(side='left', padx=2, pady=2)
# timeline figure
self.timeline_fig = Figure(figsize=(5, 0.8), facecolor='black')
self.timeline_ax = self.timeline_fig.add_subplot(111)
self.timeline_ax.set_facecolor('black')
# timeline canvas
self.timeline_canvas = FigureCanvasTkAgg(self.timeline_fig, master=self.control_frame)
self.timeline_canvas.get_tk_widget().pack(fill='x', expand=True, padx=5, pady=5)
# timeline event connection
self.timeline_canvas.mpl_connect('button_press_event', self.mouse_handler.on_timeline_click)
self.timeline_canvas.mpl_connect('motion_notify_event', self.mouse_handler.on_timeline_drag)
self.timeline_canvas.mpl_connect('button_release_event', self.mouse_handler.on_timeline_release)
self.timeline_dragging = False
# initial timeline mode
self.change_timeline_mode("time")
self.marker_label = ctk.CTkLabel(self, text="")
self.marker_label.pack(pady=5)
if self.canvas:
self.canvas.mpl_connect('button_press_event', self.mouse_handler.on_mouse_press)
self.canvas.mpl_connect('button_release_event', self.mouse_handler.on_mouse_release)
self.canvas.mpl_connect('motion_notify_event', self.mouse_handler.on_mouse_move)
def update_timeline(self):
if self.data is None:
return
self.timeline_ax.clear()
frames = np.arange(self.num_frames)
fps = float(self.fps_var.get())
times = frames / fps
# add horizontal baseline (y=0)
self.timeline_ax.axhline(y=0, color='white', alpha=0.3, linewidth=1)
display_mode = self.timeline_display_var.get()
light_yellow = '#FFEB3B'
if display_mode == "time":
# major ticks every 10 seconds
major_time_ticks = np.arange(0, times[-1] + 10, 10)
for time in major_time_ticks:
if time <= times[-1]:
frame = int(time * fps)
self.timeline_ax.axvline(frame, color='white', alpha=0.3, linewidth=1)
self.timeline_ax.text(frame, -0.7, f"{time:.0f}s",
color='white', fontsize=8,
horizontalalignment='center',
verticalalignment='top')
# minor ticks every 1 second
minor_time_ticks = np.arange(0, times[-1] + 1, 1)
for time in minor_time_ticks:
if time <= times[-1] and time % 10 != 0: # not overlap with 10-second ticks
frame = int(time * fps)
self.timeline_ax.axvline(frame, color='white', alpha=0.15, linewidth=0.5)
self.timeline_ax.text(frame, -0.7, f"{time:.0f}s",
color='white', fontsize=6, alpha=0.5,
horizontalalignment='center',
verticalalignment='top')
current_time = self.frame_idx / fps
current_display = f"{current_time:.2f}s"
else: # frame mode
# major ticks every 100 frames
major_frame_ticks = np.arange(0, self.num_frames, 100)
for frame in major_frame_ticks:
self.timeline_ax.axvline(frame, color='white', alpha=0.3, linewidth=1)
self.timeline_ax.text(frame, -0.7, f"{frame}",
color='white', fontsize=6, alpha=0.5,
horizontalalignment='center',
verticalalignment='top')
current_display = f"{self.frame_idx}"
# current frame display (light yellow line)
self.timeline_ax.axvline(self.frame_idx, color=light_yellow, alpha=0.8, linewidth=1.5)
# update label
self.current_info_label.configure(text=current_display)
# timeline settings
self.timeline_ax.set_xlim(0, self.num_frames - 1)
self.timeline_ax.set_ylim(-1, 1)
# hide y-axis
self.timeline_ax.set_yticks([])
# border style
self.timeline_ax.spines['top'].set_visible(False)
self.timeline_ax.spines['right'].set_visible(False)
self.timeline_ax.spines['left'].set_visible(False)
self.timeline_ax.spines['bottom'].set_color('white')
self.timeline_ax.spines['bottom'].set_alpha(0.3)
self.timeline_ax.spines['bottom'].set_color('white')
self.timeline_ax.spines['bottom'].set_alpha(0.3)
# hide x-axis ticks (we draw them manually)
self.timeline_ax.set_xticks([])
# adjust figure margins (to avoid text clipping)
self.timeline_fig.subplots_adjust(bottom=0.2)
self.timeline_canvas.draw_idle()
def on_model_change(self, choice):
try:
# Save the current frame
current_frame = self.frame_idx
# Update the model
self.current_model = self.available_models[choice]
# Update skeleton settings
if self.current_model is None:
self.skeleton_pairs = []
self.show_skeleton = False
else:
self.show_skeleton = True
self.update_skeleton_pairs()
# Remove existing skeleton lines
if hasattr(self, 'skeleton_lines'):
for line in self.skeleton_lines:
line.remove()
self.skeleton_lines = []
# Initialize new skeleton lines
if self.show_skeleton:
for _ in self.skeleton_pairs:
line = Line3D([], [], [], color='gray', alpha=0.9)
self.ax.add_line(line)
self.skeleton_lines.append(line)
# Re-detect outliers with new skeleton pairs
self.detect_outliers()
# Update the plot with the current frame data
self.update_plot()
self.update_frame(current_frame)
# If a marker is currently selected, update its plot
if hasattr(self, 'current_marker') and self.current_marker:
self.marker_plotter.show_marker_plot(self.current_marker)
# Refresh the canvas
if hasattr(self, 'canvas'):
self.canvas.draw()
self.canvas.flush_events()
except Exception as e:
print(f"Error in on_model_change: {e}")
import traceback
traceback.print_exc()
def update_skeleton_pairs(self):
"""update skeleton pairs"""
self.skeleton_pairs = []
if self.current_model is not None:
for node in self.current_model.descendants:
if node.parent:
parent_name = node.parent.name
node_name = node.name
# check if marker names are in the data
if (f"{parent_name}_X" in self.data.columns and
f"{node_name}_X" in self.data.columns):
self.skeleton_pairs.append((parent_name, node_name))
def open_file(self):
file_path = filedialog.askopenfilename(
filetypes=[("Motion files", "*.trc;*.c3d"), ("TRC files", "*.trc"), ("C3D files", "*.c3d"), ("All files", "*.*")]
)
if file_path:
try:
self.clear_current_state()
self.current_file = file_path
file_name = os.path.basename(file_path)
file_extension = os.path.splitext(file_path)[1].lower()
self.title_label.configure(text=file_name)
if file_extension == '.trc':
header_lines, self.data, self.marker_names, frame_rate = read_data_from_trc(file_path)
elif file_extension == '.c3d':
header_lines, self.data, self.marker_names, frame_rate = read_data_from_c3d(file_path)
else:
raise Exception("Unsupported file format")
self.num_frames = self.data.shape[0]
self.original_data = self.data.copy(deep=True)
self.calculate_data_limits()
self.fps_var.set(str(int(frame_rate)))
self.update_fps_label()
# frame_slider related code
self.frame_idx = 0
self.update_timeline()
self.current_model = self.available_models[self.model_var.get()]
self.update_skeleton_pairs()
self.detect_outliers()
self.create_plot()
self.reset_main_view()
self.update_plot()
# self.update_frame_counter()
if hasattr(self, 'canvas'):
self.canvas.draw()
self.canvas.flush_events()
self.play_pause_button.configure(state='normal')
# self.speed_slider.configure(state='normal')
self.loop_checkbox.configure(state='normal')
self.is_playing = False
self.play_pause_button.configure(text="▶")
self.stop_button.configure(state='disabled')
except Exception as e:
messagebox.showerror("Error", f"Failed to load file: {str(e)}")
def clear_current_state(self):
try:
if hasattr(self, 'fig'):
plt.close(self.fig)
del self.fig
if hasattr(self, 'marker_plot_fig'):
plt.close(self.marker_plot_fig)
del self.marker_plot_fig
if hasattr(self, 'canvas') and self.canvas:
self.canvas.get_tk_widget().destroy()
self.canvas = None
if hasattr(self, 'marker_canvas') and self.marker_canvas and hasattr(self.marker_canvas, 'get_tk_widget'):
self.marker_canvas.get_tk_widget().destroy()
del self.marker_canvas
self.marker_canvas = None
if hasattr(self, 'ax'):
del self.ax
if hasattr(self, 'marker_axes'):
del self.marker_axes
self.data = None
self.original_data = None
self.marker_names = None
self.num_frames = 0
self.frame_idx = 0
self.outliers = {}
self.current_marker = None
self.marker_axes = []
self.marker_lines = []
self.view_limits = None
self.data_limits = None
self.initial_limits = None
self.selection_data = {
'start': None,
'end': None,
'rects': [],
'current_ax': None,
'rect': None
}
# frame_slider related code
self.title_label.configure(text="")
self.show_names = False
self.show_skeleton = True
self.current_file = None
# timeline initialization
if hasattr(self, 'timeline_ax'):
self.timeline_ax.clear()
self.timeline_canvas.draw_idle()
except Exception as e:
print(f"Error clearing state: {e}")
def calculate_data_limits(self):
try:
x_coords = [col for col in self.data.columns if col.endswith('_X')]
y_coords = [col for col in self.data.columns if col.endswith('_Y')]
z_coords = [col for col in self.data.columns if col.endswith('_Z')]
x_min = self.data[x_coords].min().min()
x_max = self.data[x_coords].max().max()
y_min = self.data[y_coords].min().min()
y_max = self.data[y_coords].max().max()
z_min = self.data[z_coords].min().min()
z_max = self.data[z_coords].max().max()
margin = 0.1
x_range = x_max - x_min
y_range = y_max - y_min
z_range = z_max - z_min
self.data_limits = {
'x': (x_min - x_range * margin, x_max + x_range * margin),
'y': (y_min - y_range * margin, y_max + y_range * margin),
'z': (z_min - z_range * margin, z_max + z_range * margin)
}
self.initial_limits = self.data_limits.copy()
except Exception as e:
print(f"Error calculating data limits: {e}")
self.data_limits = None
self.initial_limits = None
def create_plot(self):
self.fig = plt.Figure(figsize=(10, 10), facecolor='black') # Changed to square figure
self.ax = self.fig.add_subplot(111, projection='3d')
self.ax.set_position([0.1, 0.1, 0.8, 0.8]) # Add proper spacing around plot
self._setup_plot_style()
self._draw_static_elements()
self._initialize_dynamic_elements()
if hasattr(self, 'canvas') and self.canvas:
self.canvas.get_tk_widget().destroy()
self.canvas = None
self.canvas = FigureCanvasTkAgg(self.fig, master=self.canvas_frame)
self.canvas.draw()
self.canvas.get_tk_widget().pack(fill='both', expand=True)
self.canvas.mpl_connect('scroll_event', self.mouse_handler.on_scroll)
self.canvas.mpl_connect('pick_event', self.mouse_handler.on_pick)
self.canvas.mpl_connect('button_press_event', self.mouse_handler.on_mouse_press)
self.canvas.mpl_connect('button_release_event', self.mouse_handler.on_mouse_release)
self.canvas.mpl_connect('motion_notify_event', self.mouse_handler.on_mouse_move)
if self.data is None:
# Set equal aspect ratio and limits
self.ax.set_xlim([-1, 1])
self.ax.set_ylim([-1, 1])
self.ax.set_zlim([-1, 1])
self.ax.set_box_aspect([1,1,1]) # Force equal aspect ratio
self.canvas.draw()
def _setup_plot_style(self):
self.ax.set_facecolor('black')
self.fig.patch.set_facecolor('black')
# 3D 축의 여백 제거
# self.ax.dist = 11 # 카메라 거리 조절
# self.fig.tight_layout(pad=10) # 여백 최소
self.fig.subplots_adjust(left=0.1, right=0.9, bottom=0.1, top=0.9) # Adjusted margins for better aspect ratio
for pane in [self.ax.xaxis.set_pane_color,
self.ax.yaxis.set_pane_color,
self.ax.zaxis.set_pane_color]:
pane((0, 0, 0, 1))
for axis in [self.ax.xaxis, self.ax.yaxis, self.ax.zaxis]:
axis.label.set_color('white')
axis.set_tick_params(colors='white')
self.ax.set_xticks([])
self.ax.set_yticks([])
self.ax.set_zticks([])
self.ax.set_xlabel('')
self.ax.set_ylabel('')
self.ax.set_zlabel('')
def _draw_static_elements(self):
"""Draw static elements like the ground grid based on the coordinate system."""
grid_size = 2
grid_divisions = 20
x = np.linspace(-grid_size, grid_size, grid_divisions)
y = np.linspace(-grid_size, grid_size, grid_divisions)
# Clear existing grid lines (if any)
if hasattr(self, 'grid_lines'):
for line in self.grid_lines:
line.remove()
self.grid_lines = []
# Draw grid based on coordinate system
# Z-up: Grid on X-Y plane at Z=0
for i in range(grid_divisions):
line1, = self.ax.plot(x, [y[i]] * grid_divisions, [0] * grid_divisions, 'gray', alpha=0.2)
line2, = self.ax.plot([x[i]] * grid_divisions, y, [0] * grid_divisions, 'gray', alpha=0.2)
self.grid_lines.extend([line1, line2])
def _initialize_dynamic_elements(self):
self._update_coordinate_axes()
if hasattr(self, 'markers_scatter'):
self.markers_scatter.remove()
if hasattr(self, 'selected_marker_scatter'):
self.selected_marker_scatter.remove()
self.markers_scatter = self.ax.scatter([], [], [], c='white', s=5, picker=5)
self.selected_marker_scatter = self.ax.scatter([], [], [], c='yellow', s=15)
if hasattr(self, 'skeleton_lines'):
for line in self.skeleton_lines:
line.remove()
self.skeleton_lines = []
if hasattr(self, 'skeleton_pairs') and self.skeleton_pairs:
for _ in self.skeleton_pairs:
line = Line3D([], [], [], color='gray', alpha=0.9)
self.ax.add_line(line)
self.skeleton_lines.append(line)
if hasattr(self, 'marker_labels'):
for label in self.marker_labels:
label.remove()
self.marker_labels = []
def _update_coordinate_axes(self):
"""Update coordinate axes and labels based on the coordinate system."""
# 축과 레이블 초기화
if hasattr(self, 'coordinate_axes'):
for line in self.coordinate_axes:
line.remove()
self.coordinate_axes = []
if hasattr(self, 'axis_labels'):
for label in self.axis_labels:
label.remove()
self.axis_labels = []
# axis settings
origin = np.zeros(3)
axis_length = 0.4
# axis colors
x_color = 'red'
y_color = 'yellow'
z_color = 'blue'
if self.is_z_up:
# draw main axes for Z-up coordinate system
# X-axis (red)
line_x = self.ax.plot([origin[0], origin[0] + axis_length],
[origin[1], origin[1]],
[origin[2], origin[2]],
color=x_color, alpha=0.8, linewidth=2)[0]
# Y-axis (yellow)
line_y = self.ax.plot([origin[0], origin[0]],
[origin[1], origin[1] + axis_length],
[origin[2], origin[2]],
color=y_color, alpha=0.8, linewidth=2)[0]
# Z-axis (blue)
line_z = self.ax.plot([origin[0], origin[0]],
[origin[1], origin[1]],
[origin[2], origin[2] + axis_length],
color=z_color, alpha=0.8, linewidth=2)[0]
# label position
label_x = self.ax.text(axis_length + 0.1, 0, 0, 'X', color=x_color, fontsize=12)
label_y = self.ax.text(0, axis_length + 0.1, 0, 'Y', color=y_color, fontsize=12)
label_z = self.ax.text(0, 0, axis_length + 0.1, 'Z', color=z_color, fontsize=12)
else:
# draw main axes for Y-up coordinate system (right-hand rule)
# X-axis (red)
line_x = self.ax.plot([origin[0], origin[0] + axis_length],
[origin[2], origin[2]],
[origin[1], origin[1]],
color=x_color, alpha=0.8, linewidth=2)[0]
# Z-axis (blue) - change direction
line_z = self.ax.plot([origin[0], origin[0]],
[origin[2], origin[2] - axis_length],
[origin[1], origin[1]],
color=z_color, alpha=0.8, linewidth=2)[0]
# Y-axis (yellow)
line_y = self.ax.plot([origin[0], origin[0]],
[origin[2], origin[2]],
[origin[1], origin[1] + axis_length],
color=y_color, alpha=0.8, linewidth=2)[0]
# label position
label_x = self.ax.text(axis_length + 0.1, 0, 0, 'X', color=x_color, fontsize=12)
label_z = self.ax.text(0, -axis_length - 0.1, 0, 'Z', color=z_color, fontsize=12)
label_y = self.ax.text(0, 0, axis_length + 0.1, 'Y', color=y_color, fontsize=12)
# save axes and labels
self.coordinate_axes = [line_x, line_y, line_z]
self.axis_labels = [label_x, label_y, label_z]
def update_plot(self):
if self.data is None:
return
# Update trajectories using the handler
if hasattr(self, 'trajectory_handler'):
self.trajectory_handler.update_trajectory(self.data, self.frame_idx, self.marker_names, self.ax)
# handle empty 3D space when data is None
if self.data is None:
# initialize markers and skeleton
if hasattr(self, 'markers_scatter'):
self.markers_scatter._offsets3d = ([], [], [])
if hasattr(self, 'selected_marker_scatter'):
self.selected_marker_scatter._offsets3d = ([], [], [])
self.selected_marker_scatter.set_visible(False)
if hasattr(self, 'skeleton_lines'):
for line in self.skeleton_lines:
line.set_data_3d([], [], [])
# set axis ranges
self.ax.set_xlim([-1, 1])
self.ax.set_ylim([-1, 1])
self.ax.set_zlim([-1, 1])
self.canvas.draw()
return
# remove existing trajectory line
if hasattr(self, 'trajectory_line') and self.trajectory_line is not None:
self.trajectory_line.remove()
self.trajectory_line = None
if self.current_marker is not None and self.show_trajectory:
x_vals = []
y_vals = []
z_vals = []
for i in range(0, self.frame_idx + 1):
try:
x = self.data.loc[i, f'{self.current_marker}_X']
y = self.data.loc[i, f'{self.current_marker}_Y']
z = self.data.loc[i, f'{self.current_marker}_Z']
if np.isnan(x) or np.isnan(y) or np.isnan(z):
continue
if self.is_z_up:
x_vals.append(x)
y_vals.append(y)
z_vals.append(z)
else:
x_vals.append(x)
y_vals.append(-z)
z_vals.append(y)
except KeyError:
continue
if len(x_vals) > 0:
self.trajectory_line, = self.ax.plot(x_vals, y_vals, z_vals, color='yellow', alpha=0.5, linewidth=1)
else:
self.trajectory_line = None
prev_elev = self.ax.elev
prev_azim = self.ax.azim
prev_xlim = self.ax.get_xlim()
prev_ylim = self.ax.get_ylim()
prev_zlim = self.ax.get_zlim()
# collect marker position data
positions = []
colors = []
alphas = []
selected_position = []
marker_positions = {}
valid_markers = []
# collect valid markers for the current frame
for marker in self.marker_names:
try:
x = self.data.loc[self.frame_idx, f'{marker}_X']
y = self.data.loc[self.frame_idx, f'{marker}_Y']
z = self.data.loc[self.frame_idx, f'{marker}_Z']
# skip NaN values or deleted data
if pd.isna(x) or pd.isna(y) or pd.isna(z):
continue
# add valid data
if self.is_z_up:
marker_positions[marker] = np.array([x, y, z])
positions.append([x, y, z])
else:
marker_positions[marker] = np.array([x, -z, y])
positions.append([x, -z, y])
# add colors and alphas for valid markers
if hasattr(self, 'pattern_selection_mode') and self.pattern_selection_mode:
if marker in self.pattern_markers:
colors.append('red')
alphas.append(0.3)
else:
colors.append('white')
alphas.append(1.0)
elif marker == self.current_marker:
colors.append('yellow')
alphas.append(1.0)
else:
colors.append('white')
alphas.append(1.0)
if marker == self.current_marker:
if self.is_z_up:
selected_position.append([x, y, z])
else:
selected_position.append([x, -z, y])
valid_markers.append(marker)
except KeyError:
continue
# array conversion
positions = np.array(positions) if positions else np.zeros((0, 3))
selected_position = np.array(selected_position) if selected_position else np.zeros((0, 3))
# update scatter plot - display valid data
if len(positions) > 0:
try:
# remove existing scatter
if hasattr(self, 'markers_scatter'):
self.markers_scatter.remove()
# create new scatter plot
self.markers_scatter = self.ax.scatter(
positions[:, 0],
positions[:, 1],
positions[:, 2],
c=colors[:len(positions)], # length match
alpha=alphas[:len(positions)], # length match
s=30,
picker=5
)
except Exception as e:
print(f"Error updating scatter plot: {e}")
# create default scatter plot if error occurs
if hasattr(self, 'markers_scatter'):
self.markers_scatter.remove()
self.markers_scatter = self.ax.scatter(
positions[:, 0],
positions[:, 1],
positions[:, 2],
c='white',
s=30,
picker=5
)
else:
# create empty scatter plot if data is None
if hasattr(self, 'markers_scatter'):
self.markers_scatter.remove()
self.markers_scatter = self.ax.scatter([], [], [], c='white', s=30, picker=5)
# update selected marker
if len(selected_position) > 0:
self.selected_marker_scatter._offsets3d = (
selected_position[:, 0],
selected_position[:, 1],
selected_position[:, 2]
)
self.selected_marker_scatter.set_visible(True)
else:
self.selected_marker_scatter._offsets3d = ([], [], [])
self.selected_marker_scatter.set_visible(False)