-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdataset_visualizer.py
More file actions
4378 lines (3718 loc) · 219 KB
/
dataset_visualizer.py
File metadata and controls
4378 lines (3718 loc) · 219 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
#!/usr/bin/env python3
"""
Qt-based visualizer for HUIInteract360 dataset
"""
import sys
import os
import argparse
import io
import numpy as np
import torch
import torch.nn as nn
import random
from scipy import ndimage
import cv2
import yaml
from datetime import datetime
SEED = 42
torch.manual_seed(SEED)
random.seed(SEED)
np.random.seed(SEED)
from typing import List, Dict, Optional, Tuple, Any
from collections import OrderedDict
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qtagg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.dates as mdates
from PIL import Image
from PyQt6.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QSlider, QPushButton, QCheckBox, QListWidget, QLabel, QSplitter,
QGroupBox, QGridLayout, QAbstractItemView, QListWidgetItem,
QScrollArea, QFrame, QMessageBox, QProgressBar, QStatusBar,
QComboBox, QSpinBox, QTextEdit, QTabWidget, QDoubleSpinBox,
QDialog, QDialogButtonBox,
QInputDialog, QFileDialog, QFormLayout, QButtonGroup, QRadioButton
)
from PyQt6.QtCore import Qt, QTimer, pyqtSignal, QThread, pyqtSlot, QRectF, QSize
from PyQt6.QtGui import (
QPixmap, QImage, QPainter, QPen, QColor, QFont, QKeySequence,
QShortcut, QBrush, QPainterPath, QPalette
)
from matplotlib.patches import Rectangle
from datasets.hui_norm_values import HUI_NORMALIZATION_VALUES
from datasets.HUIDatasetUtils import (
input_tensor_to_format_by_channel,
input_tensor_to_format_by_channel_sapiens_without_face,
keypoints17_to_coco18,
keypoints17_to_coco18_torch,
coco2h36m,
crop_scale_torch,
crop_scale_torch_by_sample,
coco2nwucla,
sapiensnoface2nturgbd_nospine_mid
)
# Add current directory to path for imports
here = os.path.dirname(__file__)
sys.path.append(here)
from datasets.HUIDataset import HUIInteract360
from utils.data_utils import VITPOSE_KEYPOINTS_NAMES, METADATA_COLUMNS, FULL_DATA_COLUMNS
from utils.print_utils import prInfo, prWarning, prError, prSuccess, prDebug
from utils.visualize_utils import RECORDINGS_LIST, VITPOSE_COLORS, GOLIATH_KPTS_COLORS, GOLIATH_KEYPOINTS_NAMES, GOLIATH_SKELETON_INFO, UNIQUE_PLACES_RECORDINGS
from predictors.mlp import MLPInteractionPredictor
from predictors.lstm import LSTMInteractionPredictor
from predictors.STG_NF.model_pose import STG_NF
from predictors.STGCN.net.st_gcn import Model as STGCN
from predictors.SkateFormer.model.SkateFormer import SkateFormer
from tools.create_config_files import FEATURES_SET_D1, FEATURES_SET_D2, FEATURES_SET_D3, FEATURES_SET_D4, FEATURES_SET_D5, FEATURES_SET_D6, FEATURES_SET_D7
from utils.debug_utils import update_old_config_dict
from sklearn.metrics import roc_auc_score, average_precision_score
from utils.eval_utils import get_best_threshold_f1
FEATURE_SET_DIC = {
"D1 (mask)": FEATURES_SET_D1,
"D2 (mask + box)": FEATURES_SET_D2,
"D3 (mask + box + vitpose)": FEATURES_SET_D3,
"D4 (mask + box + vitpose + sapiens)": FEATURES_SET_D4,
"D5 (mask + box + vitpose + facial)": FEATURES_SET_D5,
"D6 (mask + box + head/should)": FEATURES_SET_D6,
"D7 (mask + vitpose)": FEATURES_SET_D7
}
class DatasetWorker(QThread):
"""Worker thread for dataset creation to avoid blocking the UI"""
dataset_created = pyqtSignal(object, str) # dataset, message
error_occurred = pyqtSignal(str)
def __init__(self, config):
super().__init__()
self.config = config
def run(self):
dataset = HUIInteract360(allow_download=False, **self.config)
self.dataset_created.emit(dataset, f"Dataset created successfully! Length: {len(dataset)}")
prSuccess(f"Dataset created successfully! Length: {len(dataset)}")
prInfo("Visualized dataset statistics:")
print(f"\tDataset positives (number of tracks): {dataset.total_positives_tracks}")
print(f"\tDataset negatives (number of tracks): {dataset.total_negatives_tracks}")
print(f"\tDataset possible positives (number of segments): {dataset.total_possible_positives_segments}")
print(f"\tDataset possible negatives (number of segments): {dataset.total_possible_negatives_segments}")
print(f"\tDataset used positive segments: {dataset.total_used_positive_segments}")
print(f"\tDataset used negative segments: {dataset.total_used_negative_segments}")
class GraphWidget(QWidget):
"""Widget for displaying data plots with selectable columns"""
def __init__(self, raw_data_path):
super().__init__()
self.dataset = None
self.current_index = 0
self.current_data = None
self.dataset_stats = None
self.proba_sequence = None # Store probability sequence for current item
self.current_metadata = None # Store current metadata
self.raw_data_path = raw_data_path # Path to raw data directory
self.current_images_tensor = None # Store images tensor from dataset
self.current_masks_tensor = None # Store masks tensor from dataset
self.setup_ui()
def setup_ui(self):
layout = QVBoxLayout()
# Column selection controls
controls_layout = QHBoxLayout()
# Display mode selection (columns vs image)
display_mode_layout = QVBoxLayout()
display_mode_layout.addWidget(QLabel("Display Mode:"))
self.display_mode_combo = QComboBox()
self.display_mode_combo.addItems(["Select columns to plot", "Plot image (metadata)"])
self.display_mode_combo.currentTextChanged.connect(self.update_plot)
display_mode_layout.addWidget(self.display_mode_combo)
controls_layout.addLayout(display_mode_layout)
# Column selection list
self.column_list = QListWidget()
self.column_list.setSelectionMode(QAbstractItemView.SelectionMode.MultiSelection)
self.column_list.setMaximumHeight(150)
self.column_list.itemSelectionChanged.connect(self.update_plot)
controls_layout.addWidget(QLabel("Select columns to plot:"))
controls_layout.addWidget(self.column_list)
# Plot type selection
self.plot_type_combo = QComboBox()
self.plot_type_combo.addItems(["Line Plot", "Scatter Plot", "Bar Plot"])
self.plot_type_combo.currentTextChanged.connect(self.update_plot)
controls_layout.addWidget(QLabel("Plot type:"))
controls_layout.addWidget(self.plot_type_combo)
# Statistics display options
self.show_stats_checkbox = QCheckBox("Show Dataset Statistics")
self.show_stats_checkbox.setChecked(False)
self.show_stats_checkbox.toggled.connect(self.update_plot)
controls_layout.addWidget(self.show_stats_checkbox)
self.show_std_checkbox = QCheckBox("Show Standard Deviation")
self.show_std_checkbox.setChecked(True)
self.show_std_checkbox.toggled.connect(self.update_plot)
controls_layout.addWidget(self.show_std_checkbox)
layout.addLayout(controls_layout)
# Split layout for main graph and skeleton view
splitter = QSplitter(Qt.Orientation.Horizontal)
# Main graph canvas
self.figure = Figure(figsize=(3, 3))
self.canvas = FigureCanvas(self.figure)
splitter.addWidget(self.canvas)
# Skeleton view panel
skeleton_panel = QWidget()
skeleton_layout = QVBoxLayout()
# Skeleton controls
skeleton_controls = QVBoxLayout()
# Put skeleton checkboxes side by side
skeleton_type_layout = QHBoxLayout()
self.vitpose_skeleton_checkbox = QCheckBox("Show VitPose")
self.vitpose_skeleton_checkbox.setChecked(True)
self.vitpose_skeleton_checkbox.toggled.connect(self.update_skeleton)
skeleton_type_layout.addWidget(self.vitpose_skeleton_checkbox)
self.sapiens_skeleton_checkbox = QCheckBox("Show Sapiens")
self.sapiens_skeleton_checkbox.setChecked(False)
self.sapiens_skeleton_checkbox.toggled.connect(self.update_skeleton)
skeleton_type_layout.addWidget(self.sapiens_skeleton_checkbox)
self.free_scaleing_checkbox = QCheckBox("Free scale")
self.free_scaleing_checkbox.setChecked(False)
self.free_scaleing_checkbox.toggled.connect(self.update_skeleton)
skeleton_type_layout.addWidget(self.free_scaleing_checkbox)
self.show_bounding_box_checkbox = QCheckBox("Show BBox")
self.show_bounding_box_checkbox.setChecked(True)
self.show_bounding_box_checkbox.toggled.connect(self.update_skeleton)
skeleton_type_layout.addWidget(self.show_bounding_box_checkbox)
skeleton_controls.addLayout(skeleton_type_layout)
# Timestamp slider
self.timestamp_slider = QSlider(Qt.Orientation.Horizontal)
self.timestamp_slider.setRange(0, 0)
self.timestamp_slider.setValue(0)
self.timestamp_slider.valueChanged.connect(self.update_skeleton)
self.timestamp_slider.valueChanged.connect(self.update_plot) # Also update plot when slider changes (for image mode)
self.timestamp_slider.valueChanged.connect(self.update_image_display) # Update image display when slider changes
self.timestamp_label = QLabel("Frame: 0/0")
skeleton_controls.addWidget(QLabel("Timestamp:"))
skeleton_controls.addWidget(self.timestamp_slider)
skeleton_controls.addWidget(self.timestamp_label)
skeleton_layout.addLayout(skeleton_controls)
# Skeleton canvas
self.skeleton_figure = Figure(figsize=(3, 3))
self.skeleton_canvas = FigureCanvas(self.skeleton_figure)
skeleton_layout.addWidget(self.skeleton_canvas)
skeleton_panel.setLayout(skeleton_layout)
splitter.addWidget(skeleton_panel)
# Image display panel
image_panel = QWidget()
image_layout = QVBoxLayout()
# Image display label
image_label = QLabel("Image Display:")
image_layout.addWidget(image_label)
# Image canvas
self.image_figure = Figure(figsize=(3, 3))
self.image_canvas = FigureCanvas(self.image_figure)
image_layout.addWidget(self.image_canvas)
image_panel.setLayout(image_layout)
splitter.addWidget(image_panel)
# Set splitter proportions (main graph, skeleton, image)
splitter.setSizes([500, 250, 450])
layout.addWidget(splitter)
self.setLayout(layout)
def set_dataset(self, dataset):
"""Set the dataset to visualize"""
self.dataset = dataset
self.current_index = 0
if dataset is not None:
self.populate_column_list()
# self.update_current_data()
def set_current_index(self, index):
"""Set the current item index"""
self.current_index = index
# self.update_current_data()
def set_dataset_statistics(self, stats):
"""Set the dataset statistics for overlay display"""
self.dataset_stats = stats
self.update_plot()
def populate_column_list(self):
"""Populate the column list with available data columns"""
if self.dataset is None:
return
self.column_list.clear()
data_columns = self.dataset.data_columns_in_dataset
for col in data_columns:
item = QListWidgetItem(col)
self.column_list.addItem(item)
if col == "mask_size":
item.setSelected(True)
def update_current_data(self, input_tensor, label, metadata, images_tensor=None, masks_tensor=None):
"""Update the current data from the dataset"""
if self.dataset is None or len(self.dataset) == 0:
self.current_data = None
self.proba_sequence = None # Clear proba_sequence when no data
self.current_metadata = None
self.current_images_tensor = None
self.current_masks_tensor = None
return
# Store metadata and tensors
self.current_metadata = metadata
self.current_images_tensor = images_tensor
self.current_masks_tensor = masks_tensor
data_columns = self.dataset.data_columns_in_dataset
# Convert tensor to numpy and create DataFrame
input_data = input_tensor.numpy()
self.current_data = pd.DataFrame(input_data, columns=data_columns)
# Destandardize if enabled
self.destandardize_data()
# Add frame index as x-axis
self.current_data['frame_index'] = range(len(self.current_data))
# Update timestamp slider
max_frames = len(self.current_data) - 1
self.timestamp_slider.setRange(0, max_frames)
self.timestamp_slider.setValue(0)
# Update label with probability if available
if self.proba_sequence is not None and 0 < len(self.proba_sequence):
proba = self.proba_sequence[0]
if proba > -1:
proba_str = f"{proba:.3f}"
proba_percent = f"{proba*100:.0f}%"
self.timestamp_label.setText(f"Frame: 0/{max_frames} | Prob: {proba_str} ({proba_percent})")
else:
self.timestamp_label.setText(f"Frame: 0/{max_frames} | Prob: WAIT")
else:
self.timestamp_label.setText(f"Frame: 0/{max_frames}")
self.update_plot()
self.update_skeleton()
self.update_image_display()
def destandardize_data(self):
"""Destandardize the current data if destandardize is enabled"""
# Get DataVisualizationWidget (parent widget)
parent_widget = self.parent()
if parent_widget is None or not hasattr(parent_widget, 'destandardize_checkbox'):
self.destandardized = False
return
self.destandardized = True
# Check if destandardize is enabled
if not (parent_widget.destandardize_checkbox.isChecked() and
parent_widget.destandardize_checkbox.isEnabled()):
return
# Determine normalization suffix based on normalize_keypoints_in_box or normalize_keypoints_in_track from dataset
normalize_in_box = getattr(self.dataset, 'normalize_keypoints_in_box', False)
normalize_in_track = getattr(self.dataset, 'normalize_keypoints_in_track', "none")
if normalize_in_box:
norm_suffix = "_box_norm"
elif normalize_in_track != "none":
# norm_suffix = "_track_norm"
norm_suffix = "_image_norm"
# TODO : change this but for now we are using those values
else:
norm_suffix = "_image_norm"
# Destandardize mask size
if "mask_size" in self.current_data.columns and "mask_size_norm" in HUI_NORMALIZATION_VALUES:
norm_values = HUI_NORMALIZATION_VALUES["mask_size_norm"]
self.current_data["mask_size"] = (self.current_data["mask_size"] * norm_values["std"]) + norm_values["mean"]
# Destandardize bounding box coordinates
bbox_cols = ["xmin", "xmax", "ymin", "ymax"]
for col in bbox_cols:
if col in self.current_data.columns and col in HUI_NORMALIZATION_VALUES:
norm_values = HUI_NORMALIZATION_VALUES[col]
self.current_data[col] = (self.current_data[col] * norm_values["std"]) + norm_values["mean"]
# Destandardize VitPose keypoints
for kpt_name in VITPOSE_KEYPOINTS_NAMES:
for coord in ["x", "y"]:
col_name = f"vitpose_{kpt_name}_{coord}"
norm_col_name = f"{col_name}{norm_suffix}"
if col_name in self.current_data.columns and norm_col_name in HUI_NORMALIZATION_VALUES:
norm_values = HUI_NORMALIZATION_VALUES[norm_col_name]
self.current_data[col_name] = (self.current_data[col_name] * norm_values["std"]) + norm_values["mean"]
# Destandardize Sapiens keypoints
for kpt_name in GOLIATH_KEYPOINTS_NAMES:
for coord in ["x", "y"]:
col_name = f"sapiens_308_{kpt_name}_{coord}"
norm_col_name = f"{col_name}{norm_suffix}"
if col_name in self.current_data.columns and norm_col_name in HUI_NORMALIZATION_VALUES:
norm_values = HUI_NORMALIZATION_VALUES[norm_col_name]
self.current_data[col_name] = (self.current_data[col_name] * norm_values["std"]) + norm_values["mean"]
def update_plot(self):
"""Update the plot with selected columns or image"""
if self.current_data is None:
self.figure.clear()
self.canvas.draw()
return
# Check display mode
display_mode = self.display_mode_combo.currentText()
if display_mode == "Plot image (metadata)":
# Display image instead of plotting columns
self.plot_image()
return
# Original column plotting code
# Get selected columns
selected_columns = []
for i in range(self.column_list.count()):
if self.column_list.item(i).isSelected():
selected_columns.append(self.column_list.item(i).text())
if not selected_columns:
self.figure.clear()
self.canvas.draw()
return
# Clear the figure
self.figure.clear()
ax = self.figure.add_subplot(111)
# Get plot type
plot_type = self.plot_type_combo.currentText()
# Plot selected columns
x_data = self.current_data['frame_index']
colors = plt.cm.tab10(np.linspace(0, 1, len(selected_columns)))
# Plot dataset statistics first (as background)
if (self.dataset_stats is not None and
self.show_stats_checkbox.isChecked() and
plot_type == "Line Plot"): # Only show stats for line plots
for i, col in enumerate(selected_columns):
if col in self.dataset_stats['columns']:
col_idx = self.dataset_stats['columns'].index(col)
# Get statistics for this column
stats_means = self.dataset_stats['means'][:len(x_data), col_idx]
stats_stds = self.dataset_stats['stds'][:len(x_data), col_idx]
# Plot mean line
ax.plot(x_data, stats_means, '--', color=colors[i], alpha=0.7, linewidth=1,
label=f'{col} (dataset mean)')
# Plot standard deviation band if enabled
if self.show_std_checkbox.isChecked():
ax.fill_between(x_data,
stats_means - stats_stds,
stats_means + stats_stds,
color=colors[i], alpha=0.2,
label=f'{col} (±1 std)')
# Plot current data
for i, col in enumerate(selected_columns):
y_data = self.current_data[col]
if plot_type == "Line Plot":
ax.plot(x_data, y_data, label=col, color=colors[i], linewidth=2)
elif plot_type == "Scatter Plot":
ax.scatter(x_data, y_data, label=col, color=colors[i], alpha=0.7)
elif plot_type == "Bar Plot":
ax.bar(x_data, y_data, label=col, color=colors[i], alpha=0.7)
# Customize the plot
ax.set_xlabel('Frame Index')
ax.set_ylabel('Value')
ax.set_title(f'Data Visualization - Item {self.current_index + 1}')
ax.legend()
ax.grid(True, alpha=0.3)
# Adjust layout and refresh
self.figure.tight_layout()
self.canvas.draw()
def plot_image(self):
"""Plot the current image from metadata"""
if self.current_metadata is None or self.raw_data_path is None:
self.figure.clear()
ax = self.figure.add_subplot(111)
ax.text(0.5, 0.5, f'No metadata or raw data path available',
ha='center', va='center', transform=ax.transAxes)
self.canvas.draw()
return
# Get current frame index from timestamp slider
frame_idx = self.timestamp_slider.value()
# Extract metadata fields
try:
# Get unique_track_identifier and extract recording and episode from it
# Format: RECORDINGNAME_EPISODE_TRACKID (e.g., "rosbag2_2025_07_07-12_38_45_001_1")
unique_track_identifier = self.current_metadata["unique_track_identifier"]
# Handle different metadata formats
if isinstance(unique_track_identifier, torch.Tensor):
if unique_track_identifier.dim() > 0 and len(unique_track_identifier) > 0:
unique_track_identifier = unique_track_identifier[0].item()
else:
unique_track_identifier = unique_track_identifier.item()
elif isinstance(unique_track_identifier, (list, np.ndarray)):
if len(unique_track_identifier) > 0:
unique_track_identifier = unique_track_identifier[0]
else:
unique_track_identifier = ""
unique_track_identifier = str(unique_track_identifier)
# Extract recording and episode from unique_track_identifier
# Format: RECORDINGNAME_EPISODE_TRACKID
# Example: "rosbag2_2025_07_07-15_33_32_0029_1" -> recording="rosbag2_2025_07_07-15_33_32", episode="0029"
# Based on infer.py logic: recording is first 6 parts joined, episode is typically 4-digit number before track ID
parts = unique_track_identifier.rsplit("_", 2)
recording = parts[0]
episode = parts[1]
track_id = parts[2]
image_indexes = self.current_metadata["image_indexes"] # list of integer
# Convert to strings
recording = str(recording)
episode = str(episode)
video_dir = os.path.join(self.raw_data_path, "video_mini", recording, "episodes", episode)
# Construct image path
video_path = os.path.join(
video_dir,
"images_360_mini.mp4"
)
# Check if image exists
if not os.path.exists(video_path):
self.figure.clear()
ax = self.figure.add_subplot(111)
ax.text(0.5, 0.5, f'Image not found:\n{video_path}',
ha='center', va='center', transform=ax.transAxes, fontsize=10)
self.canvas.draw()
return
# Load and display image
# img = Image.open(image_path)
cap = cv2.VideoCapture(video_path)
cap.set(cv2.CAP_PROP_POS_FRAMES, image_indexes[frame_idx])
ret, frame = cap.read()
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
if not ret:
self.figure.clear()
ax = self.figure.add_subplot(111)
ax.text(0.5, 0.5, f'Error loading video:\n{video_path}',
ha='center', va='center', transform=ax.transAxes, fontsize=10)
self.canvas.draw()
return
self.figure.clear()
ax = self.figure.add_subplot(111)
ax.imshow(frame)
ax.axis('off')
ax.set_title(f'Frame {frame_idx}: {image_indexes[frame_idx]}')
# Set axis limits to match image dimensions
ax.set_xlim(0, frame.shape[1])
ax.set_ylim(frame.shape[0], 0) # Inverted y-axis to match image coordinates
# Check if shift was applied (do_recenter_interaction_zone was used)
shift_applied = self.current_metadata["shift_applied"]
interaction_zone_center_positions = self.current_metadata["interaction_zone_center_position"]
xmin_meta = self.current_metadata["xmin_meta"]
xmax_meta = self.current_metadata["xmax_meta"]
ymin_meta = self.current_metadata["ymin_meta"]
ymax_meta = self.current_metadata["ymax_meta"]
image_width = self.current_metadata["image_size"][0]
image_height = self.current_metadata["image_size"][1]
# Convert tensors to numpy arrays if needed
if xmin_meta is not None:
if isinstance(xmin_meta, torch.Tensor):
xmin_meta = xmin_meta.cpu().numpy()
elif isinstance(xmin_meta, list):
xmin_meta = np.array(xmin_meta)
if xmax_meta is not None:
if isinstance(xmax_meta, torch.Tensor):
xmax_meta = xmax_meta.cpu().numpy()
elif isinstance(xmax_meta, list):
xmax_meta = np.array(xmax_meta)
if ymin_meta is not None:
if isinstance(ymin_meta, torch.Tensor):
ymin_meta = ymin_meta.cpu().numpy()
elif isinstance(ymin_meta, list):
ymin_meta = np.array(ymin_meta)
if ymax_meta is not None:
if isinstance(ymax_meta, torch.Tensor):
ymax_meta = ymax_meta.cpu().numpy()
elif isinstance(ymax_meta, list):
ymax_meta = np.array(ymax_meta)
if interaction_zone_center_positions is not None:
if isinstance(interaction_zone_center_positions, torch.Tensor):
interaction_zone_center_positions = interaction_zone_center_positions.cpu().numpy()
elif isinstance(interaction_zone_center_positions, list):
interaction_zone_center_positions = np.array(interaction_zone_center_positions)
has_shift = (shift_applied is not None and interaction_zone_center_positions is not None)
# Draw original bounding box from metadata if shift was applied
if has_shift:
# Get original bounding box coordinates from metadata
orig_xmin = xmin_meta[frame_idx]/image_width * frame.shape[1]
orig_xmax = xmax_meta[frame_idx]/image_width * frame.shape[1]
orig_ymin = ymin_meta[frame_idx]/image_height * frame.shape[0]
orig_ymax = ymax_meta[frame_idx]/image_height * frame.shape[0]
if not (np.isnan(orig_xmin) or np.isnan(orig_xmax) or np.isnan(orig_ymin) or np.isnan(orig_ymax)):
orig_bbox_width = orig_xmax - orig_xmin
orig_bbox_height = orig_ymax - orig_ymin
# Draw original bounding box (green, solid, normal thickness)
orig_bbox_rect = Rectangle(
(orig_xmin, orig_ymin),
orig_bbox_width,
orig_bbox_height,
linewidth=3,
edgecolor='green',
facecolor='lightgreen',
alpha=0.3,
linestyle='-'
)
ax.add_patch(orig_bbox_rect)
# Draw bounding box if available in current_data (after destandardization/shifting)
if self.current_data is not None and frame_idx < len(self.current_data):
frame_data = self.current_data.iloc[frame_idx]
if 'xmin' in frame_data and 'xmax' in frame_data and 'ymin' in frame_data and 'ymax' in frame_data:
xmin = frame_data['xmin'] * frame.shape[1]
xmax = frame_data['xmax'] * frame.shape[1]
ymin = frame_data['ymin'] * frame.shape[0]
ymax = frame_data['ymax'] * frame.shape[0]
# Check if bounding box values are valid (not NaN)
if not (np.isnan(xmin) or np.isnan(xmax) or np.isnan(ymin) or np.isnan(ymax)):
# Calculate bounding box dimensions
bbox_width = xmax - xmin
bbox_height = ymax - ymin
# Draw shifted bounding box (if shift was applied, use dashed and thinner)
if has_shift:
# Shifted box: thinner, dashed line
bbox_rect = Rectangle(
(xmin, ymin),
bbox_width,
bbox_height,
linewidth=1.5,
edgecolor='green',
facecolor='none',
alpha=0.6,
linestyle='--'
)
else:
# Normal box: regular thickness, solid line
bbox_rect = Rectangle(
(xmin, ymin),
bbox_width,
bbox_height,
linewidth=3,
edgecolor='green',
facecolor='lightgreen',
alpha=0.3,
linestyle='-'
)
ax.add_patch(bbox_rect)
# Draw interaction zone center position icon at the bottom
if interaction_zone_center_positions is not None and len(interaction_zone_center_positions) > frame_idx:
iz_center_x = interaction_zone_center_positions[frame_idx]/image_width * frame.shape[1]
if isinstance(iz_center_x, torch.Tensor):
iz_center_x = iz_center_x.item()
if not np.isnan(iz_center_x) and iz_center_x >= 0:
# Convert to pixel coordinates
# interaction_zone_center_position is in pixel coordinates (not normalized)
if iz_center_x <= 1.0:
iz_center_x_px = iz_center_x * frame.shape[1]
else:
iz_center_x_px = iz_center_x
# Draw small icon at bottom of image using Circle patch
icon_y = frame.shape[0] - 20 # 20 pixels from bottom
from matplotlib.patches import Circle
iz_circle = Circle((iz_center_x_px, icon_y), 8,
fill=True, facecolor='red', edgecolor='darkred',
linewidth=2, alpha=0.8, zorder=10)
ax.add_patch(iz_circle)
# Add small vertical line to show it's at the bottom
ax.plot([iz_center_x_px, iz_center_x_px], [icon_y, frame.shape[0]],
'r-', linewidth=2, alpha=0.6, zorder=9)
# Draw virtual center position icon (where interaction zone gets recentered to) at the bottom
if has_shift:
# Virtual center is at the center of the image
virtual_center_x_px = frame.shape[1] / 2
icon_y = frame.shape[0] - 20 # 20 pixels from bottom
# Draw dashed circle using Circle patch with proper linestyle
from matplotlib.patches import Circle
virtual_circle = Circle((virtual_center_x_px, icon_y), 8,
fill=False, edgecolor='red', linewidth=2,
linestyle='--', alpha=0.8, zorder=10)
ax.add_patch(virtual_circle)
# Add small vertical dashed line to show it's at the bottom
ax.plot([virtual_center_x_px, virtual_center_x_px], [icon_y, frame.shape[0]],
'r--', linewidth=2, alpha=0.6, zorder=9, dashes=(5, 5))
self.figure.tight_layout()
self.canvas.draw()
except Exception as e:
self.figure.clear()
ax = self.figure.add_subplot(111)
ax.text(0.5, 0.5, f'Error loading image:\n{str(e)}',
ha='center', va='center', transform=ax.transAxes, fontsize=10)
self.canvas.draw()
def update_skeleton(self):
"""Update the skeleton visualization"""
if self.current_data is None:
self.skeleton_figure.clear()
self.skeleton_canvas.draw()
return
# Clear the skeleton figure
self.skeleton_figure.clear()
# Check if we should show skeletons and bounding box
show_vitpose = self.vitpose_skeleton_checkbox.isChecked()
show_sapiens = self.sapiens_skeleton_checkbox.isChecked()
show_bounding_box = self.show_bounding_box_checkbox.isChecked()
free_scaleing = self.free_scaleing_checkbox.isChecked()
# Create subplots - left for skeleton, right for bounding box
if show_bounding_box and (show_vitpose or show_sapiens):
# Two subplots side by side
ax_skeleton = self.skeleton_figure.add_subplot(121)
ax_bbox = self.skeleton_figure.add_subplot(122)
elif show_bounding_box:
# Only bounding box
ax_skeleton = None
ax_bbox = self.skeleton_figure.add_subplot(111)
else:
# Only skeleton
ax_skeleton = self.skeleton_figure.add_subplot(111)
ax_bbox = None
# Get current timestamp
timestamp = self.timestamp_slider.value()
# Update label with probability if available
if self.proba_sequence is not None and timestamp < len(self.proba_sequence):
proba = self.proba_sequence[timestamp]
if proba > -1:
proba_str = f"{proba:.3f}"
proba_percent = f"{proba*100:.0f}%"
self.timestamp_label.setText(f"Frame: {timestamp}/{len(self.current_data)-1} | Prob: {proba_str} ({proba_percent})")
else:
self.timestamp_label.setText(f"Frame: {timestamp}/{len(self.current_data)-1} | Prob: WAIT")
else:
self.timestamp_label.setText(f"Frame: {timestamp}/{len(self.current_data)-1}")
if not show_vitpose and not show_sapiens and not show_bounding_box:
# Use the main axis for the message
main_ax = ax_skeleton if ax_skeleton is not None else ax_bbox
if main_ax is not None:
main_ax.text(0.5, 0.5, 'Select skeleton type or bounding box to display',
ha='center', va='center', transform=main_ax.transAxes)
self.skeleton_canvas.draw()
return
# Get image dimensions for coordinate scaling
image_width, image_height = self.get_image_dimensions()
is_normalized = self.is_data_normalized()
# Define skeleton connections
vitpose_connections = [
(0, 1), (0, 2), (1, 3), (2, 4), # head
(5, 6), (5, 7), (7, 9), (6, 8), (8, 10), # arms
(5, 11), (6, 12), (11, 12), # torso
(11, 13), (13, 15), (12, 14), (14, 16) # legs
]
# For Sapiens, we'll use a simplified skeleton with main body parts
# (since it has 308 keypoints, we'll focus on the main body structure)
# sapiens_main_keypoints = [
# 'nose', 'left_eye', 'right_eye', 'left_ear', 'right_ear',
# 'left_shoulder', 'right_shoulder', 'left_elbow', 'right_elbow',
# 'left_wrist', 'right_wrist', 'left_hip', 'right_hip',
# 'left_knee', 'right_knee', 'left_ankle', 'right_ankle'
# ]
# sapiens_connections = [
# (0, 1), (0, 2), (1, 3), (2, 4), # head
# (5, 6), (5, 7), (7, 9), (6, 8), (8, 10), # arms
# (5, 11), (6, 12), (11, 12), # torso
# (11, 13), (13, 15), (12, 14), (14, 16) # legs
# ]
# Plot bounding box
if show_bounding_box and ax_bbox is not None:
self.plot_bounding_box(ax_bbox, timestamp, is_normalized, image_width, image_height)
# Plot VitPose skeleton
if show_vitpose and ax_skeleton is not None:
keypoints_colors = [(color[0]/255, color[1]/255, color[2]/255) for color in VITPOSE_COLORS]
self.plot_skeleton(ax_skeleton, timestamp, 'vitpose', VITPOSE_KEYPOINTS_NAMES,
vitpose_connections, 'red', keypoints_colors, 'VitPose', is_normalized, image_width, image_height)
# Plot Sapiens skeleton
if show_sapiens and ax_skeleton is not None:
keypoints_colors = [(color[0]/255, color[1]/255, color[2]/255) for color in GOLIATH_KPTS_COLORS]
sapiens_connections = [GOLIATH_SKELETON_INFO[i]['link'] for i in range(len(GOLIATH_SKELETON_INFO))]
sapiens_main_keypoints = GOLIATH_KEYPOINTS_NAMES
self.plot_skeleton(ax_skeleton, timestamp, 'sapiens_308', sapiens_main_keypoints,
sapiens_connections, 'blue', keypoints_colors, 'Sapiens', is_normalized, image_width, image_height)
# Set up the plot with dynamic limits for both axes
axes_to_setup = []
if ax_skeleton is not None:
axes_to_setup.append(('Skeleton', ax_skeleton))
if ax_bbox is not None:
axes_to_setup.append(('Bounding Box', ax_bbox))
for axis_name, ax in axes_to_setup:
if free_scaleing:
pass
#ax.set_xlim(min_x, max_x)
#ax.set_ylim(min_y, max_y)
else:
if self.is_standardized():
if self.destandardized:
if is_normalized:
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
else:
ax.set_xlim(0, image_width)
ax.set_ylim(0, image_height)
else:
pass
else:
if is_normalized:
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
else:
ax.set_xlim(0, image_width)
ax.set_ylim(0, image_height)
ax.set_aspect('equal')
ax.invert_yaxis() # Invert Y axis to match image coordinates
# ax.set_title(f'{axis_name} - Frame {timestamp} ({image_width}x{image_height})')
ax.grid(True, alpha=0.3)
self.skeleton_figure.tight_layout()
self.skeleton_canvas.draw()
def get_image_dimensions(self):
"""Get image dimensions from the current dataset item"""
if self.dataset is None or self.current_index >= len(self.dataset):
return 3840, 1920 # Default dimensions
try:
metadata = self.current_item_metadata
if 'image_size' in metadata:
width, height = metadata['image_size']
return width, height
except:
pass
return 3840, 1920 # Default fallback
def is_data_normalized(self):
"""Check if the current data is normalized"""
if self.dataset is None:
return True # Default to normalized
# Check if normalize_in_image is enabled in the dataset
return getattr(self.dataset, 'normalize_in_image', True)
def is_standardized(self):
"""Check if the current data is standardized"""
if self.dataset is None:
return True # Default to standardized
standardize_attr = getattr(self.dataset, 'standardize_data', None)
if standardize_attr == "all":
return True
else:
return False
def plot_skeleton(self, ax, timestamp, prefix, keypoint_names, connections, color, keypoints_colors, label, is_normalized, image_width, image_height):
"""Plot a skeleton for the given timestamp with dynamic coordinate handling"""
if timestamp >= len(self.current_data):
return
# Get keypoint data for this timestamp
frame_data = self.current_data.iloc[timestamp]
# Extract keypoint coordinates
keypoints = []
valid_keypoints = []
for i, name in enumerate(keypoint_names):
x_col = f"{prefix}_{name}_x"
y_col = f"{prefix}_{name}_y"
score_col = f"{prefix}_{name}_score"
if x_col in frame_data and y_col in frame_data and score_col in frame_data:
x = frame_data[x_col]
y = frame_data[y_col]
score = frame_data[score_col]
# Only plot keypoints with reasonable confidence
if not np.isnan(x) and not np.isnan(y) and score > 0.3:
x_coord, y_coord = x, y
keypoints.append((x_coord, y_coord))
valid_keypoints.append(i)
else:
keypoints.append((np.nan, np.nan))
valid_keypoints.append(-1)
else:
keypoints.append((np.nan, np.nan))
valid_keypoints.append(-1)
# Plot keypoints with dynamic sizing
valid_x = [kp[0] for i, kp in enumerate(keypoints) if valid_keypoints[i] != -1]
valid_y = [kp[1] for i, kp in enumerate(keypoints) if valid_keypoints[i] != -1]
colors = [keypoints_colors[i] for i in valid_keypoints if i != -1]
if not "sapiens" in prefix:
# Plot connections with dynamic line width
line_width = max(1, min(4, (image_width + image_height) / 200))
for connection in connections:
start_idx, end_idx = connection
if (start_idx < len(keypoints) and end_idx < len(keypoints) and
valid_keypoints[start_idx] != -1 and valid_keypoints[end_idx] != -1):
start_point = keypoints[start_idx]
end_point = keypoints[end_idx]
if not (np.isnan(start_point[0]) or np.isnan(end_point[0])):
ax.plot([start_point[0], end_point[0]],
[start_point[1], end_point[1]],
color=color, linewidth=line_width, alpha=0.8)
if valid_x and valid_y:
# Dynamic point size based on image dimensions
if "sapiens" in prefix:
point_size = max(5, min(25, (image_width + image_height) / 100))
else:
point_size = max(20, min(100, (image_width + image_height) / 20))
ax.scatter(valid_x, valid_y, c=colors, s=point_size, label=label, edgecolors='white', linewidth=1)
# # Add legend only if we have valid keypoints
# if valid_x and valid_y:
# ax.legend(loc='upper right', fontsize=8)
def plot_bounding_box(self, ax, timestamp, is_normalized, image_width, image_height):
"""Plot the bounding box for the given timestamp in its dedicated axis"""
if timestamp >= len(self.current_data):
return
# Get frame data
frame_data = self.current_data.iloc[timestamp]
# Extract bounding box coordinates
if 'xmin' in frame_data and 'xmax' in frame_data and 'ymin' in frame_data and 'ymax' in frame_data:
xmin = frame_data['xmin']
xmax = frame_data['xmax']
ymin = frame_data['ymin']
ymax = frame_data['ymax']
# Check if bounding box data is valid
if not (np.isnan(xmin) or np.isnan(xmax) or np.isnan(ymin) or np.isnan(ymax)):
# Calculate bounding box dimensions
bbox_width = xmax - xmin
bbox_height = ymax - ymin
# Create rectangle for bounding box with fill
from matplotlib.patches import Rectangle
bbox_rect = Rectangle((xmin, ymin), bbox_width, bbox_height,
linewidth=3, edgecolor='green', facecolor='lightgreen',
alpha=0.3, linestyle='-', label='Bounding Box')
ax.add_patch(bbox_rect)
# Add center point
center_x = (xmin + xmax) / 2
center_y = (ymin + ymax) / 2
ax.scatter(center_x, center_y, c='darkgreen', s=100, alpha=0.9,
marker='+', linewidth=4, label='BBox Center')
# Add corner points
# corners = [(xmin, ymin), (xmax, ymin), (xmax, ymax), (xmin, ymax)]
# for i, (cx, cy) in enumerate(corners):
# ax.scatter(cx, cy, c='green', s=60, alpha=0.8,
# marker='o', edgecolors='darkgreen', linewidth=2)