-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathheadmouse.py
executable file
·2055 lines (1731 loc) · 66.2 KB
/
headmouse.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
# HeadMouse-Pi -- Raspberry Pi based head tracking mouse
# Copyright (C) 2020 Kevin Rowland
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import logging
import math
import multiprocessing as mp
import os
import queue
import shlex
import signal
import stat
import struct
import subprocess
import sys
import time
import traceback
from os.path import getmtime
from threading import Thread
import cv2
import dlib
import eventlet
import numpy as np
import yappi
from configargparse import ArgumentParser, ArgumentDefaultsHelpFormatter
from filterpy.common.discretization import Q_discrete_white_noise
from filterpy.kalman import KalmanFilter
from flask import Response
from flask_socketio import SocketIO
from imutils import face_utils
from imutils.video import FPS
from scipy.linalg import block_diag
from webapp import create_app
# MyVideoStream, MyPiVideoStream, and MyVideoCapture are derived from the 'imutils.video'
# package authored by Adrian Rosebrock and modified by Kevin Rowland. The following license applies:
#
# The MIT License (MIT)
#
# Copyright (c) 2015-2016 Adrian Rosebrock, http://www.pyimagesearch.com
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
class MyVideoStream:
def __init__(self, src=0, usePiCamera=False, resolution=(320, 240), framerate=None,
frame_q=None, **kwargs):
# check to see if the picamera module should be used
if usePiCamera:
# only import the picamera packages unless we are
# explicitly told to do so -- this helps remove the
# requirement of `picamera[array]` from desktops or
# laptops that still want to use the `imutils` package
# initialize the picamera stream and allow the camera
# sensor to warmup
self.stream = MyPiVideoStream(resolution=resolution, framerate=framerate,
frame_q=frame_q, **kwargs)
# otherwise, we are using OpenCV so initialize the webcam
# stream
else:
self.stream = MyVideoCapture(src=src, resolution=resolution, framerate=framerate,
frame_q=frame_q)
def start(self):
# start the threaded video stream
return self.stream.start()
def update(self):
# grab the next frame from the stream
self.stream.update()
def read(self):
# return the current frame
return self.stream.read()
def stop(self):
# stop the thread and release any resources
self.stream.stop()
def join(self):
self.stream.join()
def fps(self):
self.stream.fps()
class MyPiVideoStream:
def __init__(self, resolution=(320, 240), framerate=30, frame_q=None, **kwargs):
# initialize the camera
import picamera.array
resolution = picamera.PiResolution(resolution[0], resolution[1]).pad()
self.camera = picamera.PiCamera(resolution=resolution, framerate=framerate)
self.frame_q = frame_q
# set optional camera parameters (refer to PiCamera docs)
for (arg, value) in kwargs.items():
setattr(self.camera, arg, value)
# initialize the stream
self.rawCapture = picamera.array.PiRGBArray(self.camera, size=resolution)
self.stream = self.camera.capture_continuous(self.rawCapture,
format="bgr", use_video_port=True)
# initialize the frame and the variable used to indicate
# if the thread should be stopped
self.stopped = False
self.thread = None
self.frame = None
self.framenum = None
self.framew = None
self.frameh = None
self.skipped = 0
def start(self):
# start the thread to read frames from the video stream
self.thread = Thread(target=self.update, args=())
self.thread.daemon = True
self.thread.start()
return self
def update(self):
global running
# keep looping infinitely until the thread is stopped
framenum = 0
try:
for f in self.stream:
# grab the frame from the stream and clear the stream in
# preparation for the next frame
frame = f.array
if self.framew is None and frame is not None:
(self.frameh, self.framew) = frame.shape[:2]
framenum += 1
if self.frame_q is not None:
try:
self.frame_q.put_nowait((framenum, frame))
except queue.Full:
framenum -= 1
self.skipped += 1
else:
self.frame = frame
self.framenum = framenum
self.rawCapture.truncate(0)
# if the thread indicator variable is set, stop the thread
# and resource camera resources
if self.stopped:
break
except Exception as e:
log.info("{}\n{}".format(e, traceback.format_exc()))
running = False
self.stopped = True
self.stream.close()
self.rawCapture.close()
self.camera.close()
if _args_.verbose > 0:
log.info("Frames captured: {}".format(framenum))
try:
log.info("Frames orphaned: {}".format(self.frame_q.qsize()))
except (NotImplementedError, AttributeError):
pass
log.info("Frames skipped: {}".format(self.skipped))
def read(self):
# return the frame most recently read
if self.frame_q is not None:
try:
(self.framenum, self.frame) = self.frame_q.get(timeout=1)
except queue.Empty:
pass
else:
# time.sleep(.01)
pass
return self.framenum, self.frame
def stop(self):
# indicate that the thread should be stopped
self.stopped = True
def join(self):
self.thread.join()
def fps(self):
return self.camera.framerate
class MyVideoCapture(object):
def __init__(self, src=0, resolution=(None, None), framerate=None, frame_q=None,
name="VideoCapture"):
self.frame_q = frame_q
# initialize the video camera stream and read the first frame
# from the stream
self.stream = cv2.VideoCapture(src)
if resolution[0] is not None:
self.stream.set(cv2.CAP_PROP_FRAME_WIDTH, resolution[0])
if resolution[1] is not None:
self.stream.set(cv2.CAP_PROP_FRAME_HEIGHT, resolution[1])
if framerate is not None:
self.stream.set(cv2.CAP_PROP_FPS, framerate)
# initialize the thread name
self.name = name
# initialize the variable used to indicate if the thread should
# be stopped
self.stopped = False
self.thread = None
self.frame = None
self.framenum = None
self.framew = None
self.frameh = None
self.skipped = 0
def start(self):
# start the thread to read frames from the video stream
self.thread = Thread(target=self.update, name=self.name, args=())
self.thread.daemon = True
self.thread.start()
return self
def update(self):
# keep looping infinitely until the thread is stopped
framenum = 0
while True:
# if the thread indicator variable is set, stop the thread
if self.stopped:
if _args_.verbose > 0:
log.info("Frames captured: {}".format(framenum))
try:
log.info("Frames orphaned: {}".format(self.frame_q.qsize()))
except (NotImplementedError, AttributeError):
pass
log.info("Frames skipped: {}".format(self.skipped))
return
# otherwise, read the next frame from the stream
(_, frame) = self.stream.read()
if self.framew is None and frame is not None:
(self.frameh, self.framew) = frame.shape[:2]
framenum += 1
if self.frame_q is not None:
try:
self.frame_q.put_nowait((framenum, frame))
except queue.Full:
framenum -= 1
self.skipped += 1
else:
self.framenum = framenum
self.frame = frame
def read(self):
# return the frame most recently read
if self.frame_q is not None:
try:
(self.framenum, self.frame) = self.frame_q.get(timeout=1)
except queue.Empty:
pass
else:
# time.sleep(.01)
pass
return self.framenum, self.frame
def stop(self):
# indicate that the thread should be stopped
self.stopped = True
def join(self):
self.thread.join()
def fps(self):
return self.stream.get(cv2.CAP_PROP_FPS)
class Face(object):
def __init__(self, fps, webserver=None):
self._angs_x = None
self._angs_y = None
self._cur_angle = [0, 0]
self._ave_angle = None
self._center = None
self._shapes = None
self._framenum = None
self._ws = webserver
self.mouth = MouthOpen(face=self, webserver=webserver)
self.eyes = Eyes(face=self, fps=fps, webserver=webserver)
self.brows = Eyebrows(face=self, webserver=webserver)
self.nose = Nose(face=self, fps=fps, webserver=webserver)
def update(self, framenum, shapes):
self._framenum = framenum
self._shapes = shapes
self._update_posture()
self.mouth.update()
self.eyes.update()
self.brows.update()
self.nose.update()
# let the socketio green threads do some work
self._ws.socketio.sleep(0)
def _update_posture(self):
shapes = self.shapes
if shapes is None:
return
# nose 27,30
# nostr 31,35
sep = feature_center(shapes[31:36])
cen = feature_center(shapes)
angle_x = cen[0] - sep[0]
angle_y = cen[1] - sep[1]
_n = 6
_s = -2
if self._angs_y is None:
self._angs_x = [angle_x, ] * _n
self._angs_y = [angle_y, ] * _n
else:
self._angs_x.append(self._angs_x.pop(0))
self._angs_x[-1] = angle_x
self._angs_y.append(self._angs_y.pop(0))
self._angs_y[-1] = angle_y
self._cur_angle = [sum(self._angs_x[_s:]) / len(self._angs_x[_s:]),
sum(self._angs_y[_s:]) / len(self._angs_y[_s:])]
self._ave_angle = [sum(self._angs_x[:_s]) / len(self._angs_x[:_s]),
sum(self._angs_y[:_s]) / len(self._angs_y[:_s])]
self._center = cen
if _args_.debug_face:
log.info("face {:6.02f} {:6.02f} {:6.02f} {:6.02f}".format(self._ave_angle[0],
self._cur_angle[0],
self._ave_angle[1],
self._cur_angle[1]))
def facing_camera(self):
if self._shapes is None or abs(self.x_angle) > 5.0 or self.y_angle < -5.0 or self.y_angle > 0:
return False
else:
return True
@property
def shapes(self):
return self._shapes
@property
def framenum(self):
return self._framenum
@property
def center(self):
return self._center
@property
def angle(self):
return self._cur_angle
@property
def ave_angle(self):
return self._ave_angle
@property
def x_angle(self):
return self._cur_angle[0]
@property
def x_ave_angle(self):
return self._ave_angle[0]
@property
def y_angle(self):
return self._cur_angle[1]
@property
def y_ave_angle(self):
return self._ave_angle[1]
class MouthOpen(object):
def __init__(self, face, webserver=None):
self.face = face
self._vdists = None
self._vdist = None
self._hdists = None
self._hdist = None
self._open = False
self.kf = MyKalmanFilter(dim_x=6, dim_z=2, dt=1 / 30, Q=1.0, R=.05)
self._ws = webserver
self.send_debug_data = False
def update(self):
# moutho 48,59
# mouthi 60,67
_n = 6
_s = -2
shapes = self.face.shapes
if shapes is None:
vdist = self._vdists[-1] if self._vdists is not None else 0
hdist = self._hdists[-1] if self._hdists is not None else 0
kpos = 0
kvel = 0
kacc = 0
else:
up = shapes[62]
lo = shapes[66]
vdist = point_distance(up, lo)
lc = shapes[60]
rc = shapes[64]
hdist = point_distance(lc, rc)
self.kf.predict()
self.kf.update([vdist, hdist])
kpos = (self.kf.x[0][0], self.kf.x[3][0])
kvel = (self.kf.x[1][0], self.kf.x[4][0])
kacc = (self.kf.x[2][0], self.kf.x[5][0])
if self._vdists is None:
self._vdists = [vdist, ] * _n
self._hdists = [hdist, ] * _n
else:
self._vdists.append(self._vdists.pop(0))
self._vdists[-1] = vdist
self._hdists.append(self._hdists.pop(0))
self._hdists[-1] = hdist
self._vdist = sum(self._vdists[_s:]) / len(self._vdists[_s:])
v_ave = sum(self._vdists[:_s]) / len(self._vdists[:_s])
self._hdist = sum(self._hdists[_s:]) / len(self._hdists[_s:])
h_ave = sum(self._hdists[:_s]) / len(self._hdists[:_s])
_ave = (v_ave, h_ave)
_r = self._vdist / self._hdist if self._hdist != 0 else 0
if not self._open:
self._open = _r >= .40
else:
self._open = _r >= .40
if _args_.debug_mouth:
log.info("mouth {:.02f} {:.02f} {:.02f} {:.02f} {:.02f}".format(
v_ave, self._vdist, h_ave, self._hdist, _r))
if self.send_debug_data:
self._ws.socketio.emit('mouth_data', [_ave, (self._vdist, self._hdist), _r, kpos, kvel, kacc])
@property
def open(self):
return self._open
def button_up(self):
return self._open is False
def button_down(self):
return self._open is True
class Eyebrows(object):
def __init__(self, face, webserver=None):
self.face = face
self._ebds = None
self._cur_height = None
self._ave_height = None
self._raised = False
self._raised_count = 0
self._sticky_raised = False
self.kf = MyKalmanFilter(dim_x=3, dim_z=1, dt=1 / 30, Q=25.0, R=.5)
self._ws = webserver
self.send_debug_data = False
def update(self):
# jaw 0,16
# rbrow 17,21
# lbrow 22,26
# nose 27,30
# nostr 31,35
# reye 36,41
# leye 42,47
# moutho 48,59
# mouthi 60,67
_n = 6
_s = -2
shapes = self.face.shapes
if shapes is None:
ebd = self._ebds[-1] if self._ebds is not None else 0
kpos = 0
kvel = 0
kacc = 0
else:
ebc = feature_center([shapes[19], shapes[24]])
ebd = point_distance(ebc, shapes[27])
self.kf.predict()
self.kf.update(ebd)
kpos = self.kf.x[0][0]
kvel = self.kf.x[1][0]
kacc = self.kf.x[2][0]
ebd -= .30 * abs(self.face.x_angle)
if self.face.y_angle < 0:
ebd -= .2 * abs(self.face.y_angle)
if self._ebds is None:
self._ebds = [ebd, ] * _n
else:
self._ebds.append(self._ebds.pop(0))
self._ebds[-1] = ebd
# maxangle = 12
self._cur_height = sum(self._ebds[_s:]) / len(self._ebds[_s:])
self._ave_height = sum(self._ebds[:_s]) / len(self._ebds[:_s])
_d = self._cur_height - self._ave_height
f_a = True # maxangle > self.face.x_angle > -maxangle and maxangle > self.face.y_angle > -maxangle
h_y = self._cur_height >= 17
if _args_.stickyclick:
raised = f_a and h_y and _d >= _args_.ebd
if not self._raised:
self._raised = raised
else:
lowered = f_a and -_d >= _args_.ebd * .60
if not self._sticky_raised or self._raised_count > 0:
self._raised = not lowered
elif raised:
self._sticky_raised = False
if self._raised and not self._sticky_raised:
self._raised_count += 1
if self._raised_count > int(round(_fps_.fps() * .500)):
self._sticky_raised = True
self._raised_count = 0
else:
self._raised_count = 0
else:
self._raised = f_a and h_y and _d > _args_.ebd
updown = "up" if self._raised else " "
updown += '+' if self._sticky_raised else ' '
if _args_.debug_brows:
line = "brows {:.02f}/{:.02f} x[{:.02f}] v[{:6.02f}] a[{:7.02f}] f[{:5.02f}/{:5.02f}] d[{:5.02f}] {}"
log.info(line.format(self._ave_height, self._cur_height, kpos, kvel, kacc,
self.face.x_angle, self.face.y_angle, _d, updown))
if self.send_debug_data:
self._ws.socketio.emit('brow_data', [self._ave_height, self._cur_height, kpos, kvel, kacc,
self.face.x_angle, self.face.y_angle, _d, updown])
def reset(self):
self._raised = False
self._raised_count = 0
self._sticky_raised = False
@property
def cur_height(self):
return self._cur_height
@property
def ave_height(self):
return self._ave_height
@property
def raised(self):
return self._raised
def button_up(self):
return self._raised is False
def button_down(self):
return self._raised is True
class Eyes(object):
def __init__(self, face, fps=None, webserver=None):
self.face = face
self._ws = webserver
self._open = False
dt = None if fps is None else 1.0 / fps
self.kf = MyKalmanFilter(dim_x=2, dim_z=1, dt=dt, Q=1.0, R=.05)
self._pupillary_dist = None
self.send_debug_data = False
def update(self):
# reye 36,41
# leye 42,47
shapes = self.face.shapes
if shapes is None:
ear = 0
self._pupillary_dist = 0
kpos = 0
kvel = 0
else:
rec = feature_center(shapes[36:42])
lec = feature_center(shapes[42:48])
self._pupillary_dist = point_distance(rec, lec)
red = (point_distance(shapes[37], shapes[41]) + point_distance(shapes[38], shapes[40])) / \
(2.0 * point_distance(shapes[36], shapes[39]))
led = (point_distance(shapes[43], shapes[47]) + point_distance(shapes[44], shapes[46])) / \
(2.0 * point_distance(shapes[42], shapes[45]))
ear = (red + led) / 2
self.kf.predict()
self.kf.update(ear)
kpos = self.kf.x[0][0]
kvel = self.kf.x[1][0]
if kpos < _args_.ear:
self._open = False
else:
self._open = True
if _args_.debug_eyes:
log.info("eyes {:5.02f} {:5.02f} {:6.03f} {}".format(
ear, kpos, kvel, "O" if self._open else "."
))
if self.send_debug_data:
self._ws.socketio.emit('eyes_data', [ear, kpos, kvel, self._pupillary_dist, self._open])
@property
def open(self):
return self._open
@property
def pupillary_dist(self):
return self._pupillary_dist
def button_up(self):
return self.open
def button_down(self):
return not self.button_up()
class Nose(object):
def __init__(self, face, fps=None, webserver=None):
self.face = face
self._ws = webserver
self._positions = None
self.nose_raw = [0, 0]
self._dx = None
self._dy = None
self._vx = None
self._vy = None
self._ax = None
self._ay = None
dt = None if fps is None else 1.0 / fps
self.kf = MyKalmanFilter(dim_x=6, dim_z=2, dt=dt, Q=1.0, R=.05)
self.send_debug_data = False
def update(self):
# jaw 0,16
# rbrow 17,21
# lbrow 22,26
# nose 27,30
# nostr 31,35
# reye 36,41
# leye 42,47
# moutho 48,59
# mouthi 60,67
shapes = self.face.shapes
if shapes is None:
# force 0 delta position
kpos = self._positions[1] if self._positions is not None else [0, 0]
kvel = [0, 0]
kacc = [0, 0]
else:
self.nose_raw = shapes[30]
self.kf.predict()
self.kf.update(self.nose_raw)
kpos = [int(round(self.kf.x[0][0])), int(round(self.kf.x[3][0]))]
kvel = [self.kf.x[1][0], self.kf.x[4][0]]
kacc = [self.kf.x[2][0], self.kf.x[5][0]]
nose = kpos if _args_.filter else self.nose_raw
if self._positions is None:
self._positions = [nose, nose]
else:
self._positions.append(self._positions.pop(0))
self._positions[-1] = nose
self._dx = self.position[0] - self.prev_position[0]
self._dy = self.position[1] - self.prev_position[1]
self._vx = kvel[0]
self._vy = kvel[1]
self._ax = kacc[0]
self._ay = kacc[1]
if _args_.debug_nose:
line = "nose ({:7.03f}, {:7.03f}) ({:8.03f}, {:8.03f}) ({:8.03f}, {:8.03f}) "
line += "({:7.03f}, {:6.02f}) ({:7.03f}, {:6.02f})"
log.info(line.format(self.nose_raw[0], self.nose_raw[1], kpos[0], self.vx,
kpos[1], self.vy, self.dx, self.ax, self.dy, self.ay))
if self.send_debug_data:
self._ws.socketio.emit('nose_data', [int(self.nose_raw[0]), int(self.nose_raw[1]), int(kpos[0]),
self.vx, int(kpos[1]), self.vy,
self.dx, self.ax, self.dy, self.ay])
@property
def ax(self):
return int(self._ax)
@property
def ay(self):
return int(self._ay)
@property
def vx(self):
return int(self._vx)
@property
def vy(self):
return int(self._vy)
@property
def dx(self):
return int(self._dx)
@property
def dy(self):
return int(self._dy)
@property
def prev_position(self):
return self._positions[0]
@property
def position(self):
return self._positions[1]
class Keyboard(object):
usage_ids = {'NUL': 0,
'A': 4, 'B': 5, 'C': 6, 'D': 7, 'E': 8, 'F': 9, 'G': 10, 'H': 11, 'I': 12, 'J': 13, 'K': 14, 'L': 15,
'M': 16, 'N': 17, 'O': 18, 'P': 19, 'Q': 20, 'R': 21, 'S': 22, 'T': 23, 'U': 24, 'V': 25, 'W': 26,
'X': 27, 'Y': 28, 'Z': 29,
'1': 30, '2': 31, '3': 32, '4': 33, '5': 34, '6': 35, '7': 36, '8': 37, '9': 38, '0': 39,
'RET': 40, 'ESC': 41, 'BACK': 42, 'TAB': 43, 'SPACE': 44,
'-': 45, '=': 46, '[': 47, ']': 48, '\\': 49, ';': 51, "'": 52, '`': 53, ',': 54, '.': 55, '/': 56,
'CAPS': 57, 'F1': 58, 'F2': 59, 'F3': 60, 'F4': 61, 'F5': 62, 'F6': 63, 'F7': 64, 'F8': 65, 'F9': 66,
'F10': 67, 'F11': 68, 'F12': 69,
'PRSCR': 70, 'SCRLCK': 71, 'PAUSE': 72, 'INSERT': 73, 'HOME': 74, 'PGUP': 75, 'DEL': 76, 'END': 77,
'PGDOWN': 78, 'RIGHT': 79, 'LEFT': 80, 'DOWN': 81, 'UP': 82}
class MousePointer(object):
def __init__(self, face, mindeltathresh=None, webserver=None):
self.face = face
self._ws = webserver
self._fd = None
self.open_hidg()
self._dx = None
self._dy = None
self._click = None
# todo: unlink gestures from actions, make user preference
# todo: add gesture for wheel
self.btn = {1: {'s': 0, 'f': self.face.brows},
2: {'s': 0, 'f': self.face.mouth},
3: {'s': 0, 'f': None}, }
# todo: pause on "no face", resume on "click pattern"
self.pausebtn = {'s': 0, 'f': self.face.mouth}
self._paused = False
self.cpos = None
self.angle = None
self.track_cpos = self._fd is None
self.maxheight = None
self.maxwidth = None
self.wrap = False
self.xgain = _args_.xgain if _args_.xgain is not None else 1.0
self.ygain = _args_.ygain if _args_.ygain is not None else 1.0
self.mindeltathresh = mindeltathresh if mindeltathresh is not None else 1
self._smoothness = None
self._motionweight = None
self.set_smoothness(_args_.smoothness)
self._prevdx = 0
self._prevdy = 0
self.i_accel = None
# self.accel = [0.0, 1.0, 1.2, 1.4, 1.6,
# 1.8, 2.0, 2.2, 2.4, 2.6,
# 2.3, 2.4, 2.5, 3.0, 4.0,
# 4.1, 4.2, 4.3, 4.4, 4.5,
# 4.6, 4.7, 4.8, 4.9, 5.0,
# 5.1, 5.2, 5.3, 5.4, 5.5, ]
# todo: make acceleration table user preference
# todo: adjust gain based on pupillary distance, adjust sensitivity based on head size/ratio
self.accel = [1.0]*10 + [2.0]*20
def open_hidg(self):
if self._fd is not None:
return self._fd
try:
self._fd = open('/dev/hidg0', 'r+b', buffering=0)
except FileNotFoundError:
self._fd = None
def close_hidg(self):
if self._fd is not None:
self._fd.close()
self._fd = None
def pause(self, state=None):
if state is not None:
self._paused = bool(state)
else:
self._paused = not self._paused
self.face.brows.reset()
self.send_keyboard(['ESC']) # ESC to cancel context menu
self.send_keyboard()
if _args_.verbose > 0:
log.info('{}pause'.format('' if self.paused else 'un'))
def process_movement(self):
nose = self.face.nose
dx = nose.dx
dy = nose.dy
dx *= self.xgain
dy *= self.ygain
if not _args_.filter:
if _args_.smoothness != self._smoothness:
self.set_smoothness(_args_.smoothness)
dx = dx * (1.0 - self._motionweight) + self._prevdx * self._motionweight
dy = dy * (1.0 - self._motionweight) + self._prevdy * self._motionweight
self._prevdx = dx
self._prevdy = dy
dist = math.sqrt(dx * dx + dy * dy)
self.i_accel = int(dist + 0.5)
if self.i_accel >= len(self.accel):
self.i_accel = len(self.accel) - 1
if not _args_.filter:
if -self.mindeltathresh < dx < self.mindeltathresh:
dx = 0
if -self.mindeltathresh < dy < self.mindeltathresh:
dy = 0
dx *= self.accel[self.i_accel]
dy *= self.accel[self.i_accel]
dx = -int(round(dx))
dy = int(round(dy))
self._dx = dx
self._dy = dy
if self.track_cpos:
try:
self.cpos[0] += dx
self.cpos[1] += dy
except TypeError:
self.cpos = [int(self.maxwidth/2), int(self.maxheight/2)]
if self.cpos[0] > self.maxwidth:
if self.wrap:
self.cpos[0] -= self.maxwidth
else:
self.cpos[0] = self.maxwidth
if self.cpos[1] > self.maxheight:
if self.wrap:
self.cpos[1] -= self.maxheight
else:
self.cpos[1] = self.maxheight
if self.cpos[0] < 0:
if self.wrap:
self.cpos[0] += self.maxwidth
else:
self.cpos[0] = 0
if self.cpos[1] < 0:
if self.wrap:
self.cpos[1] += self.maxheight
else:
self.cpos[1] = 0
if _args_.debug_mouse:
log.info("mouse {} {:2} {}".format(self.cpos, self.i_accel, self.accel[self.i_accel]))
return dx, dy
def process_clicks(self):
click = 0
for i, btn in self.btn.items():
if btn['f'] is None:
continue
if btn['s'] > 0:
btn['s'] -= 1
if btn['s'] == 0:
if btn['f'].button_down():
if i == 1 and _args_.stickyclick:
btn['s'] = -1
if i == 2:
btn['s'] = 1
elif btn['s'] < 0:
if btn['f'].button_up():
btn['s'] = 0
if btn['s'] < 0:
click |= 1 << (i - 1)
elif btn['s'] == 0 and btn['f'].button_down():
if i != 1:
btn['s'] = int(round(_fps_.fps() * .4))
click |= 1 << (i - 1)
self._click = click
if _args_.debug_mouse and click:
log.info('click {}'.format(click))
return click
def process_pause(self):
btn = self.pausebtn
if btn['f'] is None:
return
if not self.face.facing_camera():
btn['s'] = 0
return
if btn['s'] > 0:
btn['s'] -= 1
if btn['f'].button_up():
# reset
btn['s'] = 0
elif btn['s'] == 0:
# wait for button up to activate
btn['s'] = -1
elif btn['s'] < 0:
# if btn['f'].button_up():
btn['s'] = 0
self.pause()
if btn['s'] == 0 and btn['f'].button_down():
btn['s'] = int(round(_fps_.fps() * 1.0))
def update(self):
self.process_pause()
if not self.paused:
dx, dy = self.process_movement()
click = self.process_clicks()
self.send_mouse_relative(click, dx, dy)
elif self.click != 0:
self._click = 0
self.send_mouse_relative(0, 0, 0)
elif self.face.shapes is not None:
# x, y = self.process_circle_pattern()
# self.send_mouse_absolute(x, y, 0)
pass
def send_keyboard(self, keys=None, lctrl=False, lshift=False, lalt=False, lgui=False, rctrl=False, rshift=False,
ralt=False, rgui=False):
if self._fd is None or _args_.debug:
return
meta = 0
meta |= 1 << 0 if lctrl else 0
meta |= 1 << 1 if lshift else 0
meta |= 1 << 2 if lalt else 0
meta |= 1 << 3 if lgui else 0