-
Notifications
You must be signed in to change notification settings - Fork 0
/
gui.py
1634 lines (1362 loc) · 70.2 KB
/
gui.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
#!/usr/bin/env python3
# update splash screen
import platform
if platform.system() == 'Windows':
try:
import pyi_splash
# Update the text on the splash screen
pyi_splash.update_text("Importing modules...")
except Exception as inst:
print(f"Splash screen not supported on this platform: {inst}")
import json
import os.path
import time
import uuid
from typing import List, Dict
from collections import deque
from functools import partial
from pynput import mouse
from pynput import keyboard
# import pygame
import pyqtgraph as pg
from PySide6 import QtWidgets, QtCore, QtGui
from PySide6.QtWidgets import QApplication, QMainWindow, QWidget, QHBoxLayout, QVBoxLayout, QGroupBox, QFileDialog
import numpy as np
import Demo
import Mouse
import Gesture
import util
from gui_widgets import LogarithmicSlider, ColoredDoubleSlider, DoubleSlider, StyledMouseSlider
import re
class PlotLine:
def __init__(self, pen, plot_data_item: pg.PlotDataItem):
self.x = deque(maxlen=100)
self.y = deque(maxlen=100)
self.length = 0
self.max_length = 100
self.pen = pen
self.plot_data_item = plot_data_item
def plot(self, x, y):
self.x.append(x)
self.y.append(y)
self.plot_data_item.setData(self.x, self.y, pen=self.pen)
def set_visible(self, visibility):
self.plot_data_item.setVisible(visibility)
class SignalVis(QtWidgets.QWidget):
def __init__(self):
super(SignalVis, self).__init__()
self.plot_area: pg.PlotWidget = pg.PlotWidget()
self.plot_item: pg.PlotItem = self.plot_area.getPlotItem()
self.layout = QtWidgets.QHBoxLayout(self)
self.layout.addWidget(self.plot_area)
self.raw_selection_button = QtWidgets.QRadioButton("Raw Values")
self.layout.addWidget(self.raw_selection_button)
self.layout.setAlignment(self.raw_selection_button, QtCore.Qt.AlignmentFlag.AlignTop)
self.raw_selection_button.toggled.connect(self.toggle_raw)
self.raw_values = False
self.plot_area.setBackground('w')
self.lines = {}
self.index = 0
def add_line(self, name: str):
pen = pg.mkPen(color=pg.intColor(self.index, 8, 2), width=2)
data_line = self.plot_area.plot(x=[90, -90] * 50, y=[0] * 100, pen=pen)
plot_handler = PlotLine(pen, data_line)
self.lines[name] = plot_handler
self.index = self.index + 1
return plot_handler
def remove_line(self, name):
print(name)
handler = self.lines.pop(name,None)
if handler is not None:
handler.plot_data_item.setData()
def update_plot(self, signals):
x = time.time()
for name, plot in self.lines.items():
signal = signals.get(name)
if signal is None:
continue
if self.raw_values:
y = signals[name].raw_value.get()
plot.plot(x, y)
else:
y = signals[name].scaled_value
plot.plot(x, y)
def toggle_raw(self, checked):
print(checked)
self.raw_values = checked
class SignalSetting(QtWidgets.QFrame):
deleted = QtCore.Signal(str)
save_triggered = QtCore.Signal()
def __init__(self, name: str, min_value, max_value, min_filter=0.0001, max_filter=1., demo=None):
super().__init__()
self.name = name
print(name)
self.name_label = QtWidgets.QLabel(name)
self.demo:Demo.Demo = demo
self.lower_value = QtWidgets.QDoubleSpinBox()
self.lower_value.setSingleStep(0.01)
self.lower_value.setMinimum(-100.)
self.lower_value.setMaximum(100.)
self.lower_value.setValue(min_value)
self.lower_value.valueChanged.connect(self.set_lower_threshold)
self.lower_value.valueChanged.connect(lambda : self.save_triggered.emit())
self.higher_value = QtWidgets.QDoubleSpinBox()
self.higher_value.setSingleStep(0.01)
self.higher_value.setMinimum(-100.)
self.higher_value.setMaximum(100.)
self.higher_value.setValue(max_value)
self.higher_value.valueChanged.connect(self.set_higher_threshold)
self.higher_value.valueChanged.connect(lambda: self.save_triggered.emit())
self.filter_slider = LogarithmicSlider(orientation=QtCore.Qt.Orientation.Horizontal)
self.filter_slider.setMinimum(min_filter)
self.filter_slider.setMaximum(max_filter)
self.filter_slider.doubleValueChanged.connect(self.set_filter_value)
filter_value_indicator = QtWidgets.QLabel("0")
self.filter_slider.doubleValueChanged.connect(lambda value:filter_value_indicator.setText(f"{value:.4f}"))
self.filter_slider.doubleValueChanged.connect(lambda: self.save_triggered.emit())
self.visualization_checkbox = QtWidgets.QCheckBox("Visualize")
self.visualization_checkbox.setChecked(True)
self.calibrate_button = QtWidgets.QPushButton("Calibrate Thresholds")
self.calibrate_button.clicked.connect(self.calibrate_signal)
self.delete_button= QtWidgets.QPushButton("Delete")
self.delete_button.clicked.connect(self.delete_signal)
self.layout = QtWidgets.QHBoxLayout(self)
self.layout.addWidget(self.name_label, stretch=1)
self.layout.addWidget(self.visualization_checkbox)
self.layout.addWidget(QtWidgets.QLabel("GestureSignal range"))
self.layout.addWidget(self.lower_value)
self.layout.addWidget(self.higher_value)
self.layout.addWidget(QtWidgets.QLabel("Filter"))
self.layout.addWidget(self.filter_slider, stretch=1)
self.layout.addWidget(filter_value_indicator)
self.layout.addWidget(self.calibrate_button)
self.layout.addWidget(self.delete_button)
self.layout.addStretch(2)
self.filter_slider.doubleValueChanged.connect(lambda value: print(value))
self.setFrameShape(QtWidgets.QFrame.Shape.Box)
def calibrate_signal(self):
print("Calibration start")
self.calib_diag = CalibrationDialog(self.demo, self.name)
self.calib_diag.accepted.connect(self.accept_calibration)
self.calib_diag.webcam_timer.start()
self.calib_diag.open()
# self.calibration_dialog.show()
def accept_calibration(self):
min_value = self.calib_diag.min_value
max_value = self.calib_diag.max_value
self.lower_value.setValue(min_value)
self.higher_value.setValue(max_value)
self.save_triggered.emit()
def delete_signal(self):
print(f"Delete in signal settings with name {self.name}")
self.demo.delete_signal(self.name)
self.demo.recalibrate()
self.deleteLater()
self.deleted.emit(self.name)
self.save_triggered.emit()
def debug_check(self):
print(self.name)
def set_lower_threshold(self, value):
self.demo.signals[self.name].set_lower_threshold(value)
def set_higher_threshold(self, value):
self.demo.signals[self.name].set_higher_threshold(value)
def set_filter_value(self, value):
signal = self.demo.signals.get(self.name,None)
if signal is not None:
self.demo.signals[self.name].set_filter_value(value)
class SignalTab(QtWidgets.QWidget):
signals_updated = QtCore.Signal()
def __init__(self, demo, json_path, tracker_name):
super().__init__()
self.demo: Demo.Demo = demo
self.tracker_name = tracker_name
self.setWindowTitle("Signals Visualization")
self.signals_vis = SignalVis()
self.signals_vis.setMaximumHeight(250)
self.signals_vis.setMinimumHeight(100)
size_policy = self.signals_vis.sizePolicy()
size_policy.setVerticalPolicy(QtWidgets.QSizePolicy.Policy.Maximum)
size_policy.setHorizontalPolicy(QtWidgets.QSizePolicy.Policy.Expanding)
self.signals_vis.setSizePolicy(size_policy)
self.add_signal_button = QtWidgets.QPushButton("Record new GestureSignal")
self.add_signal_button.clicked.connect(self.add_new_signal)
self.save_signals_button = QtWidgets.QPushButton("Save Profile")
self.load_signals_button = QtWidgets.QPushButton("Load Profile")
self.save_signals_button.clicked.connect(self.save_signals)
self.load_signals_button.clicked.connect(self.load_signals_dialog)
self.layout = QtWidgets.QVBoxLayout(self)
self.layout.addWidget(self.signals_vis)
self.scroll_area = QtWidgets.QScrollArea()
self.scroll_area.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarPolicy.ScrollBarAlwaysOn)
self.scroll_area.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
self.scroll_area.setWidgetResizable(True)
self.signal_settings = dict()
self.setting_widget = QtWidgets.QWidget()
self.signal_config = dict()
self.load_signals(json_path)
self.layout.addWidget(self.scroll_area)
button_layout = QtWidgets.QHBoxLayout(self)
button_layout.addWidget(self.add_signal_button)
button_layout.addStretch()
button_layout.addWidget(self.save_signals_button)
button_layout.addWidget(self.load_signals_button)
self.layout.addLayout(button_layout)
def update_plots(self, signals):
self.signals_vis.update_plot(signals)
def add_new_signal(self):
self.sig_diag = AddSignalDialog(self.demo)
self.sig_diag.accepted.connect(self.accept_new_signal)
self.sig_diag.webcam_timer.start()
self.sig_diag.open()
def delete_signal(self, name):
print(f"delete signal with name: {name} in SignalTab")
self.signals_vis.remove_line(name)
self.signal_settings.pop(name,None)
self.signals_updated.emit()
def accept_new_signal(self):
signal_name = self.sig_diag.new_name.text()
new_singal = {
"name": signal_name,
"lower_threshold": 0.,
"higher_threshold": 1.,
"filter_value": 0.0001
}
success = self.demo.recalibrate()
if not success:
msgBox = QtWidgets.QMessageBox()
msgBox.setWindowTitle("Error")
msgBox.setText("Error occured")
msgBox.setInformativeText("Not able to add new signal")
msgBox.exec()
return
self.demo.add_signal(signal_name)
self.signal_settings[signal_name] = SignalSetting(signal_name, 0., 1., demo=self.demo)
handler = self.signals_vis.add_line(signal_name)
self.signal_settings[signal_name].visualization_checkbox.stateChanged.connect(handler.set_visible)
self.signal_settings[signal_name].visualization_checkbox.setChecked(False)
self.signal_settings[signal_name].filter_slider.setValue(0.0001)
self.signal_settings[signal_name].deleted.connect(self.delete_signal)
#self.signal_settings[signal_name].save_triggered.connect(
# lambda: self.save_signals(f"config/{self.tracker_name}_signal_latest.json"))
self.setting_widget.layout().addWidget(self.signal_settings[signal_name])
self.signals_updated.emit()
def save_signal_dialog(self):
file_name, _ = QtWidgets.QFileDialog.getSaveFileName(self, "Select profile save file", "./config",
"JSON (*.json)")
self.save_signals(file_name)
def save_signals(self, file_name):
if file_name=="":
return # no file selected
self.demo.save_signals(file_name)
def load_signals_dialog(self):
file_name, _ = QtWidgets.QFileDialog.getOpenFileName(self, "Select profile to load", "./config",
"JSON (*.json)")
if file_name == "":
return # no file selected
self.load_signals(file_name)
def load_signals(self, json_path):
# Clear widget
self.setting_widget = QtWidgets.QWidget()
self.setting_widget.setLayout(QtWidgets.QVBoxLayout())
self.signal_settings = dict()
#Load json
try:
self.signal_config: dict = json.load(open(json_path, "r"))
except FileNotFoundError:
print("File not found")
return
for json_signal in self.signal_config["signals"]:
signal_name = json_signal["name"]
lower_threshold = json_signal["lower_threshold"]
higher_threshold = json_signal["higher_threshold"]
filter_value = json_signal["filter_value"]
self.signal_settings[signal_name] = SignalSetting(signal_name, lower_threshold, higher_threshold, demo=self.demo)
handler = self.signals_vis.add_line(signal_name)
self.signal_settings[signal_name].visualization_checkbox.stateChanged.connect(handler.set_visible)
self.signal_settings[signal_name].visualization_checkbox.setChecked(False)
self.signal_settings[signal_name].filter_slider.setValue(filter_value)
self.signal_settings[signal_name].deleted.connect(self.delete_signal)
#self.signal_settings[signal_name].save_triggered.connect(lambda : self.save_signals(f"config/{self.tracker_name}_signal_latest.json"))
self.setting_widget.layout().addWidget(self.signal_settings[signal_name])
#self.signal_added.emit()
self.signals_updated.emit()
#self.save_signals(f"config/{self.tracker_name}_signal_latest.json")
# load in demo
self.demo.setup_signals(json_path)
self.scroll_area.setWidget(self.setting_widget)
class CalibrationDialog(QtWidgets.QDialog):
# TODO: add videorecording for data collection?
def __init__(self, demo, name):
super().__init__()
self.demo: Demo.Demo = demo
self.name = name
self.label = QtWidgets.QLabel(name)
self.calibration_samples = {name: {"neutral": [], "pose": []}}
self.min_value = 0.
self.max_value = 0.
self.recording_neutral = False
self.recording_max_pose = False
self.do_action_label = QtWidgets.QLabel()
self.neutral_timer = QtCore.QTimer(self)
self.neutral_timer.setSingleShot(True)
self.neutral_timer.setInterval(2000)
self.pose_timer = QtCore.QTimer(self)
self.pose_timer.setSingleShot(True)
self.pose_timer.setInterval(2000)
## Webcam Image
self.webcam_label = QtWidgets.QLabel()
self.webcam_label.setMinimumSize(640, 480)
self.webcam_label.setMaximumSize(1280, 720)
self.webcam_label.setSizePolicy(QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Expanding)
self.webcam_timer = QtCore.QTimer(self)
self.webcam_timer.setInterval(30)
self.webcam_timer.timeout.connect(self.update_image)
self.qt_image = QtGui.QImage(np.zeros((640, 480, 30), dtype=np.uint8), 480, 640,
QtGui.QImage.Format.Format_BGR888)
QBtn = QtWidgets.QDialogButtonBox.StandardButton.Ok | QtWidgets.QDialogButtonBox.StandardButton.Cancel
self.start_button = QtWidgets.QPushButton("Start")
self.start_button.clicked.connect(self.start_calibration)
self.buttonBox = QtWidgets.QDialogButtonBox(QBtn)
self.buttonBox.accepted.connect(self.accept)
self.buttonBox.rejected.connect(self.reject)
self.layout = QtWidgets.QVBoxLayout()
self.layout.addWidget(self.label)
self.layout.addWidget(self.do_action_label)
self.layout.addWidget(self.webcam_label)
self.button_layout = QtWidgets.QHBoxLayout()
self.button_layout.addWidget(self.start_button)
self.button_layout.addWidget(self.buttonBox)
self.layout.addLayout(self.button_layout)
self.setLayout(self.layout)
def update_image(self):
w = self.webcam_label.width()
h = self.webcam_label.height()
image = self.demo.annotated_landmarks
signal = self.demo.signals.get(self.name)
if signal is not None:
if self.recording_neutral:
self.calibration_samples[self.name]["neutral"].append(signal.raw_value.get())
elif self.recording_max_pose:
self.calibration_samples[self.name]["pose"].append(signal.raw_value.get())
self.qt_image = QtGui.QImage(image, image.shape[1], image.shape[0], QtGui.QImage.Format.Format_BGR888)
self.qt_image = self.qt_image.scaled(w, h, QtCore.Qt.AspectRatioMode.KeepAspectRatio,
QtCore.Qt.TransformationMode.SmoothTransformation)
self.webcam_label.setPixmap(QtGui.QPixmap.fromImage(self.qt_image))
def resizeEvent(self, event: QtGui.QResizeEvent) -> None:
super().resizeEvent(event)
self.webcam_label.resizeEvent(event)
w = self.webcam_label.width()
h = self.webcam_label.height()
self.qt_image = self.qt_image.scaled(w, h, QtCore.Qt.AspectRatioMode.KeepAspectRatio)
self.webcam_label.setPixmap(QtGui.QPixmap.fromImage(self.qt_image))
def accept(self) -> None:
self.webcam_timer.stop()
print(self.calibration_samples)
print(len(self.calibration_samples[self.name]["neutral"]))
print(len(self.calibration_samples[self.name]["pose"]))
self.min_value, self.max_value = self.demo.calibrate_signal(calibration_sample=self.calibration_samples,
name=self.name)
super().accept()
def reject(self) -> None:
self.webcam_timer.stop()
super().reject()
def start_calibration(self):
self.do_action_label.setText("Neutral Pose")
self.neutral_timer.timeout.connect(self.record_gesture)
self.recording_neutral = True
self.neutral_timer.start()
def record_gesture(self):
# TODO: save videos to create dataset?
self.do_action_label.setText("Maximum Gesture")
self.pose_timer.timeout.connect(self.finish_recording)
self.recording_neutral = False
self.recording_max_pose = True
self.pose_timer.start()
def finish_recording(self):
self.recording_max_pose = False
self.do_action_label.setText("Finished")
class AddSignalDialog(QtWidgets.QDialog):
def __init__(self, demo):
super().__init__()
self.demo: Demo.Demo = demo
self.name = "NewPosers"
self.recording_neutral = False
self.recording_max_pose = False
self.do_action_label = QtWidgets.QLabel()
self.neutral_timer = QtCore.QTimer(self)
self.neutral_timer.setSingleShot(True)
self.neutral_timer.setInterval(5000)
self.pose_timer = QtCore.QTimer(self)
self.pose_timer.setSingleShot(True)
self.pose_timer.setInterval(5000)
## Webcam Image
self.webcam_label = QtWidgets.QLabel()
self.webcam_label.setMinimumSize(640, 480)
self.webcam_label.setMaximumSize(1280, 720)
self.webcam_label.setSizePolicy(QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Expanding)
self.webcam_timer = QtCore.QTimer(self)
self.webcam_timer.setInterval(30)
self.webcam_timer.timeout.connect(self.update_image)
self.qt_image = QtGui.QImage(np.zeros((640, 480, 30), dtype=np.uint8), 480, 640,
QtGui.QImage.Format.Format_BGR888)
QBtn = QtWidgets.QDialogButtonBox.StandardButton.Ok | QtWidgets.QDialogButtonBox.StandardButton.Cancel
self.start_button = QtWidgets.QPushButton("Start")
self.start_button.clicked.connect(self.start_calibration)
self.buttonBox = QtWidgets.QDialogButtonBox(QBtn)
self.buttonBox.accepted.connect(self.accept)
self.buttonBox.rejected.connect(self.reject)
self.name_label = QtWidgets.QLabel("Name")
self.new_name = QtWidgets.QLineEdit()
self.layout = QtWidgets.QVBoxLayout()
self.layout.addWidget(self.do_action_label)
self.layout.addWidget(self.webcam_label)
self.button_layout = QtWidgets.QHBoxLayout()
self.button_layout.addWidget(self.start_button)
self.button_layout.addWidget(self.name_label)
self.button_layout.addWidget(self.new_name)
self.button_layout.addWidget(self.buttonBox)
self.layout.addLayout(self.button_layout)
self.setLayout(self.layout)
def update_image(self):
w = self.webcam_label.width()
h = self.webcam_label.height()
image = self.demo.annotated_landmarks
self.qt_image = QtGui.QImage(image, image.shape[1], image.shape[0], QtGui.QImage.Format.Format_BGR888)
self.qt_image = self.qt_image.scaled(w, h, QtCore.Qt.AspectRatioMode.KeepAspectRatio,
QtCore.Qt.TransformationMode.SmoothTransformation)
self.webcam_label.setPixmap(QtGui.QPixmap.fromImage(self.qt_image))
def resizeEvent(self, event: QtGui.QResizeEvent) -> None:
super().resizeEvent(event)
self.webcam_label.resizeEvent(event)
w = self.webcam_label.width()
h = self.webcam_label.height()
self.qt_image = self.qt_image.scaled(w, h, QtCore.Qt.AspectRatioMode.KeepAspectRatio)
self.webcam_label.setPixmap(QtGui.QPixmap.fromImage(self.qt_image))
def accept(self) -> None:
name = self.new_name.text()
if name == "":
msgBox = QtWidgets.QMessageBox()
msgBox.setWindowTitle("Error")
msgBox.setText("Error occured")
msgBox.setInformativeText("Name is missing")
msgBox.exec()
return
self.webcam_timer.stop()
super().accept()
def reject(self) -> None:
self.webcam_timer.stop()
self.neutral_timer.blockSignals(True)
self.pose_timer.blockSignals(True)
self.neutral_timer.stop()
self.pose_timer.stop()
self.neutral_timer.blockSignals(False)
self.pose_timer.blockSignals(False)
super().reject()
def start_calibration(self):
name = self.new_name.text()
if name == "":
msgBox = QtWidgets.QMessageBox()
msgBox.setWindowTitle("Error")
msgBox.setText("Error occured")
msgBox.setInformativeText("Name is missing")
msgBox.exec()
return
self.do_action_label.setText("Neutral Pose")
self.neutral_timer.timeout.connect(self.record_gesture)
self.recording_neutral = True
self.demo.calibrate_neutral_start(name)
self.neutral_timer.start()
self.setStyleSheet("background-color:rgb(18,102,80)")
def record_gesture(self):
# TODO: save videos to create dataset?
name = self.new_name.text()
self.demo.calibrate_neutral_stop(name)
self.demo.calibrate_pose_start(name)
self.do_action_label.setText("Maximum Gesture")
self.pose_timer.timeout.connect(self.finish_recording)
self.recording_neutral = False
self.recording_max_pose = True
self.pose_timer.start()
self.setStyleSheet("background-color:rgb(96,70,8)")
def finish_recording(self):
name = self.new_name.text()
self.recording_max_pose = False
self.demo.calibrate_pose_stop(name)
self.do_action_label.setText("Finished")
self.setStyleSheet("")
class DebugVisualizetion(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.setWindowFlag(QtCore.Qt.WindowType.WindowStaysOnTopHint, True)
self.setWindowTitle("Gesture Mouse - Live Debug")
self.setMaximumSize(Demo.VID_RES_X, Demo.VID_RES_Y+50)
self.webcam_label = QtWidgets.QLabel()
self.webcam_label.setMinimumSize(Demo.VID_RES_X/2, Demo.VID_RES_Y/2)
self.qt_image = QtGui.QImage()
self.webcam_label.setSizePolicy(QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Expanding)
self.status_bar1 = QtWidgets.QStatusBar()
self.status_bar1.showMessage("Tracking: ")
self.status_bar2 = QtWidgets.QStatusBar()
self.status_bar2.showMessage("Mouse: ")
self.status_bar3 = QtWidgets.QStatusBar()
self.status_bar3.showMessage("Gestures: Screen:")
self.status_bar_gestures = QtWidgets.QStatusBar()
self.status_bar_gestures.showMessage("")
self.layout = QtWidgets.QVBoxLayout(self)
self.layout.addWidget(self.status_bar1)
self.layout.addWidget(self.status_bar2)
self.layout.addWidget(self.status_bar3)
self.layout.addWidget(self.webcam_label)
self.layout.addWidget(self.status_bar_gestures)
def update_image(self, image):
w = self.webcam_label.width()
h = self.webcam_label.height()
self.qt_image = QtGui.QImage(image, image.shape[1], image.shape[0], QtGui.QImage.Format.Format_BGR888)
self.qt_image = self.qt_image.scaled(w, h, QtCore.Qt.AspectRatioMode.KeepAspectRatio,
QtCore.Qt.TransformationMode.SmoothTransformation)
self.webcam_label.setPixmap(QtGui.QPixmap.fromImage(self.qt_image))
def resizeEvent(self, event: QtGui.QResizeEvent) -> None:
super().resizeEvent(event)
self.webcam_label.resizeEvent(event)
self.status_bar1.resizeEvent(event)
w = self.webcam_label.width()
h = self.webcam_label.height()
self.qt_image = self.qt_image.scaled(w, h, QtCore.Qt.AspectRatioMode.KeepAspectRatio)
self.webcam_label.setPixmap(QtGui.QPixmap.fromImage(self.qt_image))
class GeneralTab(QtWidgets.QWidget):
mode_changed = QtCore.Signal(str) # Change to enum
def __init__(self, demo):
super().__init__()
self.demo: Demo.Demo = demo
#add group box for video source and other settings
self.video_source_grp=QGroupBox("Camera / Video source")
self.filter_grp=QGroupBox("Filter settings")
self.mediapipe_selector_button = QtWidgets.QCheckBox(text="Use web cam tracking.")
self.mediapipe_selector_button.setChecked(self.demo.use_mediapipe)
self.mediapipe_selector_button.clicked.connect(lambda selected: self.demo.set_use_mediapipe(selected))
self.landmark_filter_button = QtWidgets.QCheckBox(text="Filter Landmarks.")
self.landmark_filter_button.setChecked(self.demo.filter_landmarks)
self.landmark_filter_button.clicked.connect(lambda selected: self.demo.set_filter_landmarks(selected))
self.debug_window = DebugVisualizetion()
self.debug_window_button = QtWidgets.QPushButton("Open Camera/Video Display")
self.debug_window_button.clicked.connect(self.toggle_debug_window)
self.vid_source_start = QtWidgets.QPushButton("Start tracking")
self.vid_source_start.clicked.connect(self.demo.start_tracking)
self.vid_source_stop = QtWidgets.QPushButton("Stop tracking")
self.vid_source_stop.clicked.connect(self.demo.stop_tracking)
self.layout = QtWidgets.QVBoxLayout(self)
self.layout.addWidget(self.video_source_grp)
self.layout.addWidget(self.filter_grp)
self.vid_main_layout=QtWidgets.QVBoxLayout()
self.vid_mode_layout=QtWidgets.QHBoxLayout()
self.vid_mode_grp=QtWidgets.QGroupBox("Video mode selection")
self.vid_mode_grp.setLayout(self.vid_mode_layout)
self.vid_webcam_grp=QGroupBox("Use webcam")
self.vid_webcam_grp.setCheckable(True)
self.vid_webcam_grp.setChecked(self.demo.use_mediapipe)
self.vid_webcam_grp.toggled.connect(self.webcam_grp_toggled)
self.vid_webcam_layout=QtWidgets.QFormLayout()
self.vid_webcam_grp.setLayout(self.vid_webcam_layout)
self.vid_iphone3d_grp=QGroupBox("Use iPhone 3D camera")
self.vid_iphone3d_grp.setCheckable(True)
self.vid_iphone3d_grp.setChecked(not self.demo.use_mediapipe)
self.vid_iphone3d_grp.toggled.connect(self.iphone_grp_toggled)
self.vid_iphone3d_layout=QtWidgets.QFormLayout()
self.vid_iphone3d_layout.addRow(QtWidgets.QLabel("My IP address: "),QtWidgets.QLabel(self.demo.my_ip))
self.vid_iphone3d_layout.addRow(QtWidgets.QLabel("My UPD port: "), QtWidgets.QLabel(str(self.demo.UDP_PORT)))
self.vid_iphone3d_grp.setLayout(self.vid_iphone3d_layout)
self.vid_vidfile_grp=QGroupBox("Use video file")
self.vid_vidfile_grp.setCheckable(True)
self.vid_vidfile_grp.setChecked(False)
self.vid_vidfile_grp.toggled.connect(self.vidfile_grp_toggled)
self.vid_vidfile_layout=QtWidgets.QFormLayout()
self.vid_vidfile_openfile = QtWidgets.QPushButton("Select video file")
self.vid_vidfile_openfile.clicked.connect(self.open_file_dialog)
self.vid_vidfile_layout.addWidget(self.vid_vidfile_openfile)
self.vid_vidfile_grp.setLayout(self.vid_vidfile_layout)
self.csv_record_group = QGroupBox("Record all signals")
self.csv_record_group.setCheckable(True)
self.csv_record_group.setChecked(False)
self.csv_record_group.toggled.connect(self.csv_grp_toggled)
label = QtWidgets.QLabel("Helper Mode to evaluate system")
self.csv_grp_layout = QtWidgets.QFormLayout()
self.csv_grp_layout.addWidget(label)
self.csv_record_group.setLayout(self.csv_grp_layout)
self.vid_mode_layout.addWidget(self.vid_webcam_grp)
self.vid_mode_layout.addWidget(self.vid_iphone3d_grp)
self.vid_mode_layout.addWidget(self.vid_vidfile_grp)
self.vid_mode_layout.addWidget(self.csv_record_group)
self.vid_webcam_device=QtWidgets.QComboBox()
webcam_available_ports,self.vid_webcam_devices,webcam_non_working_ports=util.list_camera_ports()
self.vid_webcam_devices=map(str,self.vid_webcam_devices)
print(self.vid_webcam_devices)
self.vid_webcam_device.addItems(self.vid_webcam_devices)
self.vid_webcam_device.currentTextChanged.connect(lambda arg__1: self.demo.update_webcam_device_selection(arg__1))
self.vid_webcam_layout.addRow(QtWidgets.QLabel("Camera device"),self.vid_webcam_device)
self.csv_write_group = QGroupBox("CSV Settings")
self.csv_start_button = QtWidgets.QPushButton("Start")
self.csv_stop_button = QtWidgets.QPushButton("Stop")
self.csv_file_selection_button = QtWidgets.QPushButton("Select file location")
self.csv_file_label = QtWidgets.QLabel("File Location")
self.csv_file_path = ""
# Events
self.csv_file_selection_button.clicked.connect(self.csv_save_dialog)
self.csv_start_button.clicked.connect(self.start_csv_recording)
self.csv_stop_button.clicked.connect(self.demo.stop_write_csv)
self.vid_mode_layout.addWidget(self.vid_webcam_grp)
self.vid_mode_layout.addWidget(self.vid_iphone3d_grp)
self.vid_mode_layout.addWidget(self.vid_vidfile_grp)
self.vid_main_layout.addWidget(self.vid_mode_grp)
self.vid_main_layout.addWidget(self.vid_source_start)
self.vid_main_layout.addWidget(self.vid_source_stop)
self.vid_main_layout.addWidget(self.debug_window_button)
self.video_source_grp.setLayout(self.vid_main_layout)
self.filter_grp_layout = QtWidgets.QVBoxLayout()
self.filter_grp_layout.addWidget(self.landmark_filter_button)
self.filter_grp.setLayout(self.filter_grp_layout)
self.csv_writer_layout = QtWidgets.QHBoxLayout()
self.csv_writer_layout.addWidget(self.csv_file_selection_button)
self.csv_writer_layout.addWidget(self.csv_file_label)
self.csv_writer_layout.addStretch()
self.csv_writer_layout.addWidget(self.csv_start_button)
self.csv_writer_layout.addWidget(self.csv_stop_button)
self.csv_write_group.setLayout(self.csv_writer_layout)
self.layout.addWidget(self.csv_write_group)
self.shortcut_group = QGroupBox("Important Shortcuts")
self.shortcut_layout = QtWidgets.QVBoxLayout()
self.shortcut_group.setLayout(self.shortcut_layout)
self.shortcut_layout.addWidget(QtWidgets.QLabel("<Ctrl><Alt>+v: Start/Stop video and tracking"))
self.shortcut_layout.addWidget(QtWidgets.QLabel("<Ctrl><Alt>+g: Enable/Disable gestures"))
self.shortcut_layout.addWidget(QtWidgets.QLabel("<Ctrl><Alt>+m: Enable/Disable mouse movement"))
self.shortcut_layout.addWidget(QtWidgets.QLabel("<Ctrl><Alt>+e: Enable/Disable gestures and mouse movement"))
self.shortcut_layout.addWidget(QtWidgets.QLabel("<Shift><Alt>+m: Change mouse movement mode"))
self.shortcut_layout.addWidget(QtWidgets.QLabel("<Shift><Alt>+r: Change mouse tracking mode"))
self.shortcut_layout.addWidget(QtWidgets.QLabel("<Shift><Alt>+c: Center mouse"))
self.shortcut_layout.addWidget(QtWidgets.QLabel("<Shift><Alt>+s: Switch primary screen for mouse movement"))
self.layout.addWidget(self.shortcut_group)
self.layout.addStretch()
def open_file_dialog(self):
fileName = QFileDialog.getOpenFileName(self, "Open File")
print(f"selected file {fileName[0]}")
if fileName[0]:
self.demo.update_webcam_video_file_selection(fileName[0])
def csv_save_dialog(self):
file_name = QFileDialog.getSaveFileName(self, "Select File", filter="*.csv")[0]
if file_name:
self.csv_file_path = file_name
self.csv_file_label.setText(self.csv_file_path)
def start_csv_recording(self):
self.demo.start_write_csv(self.csv_file_path)
def toggle_debug_window_globally(self):
"""
Need a specific method for the global hook, because directly calling self.debug_window.show() freezes the GUI.
This is probably because the GlobalHook is executed in a another thread and causes a dead lock.
"""
print("called by global hotkey")
self.debug_window_button.click()
self.demo.toggle_tracking()
def toggle_debug_window(self):
print("showing window...")
self.debug_window.show()
def update_debug_visualization(self):
self.debug_window.update_image(self.demo.annotated_landmarks)
self.debug_window.status_bar1.showMessage(f"Tracking: {self.demo.is_tracking}, FPS: {int(self.demo.fps)}")
self.debug_window.status_bar2.showMessage(f"Mouse: {self.demo.mouse.mouse_movement_enabled}, {self.demo.mouse.mode.name}, {self.demo.mouse.tracking_mode.name}")
self.debug_window.status_bar3.showMessage(f"Gestures: {self.demo.mouse.mouse_gesture_enabled}, Screen: {self.demo.mouse.monitor_index}")
# Check all gestures if they are activated and update status bar
# TODO: Use listener pattern or queue to notify about changes?
active_gestures = ""
for signal in self.demo.signals.values():
for action in signal.actions.values():
if action.is_activated:
if active_gestures != "":
active_gestures += ", "
active_gestures += signal.name
self.debug_window.status_bar_gestures.showMessage(active_gestures)
def webcam_grp_toggled(self, on:bool):
if on:
self.vid_iphone3d_grp.blockSignals(True)
self.vid_iphone3d_grp.setChecked(False)
self.vid_iphone3d_grp.blockSignals(False)
self.vid_vidfile_grp.blockSignals(True)
self.vid_vidfile_grp.setChecked(False)
self.vid_vidfile_grp.blockSignals(False)
self.demo.use_mediapipe = True
self.mode_changed.emit("WEBCAM")
else:
self.vid_webcam_grp.blockSignals(True)
self.vid_webcam_grp.setChecked(False)
self.vid_webcam_grp.blockSignals(False)
def iphone_grp_toggled(self, on:bool):
if on:
self.vid_webcam_grp.blockSignals(True)
self.vid_webcam_grp.setChecked(False)
self.vid_webcam_grp.blockSignals(False)
self.vid_vidfile_grp.blockSignals(True)
self.vid_vidfile_grp.setChecked(False)
self.vid_vidfile_grp.blockSignals(False)
self.csv_record_group.blockSignals(True)
self.csv_record_group.setChecked(False)
self.csv_record_group.blockSignals(False)
self.demo.use_mediapipe = False
self.mode_changed.emit("IPHONE")
else:
self.vid_iphone3d_grp.blockSignals(True)
self.vid_iphone3d_grp.setChecked(False)
self.vid_iphone3d_grp.blockSignals(False)
def vidfile_grp_toggled(self, on:bool):
if on:
self.vid_webcam_grp.blockSignals(True)
self.vid_webcam_grp.setChecked(False)
self.vid_webcam_grp.blockSignals(False)
self.vid_iphone3d_grp.blockSignals(True)
self.vid_iphone3d_grp.setChecked(False)
self.vid_iphone3d_grp.blockSignals(False)
self.csv_record_group.blockSignals(True)
self.csv_record_group.setChecked(False)
self.csv_record_group.blockSignals(False)
self.demo.use_mediapipe = True
self.mode_changed.emit("VIDEOFILE")
else:
self.vid_vidfile_grp.blockSignals(True)
self.vid_vidfile_grp.setChecked(False)
self.vid_vidfile_grp.blockSignals(False)
def csv_grp_toggled(self, on:bool):
if on:
self.vid_webcam_grp.blockSignals(True)
self.vid_webcam_grp.setChecked(False)
self.vid_webcam_grp.blockSignals(False)
self.vid_iphone3d_grp.blockSignals(True)
self.vid_iphone3d_grp.setChecked(False)
self.vid_iphone3d_grp.blockSignals(False)
self.vid_vidfile_grp.blockSignals(True)
self.vid_vidfile_grp.setChecked(False)
self.vid_vidfile_grp.blockSignals(False)
self.demo.recording_mode=True
self.demo.use_mediapipe=False
self.mode_changed.emit("VIDEOFILE")
else:
self.csv_record_group.blockSignals(True)
self.csv_record_group.setChecked(False)
self.csv_record_group.blockSignals(False)
class MouseTab(QtWidgets.QWidget):
def __init__(self, demo):
super().__init__()
self.demo: Demo.Demo = demo
self.click_settings = ["Left", "Right", "Double", "Drag and Drop", "Pause", "Center"]
outer_layout = QtWidgets.QVBoxLayout(self)
debug_layout = QtWidgets.QVBoxLayout()
debug_frame = QtWidgets.QFrame()
debug_frame.setFrameShape(QtWidgets.QFrame.Box)
debug_frame.setLayout(debug_layout)
upper_outer_layout = QtWidgets.QHBoxLayout()
actions_layout = QtWidgets.QVBoxLayout()
action_frame = QtWidgets.QFrame()
action_frame.setFrameShape(QtWidgets.QFrame.Box)
action_frame.setLayout(actions_layout)
settings_layout = QtWidgets.QFormLayout()
settings_frame = QtWidgets.QFrame()
settings_frame.setFrameShape(QtWidgets.QFrame.Box)
settings_frame.setLayout(settings_layout)
outer_layout.addLayout(upper_outer_layout)
#outer_layout.addStretch()
outer_layout.addWidget(debug_frame)
upper_outer_layout.addWidget(action_frame, stretch=1)
upper_outer_layout.addWidget(settings_frame, stretch=1)
actions_layout.addWidget(QtWidgets.QLabel("Click Settings"))
settings_layout.addRow("Mouse Settings", None)
debug_layout.addWidget(QtWidgets.QLabel("Information Screen"))
# Click settings
self.mouse_settings = {}
self.mouse_settings["left_click"] = MouseClickSettings("Left",self.demo,lambda : self.demo.mouse.click(mouse.Button.left))
self.mouse_settings["right_click"] = MouseClickSettings("Right",self.demo,lambda : self.demo.mouse.click(mouse.Button.right))
self.mouse_settings["double_click"] = MouseClickSettings("Double Click", self.demo,lambda : self.demo.mouse.double_click(mouse.Button.left))
self.mouse_settings["drag_drop"] = MouseClickSettings("Drag and Drop",self.demo,lambda : self.demo.mouse.drag_drop())
self.mouse_settings["pause"] = MouseClickSettings("Pause", self.demo, lambda : self.demo.mouse.toggle_mouse_movement())
self.mouse_settings["center"] = MouseClickSettings("Center", self.demo, lambda : self.demo.mouse.centre_mouse())
self.mouse_settings["switch_mode"] = MouseClickSettings("Switch Mode", self.demo, lambda : self.demo.mouse.toggle_mode())
self.mouse_settings["switch_monitor"] = MouseClickSettings("Switch Monitor", self.demo, lambda : self.demo.mouse.switch_monitor())
self.mouse_settings["precision_mode"] = MouseClickSettings("Toggle Precision Mode", self.demo, lambda : self.demo.mouse.toggle_precision_mode())
for mouse_setting in self.mouse_settings.values():
actions_layout.addWidget(mouse_setting)
mouse_setting.trigger_save.connect(self.save_lates)
# Mouse Settings
self.x_sensitivity_slider = StyledMouseSlider(decimals=3)
self.x_sensitivity_slider.setValue(self.demo.mouse.x_sensitivity)
self.x_sensitivity_slider.doubleValueChanged.connect(self.demo.mouse.set_x_sensitivity)
self.x_sensitivity_slider.doubleValueChanged.connect(self.save_lates)
self.y_sensitivity_slider = StyledMouseSlider(decimals=3)
self.y_sensitivity_slider.setValue(self.demo.mouse.y_sensitivity)
self.y_sensitivity_slider.doubleValueChanged.connect(self.demo.mouse.set_y_sensitivity)
self.y_sensitivity_slider.doubleValueChanged.connect(self.save_lates)
self.x_acceleration_slider = StyledMouseSlider(decimals=3)
self.x_acceleration_slider.setValue(self.demo.mouse.x_acceleration)
self.x_acceleration_slider.doubleValueChanged.connect(self.demo.mouse.set_x_acceleration)
self.x_acceleration_slider.doubleValueChanged.connect(self.save_lates)
self.y_acceleration_slider = StyledMouseSlider(decimals=3)
self.y_acceleration_slider.setValue(self.demo.mouse.y_acceleration)
self.y_acceleration_slider.doubleValueChanged.connect(self.demo.mouse.set_y_acceleration)
self.y_acceleration_slider.doubleValueChanged.connect(self.save_lates)
self.smoothing_toggle = QtWidgets.QCheckBox()
self.smoothing_toggle.setChecked(self.demo.mouse.filter_mouse_position)
self.smoothing_toggle.toggled.connect(self.demo.mouse.set_filter_enabled)
self.smoothing_toggle.toggled.connect(self.save_lates)
self.smoothing_value = LogarithmicSlider()
self.smoothing_value.setOrientation(QtCore.Qt.Orientation.Horizontal)
self.smoothing_value.setMinimum(0.001)
self.smoothing_value.setMaximum(0.1)
self.smoothing_value.setValue(self.demo.mouse.filter_value)
self.smoothing_value.doubleValueChanged.connect(self.demo.mouse.set_filter_value)
self.smoothing_value.doubleValueChanged.connect(self.save_lates)
self.tracking_mode_selector = QtWidgets.QComboBox()
self.tracking_mode_selector.addItems([mode.name for mode in Mouse.TrackingMode])
self.tracking_mode_selector.currentTextChanged.connect(self.demo.mouse.set_tracking_mode)
self.tracking_mode_selector.currentTextChanged.connect(self.save_lates)
self.mouse_mode_selector = QtWidgets.QComboBox()
self.mouse_mode_selector.addItems([mode.name for mode in Mouse.MouseMode])
self.mouse_mode_selector.currentTextChanged.connect(self.demo.mouse.set_mouse_mode)
self.mouse_mode_selector.currentTextChanged.connect(self.save_lates)
self.save_button = QtWidgets.QPushButton("Save Profile")
self.save_button.clicked.connect(self.save_profile_dialog)