-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheye_tracker_05.py
1773 lines (1504 loc) · 72.6 KB
/
eye_tracker_05.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
import numpy as np
# from PIL import Image
from matplotlib import pyplot as plt
# %matplotlib inline
import math
import dlib
import cv2
import operator
import time
#3d face model point index
C_R_HEAR = 0
C_L_HEAR = 1
C_NOSE = 2
C_R_MOUTH= 3
C_L_MOUTH= 4
C_R_EYE = 5
C_L_EYE = 6
#2d face mappint point sequence - 68 point
RIGHT_EYE = list(range(36, 42)) # 6
LEFT_EYE = list(range(42, 48)) # 6
NOSE = list(range(27, 36)) # 9
MOUTH_OUTLINE = list(range(48, 60))
MOUTH_INNER = list(range(60, 68)) # 나는 60번이 INNER로 보임
#2d face mappint point sequence - 21 point
RIGHT_EYE_MINI = list(range(3, 9)) # 6
LEFT_EYE_MINI = list(range(9, 15)) # 6
MOUTH_OUTLINE_MINI = list(range(15, 19))
MOUTH_INNER_MINI = list(range(19, 21)) # 나는 60번이 INNER로 보임
#eye open and repeat threshold
# EYE_CLOSE_THRESH = 0.26
EYE_CLOSE_THRESH = 1.5
EYE_CLOSE_REPEAT = 15
EYE_DROWSINESS_THRESH = 0.25
EYE_DROWSINESS_REPEAT = 5
#status
RET_NOT_DETECT = 0
RET_DETECT = 1
RET_OPEN = 2
RET_CLOSE = 3
degreeToRadian = math.pi/180
radianToDegree = 180/math.pi
kGradientThreshold = 5.0
kWeightBlurSize = 3;
maxEyeSize = 8;
# SOLVER FOR PNP
cameraMatrix = np.eye(3) # A checker en fct de l'optique choisie
distCoeffs = np.zeros((5, 1))
eyeConst = 1.5
# IMAGE POI FOR 7 POINT
FacePOI = np.zeros((7, 2), dtype=np.float32)
ThreeDFacePOI = np.zeros((7, 3), dtype=np.float32)
# RIGHTHEAR
ThreeDFacePOI[C_R_HEAR, 0] = -6
ThreeDFacePOI[C_R_HEAR, 1] = 0
ThreeDFacePOI[C_R_HEAR, 2] = -8
# LEFTHEAR
ThreeDFacePOI[C_L_HEAR, 0] = 6
ThreeDFacePOI[C_L_HEAR, 1] = 0
ThreeDFacePOI[C_L_HEAR, 2] = -8
# NOSE
ThreeDFacePOI[C_NOSE, 0] = 0
ThreeDFacePOI[C_NOSE, 1] = -4
ThreeDFacePOI[C_NOSE, 2] = 2.5
# RIGHTMOUTH
ThreeDFacePOI[C_R_MOUTH, 0] = -5
ThreeDFacePOI[C_R_MOUTH, 1] = -8
ThreeDFacePOI[C_R_MOUTH, 2] = 0
# LEFTMOUTH
ThreeDFacePOI[C_L_MOUTH, 0] = 5
ThreeDFacePOI[C_L_MOUTH, 1] = -8
ThreeDFacePOI[C_L_MOUTH, 2] = 0
# RIGHTEYE
ThreeDFacePOI[C_R_EYE, 0] = -3
ThreeDFacePOI[C_R_EYE, 1] = 0
ThreeDFacePOI[C_R_EYE, 2] = -1
# LEFTEYE
ThreeDFacePOI[C_L_EYE, 0] = 3
ThreeDFacePOI[C_L_EYE, 1] = 0
ThreeDFacePOI[C_L_EYE, 2] = -1
ThreeDFacePOI2 = np.zeros((7, 3), dtype=np.float32)
# RIGHTHEAR
ThreeDFacePOI2[C_R_HEAR, 0] = -6
ThreeDFacePOI2[C_R_HEAR, 1] = 0
ThreeDFacePOI2[C_R_HEAR, 2] = -8
# LEFTHEAR
ThreeDFacePOI2[C_L_HEAR, 0] = 6
ThreeDFacePOI2[C_L_HEAR, 1] = 0
ThreeDFacePOI2[C_L_HEAR, 2] = -8
# NOSE
ThreeDFacePOI2[C_NOSE, 0] = 0
ThreeDFacePOI2[C_NOSE, 1] = 4
ThreeDFacePOI2[C_NOSE, 2] = 2.5
# RIGHTMOUTH
ThreeDFacePOI2[C_R_MOUTH, 0] = -5
ThreeDFacePOI2[C_R_MOUTH, 1] = 8
ThreeDFacePOI2[C_R_MOUTH, 2] = 0
# LEFTMOUTH
ThreeDFacePOI2[C_L_MOUTH, 0] = 5
ThreeDFacePOI2[C_L_MOUTH, 1] = 8
ThreeDFacePOI2[C_L_MOUTH, 2] = 0
# RIGHTEYE
ThreeDFacePOI2[C_R_EYE, 0] = -3.13
ThreeDFacePOI2[C_R_EYE, 1] = 0
ThreeDFacePOI2[C_R_EYE, 2] = -1
# LEFTEYE
ThreeDFacePOI2[C_L_EYE, 0] = 3.13
ThreeDFacePOI2[C_L_EYE, 1] = 0
ThreeDFacePOI2[C_L_EYE, 2] = -1
PERPROMANCE_TEST = 1
def timelap_check(title, start):
if(PERPROMANCE_TEST == 1):
print('\tTimeLap - {:s} {:.6f}'.format(title, time.time() - start))
def isRotationMatrix(R):
Rt = np.transpose(R)
shouldBeIdentity = np.dot(Rt, R)
I = np.identity(3, dtype=R.dtype)
n = np.linalg.norm(I - shouldBeIdentity)
return n < 1e-6
# Calculates rotation matrix to euler angles
# The result is the same as MATLAB except the order
# of the euler angles ( x and z are swapped ).
def rotationMatrixToEulerAngles(R):
assert (isRotationMatrix(R))
# sy = math.sqrt(R[0, 0] * R[0, 0] + R[1, 0] * R[1, 0])
sy = math.sqrt(R[2, 1] * R[2, 1] + R[2, 2] * R[2, 2])
singular = sy < 1e-6
if not singular:
x = math.atan2(R[2, 1], R[2, 2])
y = math.atan2(-R[2, 0], sy)
z = math.atan2(R[1, 0], R[0, 0])
else:
x = math.atan2(-R[1, 2], R[1, 1])
y = math.atan2(-R[2, 0], sy)
z = 0
return np.array([ x, y, z])
# Calculates Rotation Matrix given euler angles.
def eulerAnglesToRotationMatrix(theta):
R_x = np.array([[1, 0, 0],
[0, math.cos(theta[0]), -math.sin(theta[0])],
[0, math.sin(theta[0]), math.cos(theta[0])]
])
R_y = np.array([[math.cos(theta[1]), 0, math.sin(theta[1])],
[0, 1, 0],
[-math.sin(theta[1]), 0, math.cos(theta[1])]
])
R_z = np.array([[math.cos(theta[2]), -math.sin(theta[2]), 0],
[math.sin(theta[2]), math.cos(theta[2]), 0],
[0, 0, 1]
])
R = np.dot(R_z, np.dot(R_y, R_x))
return R
def calc_dist(p1, p2):
distance = math.sqrt(((p1[0] - p2[0]) ** 2) + ((p1[1] - p2[1]) ** 2))
return distance
def shape_to_np(shape, dtype="int", offset=(0,0)):
"""
Convert a facial landmark shape to a numpy array containing (x, y)-coordinates.
Args:
- shape: The facial landmark shape object.
- dtype: The data type for the numpy array (default is "int").
- offset: A tuple representing the offset to be added to each (x, y)-coordinate.
Returns:
- coords: A numpy array containing the list of (x, y)-coordinates.
"""
# initialize the list of (x, y)-coordinates
coords = np.zeros((shape.num_parts, 2), dtype=dtype)
# loop over all facial landmarks and convert them
# to a 2-tuple of (x, y)-coordinates
for i in range(0, shape.num_parts):
coords[i] = (shape.part(i).x + offset[0], shape.part(i).y + offset[1])
# return the list of (x, y)-coordinates
return coords
def analyseFace(img, detector, predictor, quality=0, offset=(0, 0)):
"""
Analyzes the face in the given image using the provided detector and predictor.
Args:
img: The input image to analyze.
detector: The face detector function.
predictor: The facial landmark predictor function.
quality: The quality parameter for the detection (default is 0).
offset: The offset tuple for adjusting the detected face position (default is (0, 0)).
Returns:
A tuple containing the analyzed face data and the additional result data, along with the training type.
"""
dets = detector(img, quality)
result = []
result_other = []
train_type = 0
for k, d in enumerate(dets):
instantFacePOI = np.zeros((7, 2), dtype=np.float32)
eyeCorners = np.zeros((2, 2, 2), dtype=np.float32)
# Get the landmarks/parts for the face in box d.
shape = predictor(img, d)
train_type = shape.num_parts
print("train_type",train_type)
if(shape.num_parts == 21): #custom training
instantFacePOI[C_R_HEAR][0] = shape.part(0).x + offset[0]
instantFacePOI[C_R_HEAR][1] = shape.part(0).y + offset[1]
instantFacePOI[C_L_HEAR][0] = shape.part(1).x + offset[0]
instantFacePOI[C_L_HEAR][1] = shape.part(1).y + offset[1]
instantFacePOI[C_NOSE][0] = shape.part(2).x + offset[0]
instantFacePOI[C_NOSE][1] = shape.part(2).y + offset[1]
instantFacePOI[C_R_MOUTH][0] = shape.part(15).x + offset[0]
instantFacePOI[C_R_MOUTH][1] = shape.part(15).y + offset[1]
instantFacePOI[C_L_MOUTH][0] = shape.part(17).x + offset[0]
instantFacePOI[C_L_MOUTH][1] = shape.part(17).y + offset[1]
leftEyeX = 0
leftEyeY = 0
for i in range(3, 9):
if (i == 3 or i == 6):
continue
leftEyeX += shape.part(i).x
leftEyeY += shape.part(i).y
leftEyeX = int(leftEyeX / 4.0)
leftEyeY = int(leftEyeY / 4.0)
eyeCorners[0][0] = [shape.part(3).x + offset[0], shape.part(3).y + offset[1]]
eyeCorners[0][1] = [shape.part(6).x + offset[0], shape.part(6).y + offset[1]]
instantFacePOI[C_R_EYE][0] = leftEyeX + offset[0]
instantFacePOI[C_R_EYE][1] = leftEyeY + offset[1]
rightEyeX = 0
rightEyeY = 0
for i in range(9, 15):
if (i == 9 or i == 12):
continue
rightEyeX += shape.part(i).x
rightEyeY += shape.part(i).y
rightEyeX = int(rightEyeX / 4.0)
rightEyeY = int(rightEyeY / 4.0)
eyeCorners[1][0] = [shape.part(9).x + offset[0], shape.part(9).y + offset[1]]
eyeCorners[1][1] = [shape.part(12).x + offset[0], shape.part(12).y + offset[1]]
instantFacePOI[C_L_EYE][0] = rightEyeX + offset[0]
instantFacePOI[C_L_EYE][1] = rightEyeY + offset[1]
data = [instantFacePOI,
(int(d.left() + offset[0]), int(d.top() + offset[1]), int(d.right() + offset[0]),int(d.bottom() + offset[1])),\
eyeCorners]
result.append(data)
p_lefteye = []
p_righteye = []
p_mouse_in = []
p_mouse_out = []
p_lefteye.extend([[shape.part(t).x + offset[0], shape.part(t).y + offset[1]] for t in LEFT_EYE_MINI])
p_righteye.extend([[shape.part(t).x + offset[0], shape.part(t).y + offset[1]] for t in RIGHT_EYE_MINI])
p_mouse_out.extend([[shape.part(t).x + offset[0], shape.part(t).y + offset[1]] for t in MOUTH_OUTLINE_MINI])
p_mouse_in.extend([[shape.part(t).x + offset[0], shape.part(t).y + offset[1]] for t in MOUTH_INNER_MINI])
result_other.append([p_lefteye, p_righteye, p_mouse_in, p_mouse_out])
else:
# oreille droite
instantFacePOI[C_R_HEAR][0] = shape.part(0).x + offset[0]
instantFacePOI[C_R_HEAR][1] = shape.part(0).y + offset[1]
# oreille gauche
instantFacePOI[C_L_HEAR][0] = shape.part(16).x + offset[0]
instantFacePOI[C_L_HEAR][1] = shape.part(16).y + offset[1]
# nez
instantFacePOI[C_NOSE][0] = shape.part(30).x + offset[0]
instantFacePOI[C_NOSE][1] = shape.part(30).y + offset[1]
# bouche gauche
instantFacePOI[C_R_MOUTH][0] = shape.part(48).x + offset[0]
instantFacePOI[C_R_MOUTH][1] = shape.part(48).y + offset[1]
# bouche droite
instantFacePOI[C_L_MOUTH][0] = shape.part(54).x + offset[0]
instantFacePOI[C_L_MOUTH][1] = shape.part(54).y + offset[1]
leftEyeX = 0
leftEyeY = 0
# for i in range(36, 42):
# leftEyeX += shape.part(i).x
# leftEyeY += shape.part(i).y
# leftEyeX = int(leftEyeX / 6.0)
# leftEyeY = int(leftEyeY / 6.0)
for i in range(37, 42):
if(i == 39):
continue
leftEyeX += shape.part(i).x
leftEyeY += shape.part(i).y
leftEyeX = int(leftEyeX / 4.0)
leftEyeY = int(leftEyeY / 4.0)
eyeCorners[0][0] = [shape.part(36).x + offset[0], shape.part(36).y + offset[1]]
eyeCorners[0][1] = [shape.part(39).x + offset[0], shape.part(39).y + offset[1]]
instantFacePOI[C_R_EYE][0] = leftEyeX + offset[0]
instantFacePOI[C_R_EYE][1] = leftEyeY + offset[1]
rightEyeX = 0
rightEyeY = 0
# for i in range(42, 48):
# rightEyeX += shape.part(i).x
# rightEyeY += shape.part(i).y
# rightEyeX = int(rightEyeX / 6.0)
# rightEyeY = int(rightEyeY / 6.0)
for i in range(43, 48):
if(i == 45):
continue
rightEyeX += shape.part(i).x
rightEyeY += shape.part(i).y
rightEyeX = int(rightEyeX / 4.0)
rightEyeY = int(rightEyeY / 4.0)
eyeCorners[1][0] = [shape.part(42).x + offset[0], shape.part(42).y + offset[1]]
eyeCorners[1][1] = [shape.part(45).x + offset[0], shape.part(45).y + offset[1]]
instantFacePOI[C_L_EYE][0] = rightEyeX + offset[0]
instantFacePOI[C_L_EYE][1] = rightEyeY + offset[1]
data = [instantFacePOI, (
int(d.left() + offset[0]), int(d.top() + offset[1]), int(d.right() + offset[0]), int(d.bottom() + offset[1])),
eyeCorners]
result.append(data)
p_lefteye = []
p_righteye = []
p_mouse_in = []
p_mouse_out = []
p_lefteye.extend([[shape.part(t).x +offset[0], shape.part(t).y+ offset[1]] for t in LEFT_EYE])
p_righteye.extend([[shape.part(t).x +offset[0], shape.part(t).y+ offset[1]] for t in RIGHT_EYE])
p_mouse_out.extend([[shape.part(t).x +offset[0], shape.part(t).y+ offset[1]] for t in MOUTH_OUTLINE])
p_mouse_in.extend([[shape.part(t).x +offset[0], shape.part(t).y+ offset[1]] for t in MOUTH_INNER])
result_other.append([p_lefteye, p_righteye, p_mouse_in, p_mouse_out])
# print('result_other', result_other)
return result, result_other, train_type
def computeGradient(img):
"""
Compute the gradient of the input image.
Args:
img: Input image as a NumPy array.
Returns:
out: Gradient of the input image as a NumPy array.
"""
# out2 = cv2.Sobel(img,cv2.CV_8U,1,0,ksize=5)
out = np.zeros((img.shape[0], img.shape[1]), dtype=np.float32) # create a receiver array
if img.shape[0] < 2 or img.shape[1] < 2: # TODO I'm not sure that secure out of range
print("EYES too small")
return out
for y in range(0, out.shape[0]):
out[y][0] = img[y][1] - img[y][0]
for x in range(1, out.shape[1] - 1):
out[y][x] = (img[y][x + 1] - img[y][x - 1]) / 2.0
out[y][out.shape[1] - 1] = img[y][out.shape[1] - 1] - img[y][out.shape[1] - 2]
# cv2.imshow("test",out)
# cv2.waitKey(0)
return out
def testPossibleCentersFormula(x, y, weight, gx, gy, out):
"""
Calculate the possible centers formula for the given input parameters.
"""
for cy in range(0, out.shape[0]):
for cx in range(0, out.shape[1]):
if x == cx and y == cy:
continue
dx = x - cx
dy = y - cy
magnitude = math.sqrt(dx * dx + dy * dy)
dx = dx / magnitude
dy = dy / magnitude
dotProduct = dx * gx + dy * gy
dotProduct = max(0.0, dotProduct)
out[cy][cx] += dotProduct * dotProduct * weight[cy][cx]
def findEyeCenter(eyeImage, offset):
"""
Find the center of the eye in the given eye image.
Args:
- eyeImage: the image of the eye
- offset: offset to be added to the result
Returns:
- Tuple of coordinates representing the center of the eye
"""
if (len(eyeImage.shape) <= 0 or eyeImage.shape[0] <= 0 or eyeImage.shape[1] <= 0):
return tuple(map(operator.add, (0, 0), offset))
if (int(eyeImage.size / (eyeImage.shape[0] * (eyeImage.shape[1]))) == 3):
eyeImg = np.asarray(cv2.cvtColor(eyeImage, cv2.COLOR_BGR2GRAY))
else:
eyeImg = eyeImage.copy() #.copy()
eyeImg = eyeImg.astype(np.float32)
scaleValue = 1.0;
if (eyeImg.shape[0] > maxEyeSize or eyeImg.shape[1] > maxEyeSize):
scaleValue = max(maxEyeSize / float(eyeImg.shape[0]), maxEyeSize / float(eyeImg.shape[1]))
eyeImg = cv2.resize(eyeImg, None, fx=scaleValue, fy=scaleValue, interpolation=cv2.INTER_AREA)
# img_int8 = img.astype(np.uint8)
# eyeImg = eyeImg.astype(np.uint8)
# eyeImg = cv2.equalizeHist(eyeImg)
# eyeImg = cv2.GaussianBlur(eyeImg, (3,3), 0)
gradientX = computeGradient(eyeImg)
gradientY = np.transpose(computeGradient(np.transpose(eyeImg)))
gradientMatrix = matrixMagnitude(gradientX, gradientY)
gradientThreshold = computeDynamicThreshold(gradientMatrix, kGradientThreshold)
# Normalisation
for y in range(0, eyeImg.shape[0]): # Iterate through rows
for x in range(0, eyeImg.shape[1]): # Iterate through columns
if (gradientMatrix[y][x] > gradientThreshold):
gradientX[y][x] = gradientX[y][x] / gradientMatrix[y][x]
gradientY[y][x] = gradientY[y][x] / gradientMatrix[y][x]
else:
gradientX[y][x] = 0.0
gradientY[y][x] = 0.0
# Invert and blur befor algo
weight = cv2.GaussianBlur(eyeImg, (kWeightBlurSize, kWeightBlurSize), 0)
for y in range(0, weight.shape[0]): # Iterate through rows
for x in range(0, weight.shape[1]): # Iterate through columns
weight[y][x] = 255 - weight[y][x]
outSum = np.zeros((eyeImg.shape[0], eyeImg.shape[1]), dtype=np.float32) # create a receiver array
for y in range(0, outSum.shape[0]): # Iterate through rows
for x in range(0, outSum.shape[1]): # Iterate through columns
if (gradientX[y][x] == 0.0 and gradientY[y][x] == 0.0):
continue
testPossibleCentersFormula(x, y, weight, gradientX[y][x], gradientY[y][x], outSum)
# scale all the values down, basically averaging them
numGradients = (weight.shape[0] * weight.shape[1]);
out = np.divide(outSum, numGradients * 10)
# find maxPoint
(minval, maxval, mincoord, maxcoord) = cv2.minMaxLoc(out)
maxcoord = (int(maxcoord[0] / scaleValue), int(maxcoord[1] / scaleValue))
return tuple(map(operator.add, maxcoord, offset))
def matrixMagnitude(gradX, gradY):
"""
Calculate the magnitude of the matrix based on the gradients gradX and gradY.
Args:
gradX: numpy array representing the x-gradient
gradY: numpy array representing the y-gradient
Returns:
numpy array: matrix of magnitudes
"""
mags = np.zeros((gradX.shape[0], gradX.shape[1]), dtype=np.float32) # create a receiver array
for y in range(0, mags.shape[0]):
for x in range(0, mags.shape[1]):
gx = gradX[y][x]
gy = gradY[y][x]
magnitude = math.sqrt(gx * gx + gy * gy)
mags[y][x] = magnitude
return mags
def computeDynamicThreshold(gradientMatrix, DevFactor):
"""
Compute dynamic threshold based on the gradient matrix and deviation factor.
Parameters:
- gradientMatrix: the input gradient matrix
- DevFactor: the deviation factor
Returns:
- float: the computed dynamic threshold
"""
(meanMagnGrad, meanMagnGrad) = cv2.meanStdDev(gradientMatrix)
stdDev = meanMagnGrad[0] / math.sqrt(gradientMatrix.shape[0] * gradientMatrix.shape[1])
return DevFactor * stdDev + meanMagnGrad[0]
def getEyePOI(eyes):
"""
Generate the points of interest (POI) for each eye in the input list of eyes.
Parameters:
- eyes: a list of tuples, where each tuple represents the coordinates of the left and right corners of the eye in the format (x, y).
Returns:
- result: a list of tuples, where each tuple represents the coordinates of the left, top, right, and bottom corners of the POI bounding box in the format (left, top, right, bottom).
"""
result = []
for eye in eyes:
left = eye[0][0]
right = eye[1][0]
middle = (eye[0][1] + eye[1][1]) / 2.0
width = eye[1][0] - eye[0][0]
height = width / 4.0
result.append((int(left), int(middle - height), int(right), int(middle + height)))
return result
def scale(rectangle, scale):
"""
Scales a rectangle by the given factor.
Parameters:
- rectangle: tuple of 4 integers representing the coordinates of the top-left and bottom-right corners of the rectangle
- scale: float representing the factor by which the rectangle should be scaled
Returns:
- tuple of 4 integers representing the coordinates of the scaled rectangle
"""
width = rectangle[2] - rectangle[0]
height = rectangle[3] - rectangle[1]
midddle = (width / 2 + rectangle[0], height / 2 + rectangle[1])
left = midddle[0] - int(scale * width / 2)
top = midddle[1] - int(scale * height / 2)
right = midddle[0] + int(scale * width / 2)
bottom = midddle[1] + int(scale * height / 2)
return (left, top, right, bottom)
def getEyePos(corners, img):
"""
A function to find the eye position based on the given corners and image.
Args:
- corners: list, the corners of the eye region
- img: array, the input image
Returns:
- list: the coordinates of the eye position
"""
# here we don't need both but the biggest one
eyes = getEyePOI(corners)
# print('corners', corners, '\neyes', eyes)
choosen = 0
eyeToConsider = eyes[0]
if ((eyes[0][0] - eyes[0][2]) > (eyes[1][0] - eyes[1][2])):
eyeToConsider = eyes[1]
choosen = 1
scalesrect = scale(eyeToConsider, 1.2)
croppedImage = img[
int(max(scalesrect[1], 0)):int(max(scalesrect[3], 0)),
int(max(scalesrect[0], 0)):int(max(scalesrect[2], 0))
]
return [findEyeCenter(croppedImage, [scalesrect[0], scalesrect[1]]), corners[choosen]]
def getEyePos2(corners, img, left_or_right=0):
"""
A function to get the eye position with the option to choose left or right eye.
:param corners: list of corner coordinates
:param img: input image
:param left_or_right: integer indicating left (0) or right (1) eye, default is 0
:return: list containing the eye center and the corner coordinates of the chosen eye
"""
# here we don't need both but the biggest one
eyes = getEyePOI(corners)
# print('corners', corners, '\neyes', eyes)
if(left_or_right == 0):
choosen = 0
eyeToConsider = eyes[0]
elif(left_or_right == 1):
choosen = 1
eyeToConsider = eyes[1]
else:
assert(1)
scalesrect = scale(eyeToConsider, 1.2)
croppedImage = img[
int(max(scalesrect[1], 0)):int(max(scalesrect[3], 0)),
int(max(scalesrect[0], 0)):int(max(scalesrect[2], 0))
]
return [findEyeCenter(croppedImage, [scalesrect[0], scalesrect[1]]), corners[choosen]]
#############
def sub_eyecenter_and_pupilcenter(tFacePOI, pupilcenter, cameraMatrix, tproj_matrix):
"""
A function to calculate the sub eyecenter and pupilcenter using the given parameters and return the result.
"""
print("//////////sub_eyecenter_and_pupilcenter")
print('FacePOI[5]',tFacePOI[6], pupilcenter[0], pupilcenter[1])
# print('//////', np.asmatrix(proj_matrix).I)
#inverse matrix
# tmatrix = np.eye(4)
# tmatrix[0:3,0:3] = rt
# tmatrix[0:3,3] = tvec.T
# tmatrix = np.asmatrix(tmatrix)
# tmatrix_inv = tmatrix.I
# print('tmatrix', tmatrix)
# print('tmatrix_inv', tmatrix_inv)
# print(np.ones((tFacePOI.shape[0], tFacePOI.shape[1]+1)))
imgpos_face = np.ones((tFacePOI.shape[0], tFacePOI.shape[1]+1))
imgpos_face[:,0:2] = tFacePOI
print('image_face',imgpos_face)
a = np.asmatrix(tproj_matrix).I * np.asmatrix(cameraMatrix).I * np.float32(imgpos_face).T
a = a / a[3]
print(a)
b = np.asmatrix(tproj_matrix).I * np.asmatrix(cameraMatrix).I * np.float32([[tFacePOI[6][0], tFacePOI[6][1], 1], [pupilcenter[0], pupilcenter[1], 1]]).T
b = b / b[3]
print(b)
print(np.subtract(b[0:-1,1], b[0:-1,0]))
return np.subtract(b[0:-1,1], b[0:-1,0]), b
def rotMatFromEye(eyeData):
"""
A function to calculate the rotation matrix from eye data.
Parameters:
eyeData (array): The input eye data containing position and axis information.
Returns:
array: The rotation matrix calculated from the eye data.
"""
# print eyeData
# eyeDiameter = eyeConst * Distance(eyeData[1][0], eyeData[1][1])
eyeCenter = ((eyeData[1][0][0] + eyeData[1][1][0]) / 2.0, (eyeData[1][0][1] + eyeData[1][1][1]) / 2.0)
eyePos = eyeData[0]
# HERE WE CONSTRUCT A MATRIX OF A BASE WHERE THE UNIT IS THE DIAMETER OF THE EYE AND AXIS OF THIS
mainEyeAxis = ((eyeData[1][0][0] - eyeData[1][1][0]), (eyeData[1][0][1] - eyeData[1][1][1]))
secondEyeAxis = perpendicular(mainEyeAxis)
reverseTransitionMatrix = (mainEyeAxis, secondEyeAxis)
transitionMatrix = np.linalg.inv(reverseTransitionMatrix)
print('transitionMatrix', transitionMatrix)
eyeCenterInEyeRef = np.dot(transitionMatrix, eyeCenter)
eyeCenterInEyeRef[1] = eyeCenterInEyeRef[1] + 0.2
eyePosInEyeRef = np.dot(transitionMatrix, eyePos)
eyeOffset = eyePosInEyeRef - eyeCenterInEyeRef
eyeOffset = [clamp(eyeOffset[0], -0.99, 0.99), clamp(eyeOffset[1], -0.99, 0.99)]
# Now we get the rotation values
thetay = -np.arcsin(eyeOffset[0]) * eyeConst
thetax = np.arcsin(eyeOffset[1]) * eyeConst
print('각도', thetax*radianToDegree, thetay*radianToDegree)
# Aaand the rotation matrix
rot = eulerAnglesToRotationMatrix([thetax, thetay, 0])
# print rot
return rot
# Given the data from a faceExtract
def getCoordFromFace(FacePOI, eyeData, img, cameraMatrix, distCoeffs):
"""
This function takes in FacePOI, eyeData, img, cameraMatrix, and distCoeffs as parameters and returns tview_point, nose_end_point2D, leye_end_point2D, imgpts, lpupil_end_point2D, leyeball_to_pupil_point2D, leyeball_to_pupil_point2D2.
"""
print("\n//////////////getCoordFromFace")
# SOLVER FOR PNPs
retval, rvec, tvec = cv2.solvePnP(ThreeDFacePOI2, FacePOI, cameraMatrix, distCoeffs);
# rvec[0] = rvec[0]+3.14/10 # roll임 - world coordinate가 y가 위로 +일경우
# rvec[1] = rvec[1]+3.14/10 # yaw임 (얼굴이 왼쪽으로 +a , 얼굴이 오른쪽으로 -a)
# rvec[2] = rvec[2]+3.14/10 # pitch임 (얼굴이 위쪽으로 +a , 얼굴이 아래쪽으로 -a)
rt, jacobian = cv2.Rodrigues(rvec)
rot2 = rotMatFromEye(eyeData)
origin = [tvec[0][0], tvec[1][0], tvec[2][0]]
headDir = np.dot(rot2, np.dot(rt, [0, 0, 1]))
camPlaneOrthVector = [0, 0, 1]
pointOnPlan = [0, 0, 0]
tview_point = intersectionWithPlan(origin, headDir, camPlaneOrthVector, pointOnPlan)
print('tview_point',tview_point)
temp = np.dot(rt, [0, 0, 1])
print("eyeData", eyeData[0])
print("head rot ", rvec.T*radianToDegree)
# print("head rot yaw", np.dot(rt, [0, 0, 1])*radianToDegree)
# print("head rot tilt", np.dot(rt, [1, 0, 0])*radianToDegree)
# print("test", np.dot(rt, [0, 0, 1])[0], np.dot(rt, [0, 0, 1])[1], np.dot(rt, [0, 0, 1])[2], math.atan2(temp[1], temp[0])* radianToDegree)
# if(math.atan2(temp[1], temp[0]) * radianToDegree-90 < 0):
# print('yaw',360 + (math.atan2(temp[1], temp[0]) * radianToDegree-90))
# else:
# print('yaw', math.atan2(temp[1], temp[0]) * radianToDegree-90)
# print('pitch',-(math.atan2(temp[2], np.sqrt(temp[0]*temp[0]+ temp[1]*temp[1]))* radianToDegree))
print('head trans [{:03.2f}, {:03.2f}, {:03.2f}]'.format(tvec[0][0], tvec[1][0], tvec[2][0]))
axis = np.float32([[10, 0, 0],
[0, 10, 0],
[0, 0, 10]]) + ThreeDFacePOI2[2] #nose
imgpts, jac = cv2.projectPoints(axis, rvec, tvec, cameraMatrix, distCoeffs)
# modelpts, jac2 = cv2.projectPoints(ThreeDFacePOI2, rvec, tvec, cameraMatrix, distCoeffs)
rvec_matrix = cv2.Rodrigues(rvec)[0]
# proj_matrix = np.hstack((np.dot(rot2, rt), tvec))
proj_matrix = np.hstack((rvec_matrix, tvec))
eulerAngles = cv2.decomposeProjectionMatrix(proj_matrix)
print('eulerAngles', eulerAngles[6])
pitch, yaw, roll = [math.radians(_) for _ in eulerAngles[6]]
# xpan = np.asmatrix([math.cos(pitch), math.sin(pitch), 0])
# # xpan = xpan.reshape(1,3)
# xw = np.dot(np.asmatrix(rt).I, [0, 0, 1])
# print('roll', xw, ' data', xpan.T)
# print(np.dot(xw, xpan.T))
# roll2 = math.acos(np.dot(xw, xpan.T))
# if (xw[0:1,2] < 0):
# roll2 = -roll2;
# # print("xw[2]", xw[0:1,2])
# print('roll2', roll2)
pitch = math.degrees(math.asin(math.sin(pitch)))
roll = -math.degrees(math.asin(math.sin(roll)))
yaw = math.degrees(math.asin(math.sin(yaw)))
print('pitch_ {:.02f}, yaw_ {:.02f}, roll_ {:.02f}'.format(pitch,yaw,roll))
# cv2.putText(img, '^pitch {:.02f}, yaw {:.02f}, roll {:.02f}'.format(math.degrees(math.asin(math.sin(rvec[0]))), math.degrees(math.asin(math.sin(rvec[1]))), -math.degrees(math.asin(math.sin(rvec[2])))),
# (int(eyeData[0][0] - 250), int(eyeData[0][1] - 120)),
# cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), thickness=2, lineType=8)
cv2.putText(img, '^pitch {:.02f}, yaw {:.02f}, roll {:.02f}'.format(math.degrees(math.asin(math.sin(rvec[0]))), math.degrees(math.asin(math.sin(rvec[1]))), -math.degrees(math.asin(math.sin(rvec[2])))),
(10, 40),
cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), thickness=2, lineType=8)
# cv2.putText(img, ' pitch {:.02f}, yaw {:.02f}, roll {:.02f}'.format(pitch, yaw, roll),
# (int(eyeData[0][0] - 250), int(eyeData[0][1] - 60)),
# cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), thickness=2, lineType=8)
cv2.putText(img, ' pitch {:.02f}, yaw {:.02f}, roll {:.02f}'.format(pitch, yaw, roll),
(10, 70),
cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), thickness=2, lineType=8)
nose_end_point2D, jacobian = cv2.projectPoints(np.array([ThreeDFacePOI2[2]]),rvec, tvec, cameraMatrix, distCoeffs)
# print(nose_end_point2D)
leye_end_point2D, jacobian = cv2.projectPoints(np.array([(3.0, 0.0, 25.0)]), rvec, tvec, cameraMatrix, distCoeffs)
# print(reye_end_point2D)
# pose estimation
# self.axis = np.float32([[3, 0, 0], [0, 3, 0], [0, 0, -3]]).reshape(-1, 3)
retGap, retGapCoord = sub_eyecenter_and_pupilcenter(FacePOI, eyeData[0], cameraMatrix, proj_matrix)
print(np.array([(3.0, 0.0, 25.0)] + retGap.T))
rvec_pupil = cv2.Rodrigues(np.dot(rot2,rt))[0]
lpupil_end_point2D, jacobian = cv2.projectPoints(np.array([(3.0, 0.0, 25.0)]), rvec_pupil, tvec+retGap, cameraMatrix, distCoeffs)
K = 1.31 #distance between eyeball center and pupil center
K0 = 0.53 #cornea radius
tretGap = np.array(retGap)
# tretGap[2] = 0
tretGapCoord = np.array(retGapCoord.T[1])[0][0:3]
tretGapCoord[2] = 0
print('retGapCoord', np.array(retGapCoord.T[1])[0][0:3])
taa = np.array([ThreeDFacePOI2[6]]) - np.array([(0, 0, K)])
tbb = np.array([ThreeDFacePOI2[6]]) + tretGap.T
# tbb = np.array([ThreeDFacePOI2[6]]) + tretGapCoord
tcc = np.array([ThreeDFacePOI2[6]])
temp2 = cv2.Rodrigues(tcc - taa)[0]
print('temp2',temp2, tcc - taa)
print('taa',taa)
print('tbb',tbb)
print('tbb-taa',(tbb - taa))
print('tcc-taa',(tcc - taa))
aaa = np.array(tbb - taa)
bbb = np.array(tcc - taa)
calc_ang = np.dot(aaa[0],bbb[0])
print(calc_ang)
calc_ang2 = np.sqrt(aaa[0][0]*aaa[0][0]+aaa[0][1]*aaa[0][1]+aaa[0][2]*aaa[0][2]) * np.sqrt(bbb[0][0]*bbb[0][0]+bbb[0][1]*bbb[0][1]+bbb[0][2]*bbb[0][2])
tang = np.arccos(calc_ang/ calc_ang2)
print('tang',tang*radianToDegree)
temp = cv2.Rodrigues(tbb - taa)[0]
print(temp)
print("norm", cv2.norm(tbb - taa))
xx = np.arccos((tbb - taa)/cv2.norm(tbb - taa))
print('x ang', xx * radianToDegree)
temp3d = np.array([taa, tbb, (tbb - taa) *10+ taa])
print(temp3d)
tangle = math.atan2(cv2.norm(np.cross(aaa, bbb)), np.dot(aaa, bbb.T))
print(tangle*radianToDegree)
leyeball_to_pupil_point2D2, jacobian = cv2.projectPoints(temp3d, rvec, tvec,
cameraMatrix, distCoeffs)
print('leyeball_to_pupil_point2D2',leyeball_to_pupil_point2D2)
leyeball_to_pupil_point2D = intersectionWithPlan(origin, np.dot(cv2.Rodrigues(xx)[0], np.dot(rt, [0, 0, 1])), camPlaneOrthVector, pointOnPlan)
print('leyeball_to_pupil_point2D',leyeball_to_pupil_point2D)
# tview_point = intersectionWithPlan(origin , headDir, camPlaneOrthVector, pointOnPlan)
# print('tview_point',np.array(tview_point).ravel())
return tview_point, nose_end_point2D, leye_end_point2D, imgpts, lpupil_end_point2D, leyeball_to_pupil_point2D, leyeball_to_pupil_point2D2
def perpendicular(a):
"""
Calculate the perpendicular vector to the input vector 'a' in 2D space.
:param a: numpy array representing the input vector
:return: numpy array representing the perpendicular vector
"""
b = np.empty_like(a)
b[0] = -a[1]
b[1] = a[0]
return b
def clamp(n, minn, maxn):
"""
A function that clamps a value within a specified range defined by minn and maxn parameters.
Parameters:
- n: The value to be clamped
- minn: The lower bound of the range
- maxn: The upper bound of the range
Returns:
- The clamped value within the specified range
"""
if n < minn:
return minn
elif n > maxn:
return maxn
else:
return n
def intersectionWithPlan(linePoint, lineDir, planOrth, planPoint):
"""
Calculate the intersection point of a line with a plane.
Parameters:
- linePoint: the point on the line
- lineDir: the direction vector of the line
- planOrth: the normal vector of the plane
- planPoint: a point on the plane
Returns:
- intersectionPoint: the point of intersection between the line and the plane
"""
d = np.dot(np.subtract(linePoint, planPoint), planOrth) / (np.dot(lineDir, planOrth))
intersectionPoint = np.subtract(np.multiply(d, lineDir), linePoint)
return intersectionPoint
def draw_xyz_axis(img, corners, imgpts):
"""
Draw XYZ axis on the image based on the provided corners and image points.
Args:
- img: The input image
- corners: The corners of the object in the image
- imgpts: The image points
Returns:
- img: The image with XYZ axis drawn on it
"""
corner = tuple(corners[0].ravel())
# print(corner)
# print(tuple(imgpts[0].ravel()))
img = cv2.line(img, corner, tuple(imgpts[0].ravel()), (255, 0, 0), 3)
img = cv2.line(img, corner, tuple(imgpts[1].ravel()), (0, 255, 0), 3)
img = cv2.line(img, corner, tuple(imgpts[2].ravel()), (0, 0, 255), 3)
return img
def getIntersection(line1, line2):
"""
Calculate the intersection point of two lines given by the endpoints line1 and line2.
Args:
line1: A tuple representing the endpoints of the first line.
line2: A tuple representing the endpoints of the second line.
Returns:
A tuple containing the x and y coordinates of the intersection point, or False if the lines are parallel.
"""
s1 = np.array(line1[0])
e1 = np.array(line1[1])
s2 = np.array(line2[0])
e2 = np.array(line2[1])
a1 = (s1[1] - e1[1]) / (s1[0] - e1[0])
b1 = s1[1] - (a1 * s1[0])
a2 = (s2[1] - e2[1]) / (s2[0] - e2[0])
b2 = s2[1] - (a2 * s2[0])
if abs(a1 - a2) < 1e-8:
return False
x = (b2 - b1) / (a1 - a2)
y = a1 * x + b1
return (x, y)
#############
class eyeTracker(object):
def __init__(self, predictor_path):
self.EyeCloseCounter = 0
twidth = 640
theight = 480
tmaxSize = max(twidth, theight)
tK = np.array([[tmaxSize, 0, twidth / 2.0], [0, tmaxSize, theight / 2.0], [0, 0, 1]], np.float32)
tD = np.zeros((5,1))
self.initilaize_calib(tK, tD)
self.initialize_p3dmodel(ThreeDFacePOI2)
self.initilaize_training_path(predictor_path)
#preprocess
self.faces_eye = []
self.faces_status = []
self.faces_point = []
#algo_data
self.mEye_centers_r = []
self.mEye_centers_l = []
self.mRT = []
self.mEularAngle = []
self.mLandmark_2d = []
self.mEyeballgaze_l=[]
self.mEyeballgaze_r = []
self.mViewpoint_2d_l = []
self.mViewpoint_2d_r = []
self.mVpoint_2d_l = []
self.mVpoint_2d_r = []
pass
def initilaize_training_path(self, predictor_path):
# predictor_path = './dlib/shape_predictor_68_face_landmarks.dat'
# predictor_path = './dlib/shape_predictor_5_face_landmarks.dat'
# face_rec_model_path = './dlib/dlib_face_recognition_resnet_model_v1.dat'
self.detector = dlib.get_frontal_face_detector()
self.predictor = dlib.shape_predictor(predictor_path)
# self.facerec = dlib.face_recognition_model_v1(face_rec_model_path)
def initilaize_calib(self, tCameraMatrix, tDistCoeffs):
# cameraMatrix = np.eye(3) # A checker en fct de l'optique choisie
# distCoeffs = np.zeros((5, 1))
self.cameraMatrix = tCameraMatrix
self.distCoeffs = tDistCoeffs
print(cameraMatrix, distCoeffs)
pass
def initialize_p3dmodel(self, paramPOI):
# tparamPOI = np.zeros((7, 3), dtype=np.float32)
# # RIGHTHEAR
# tparamPOI[0] = [-6., 0., -8.]
# # LEFTHEAR
# tparamPOI[1] = [6., 0., -8.]
# # NOSE
# tparamPOI[2] = [0., 4., 2.5]
# # RIGHTMOUTH
# tparamPOI[3] = [-5., 8., 0.]
# # LEFTMOUTH
# tparamPOI[4] = [5., 8., 0.]
# # RIGHTEYE
# tparamPOI[5] = [-3.5, 0., -1.]
# # LEFTEYE
# tparamPOI[6] = [3.5, 0., -1.]
self.ref_p3dmodel = paramPOI
def preprocess(self, image, activeROI):
"""
Preprocesses an image using the provided active region of interest (ROI).
Args:
image: The input image to be preprocessed.
activeROI: The active region of interest (ROI) in the image.
Returns:
int: The number of detected faces in the preprocessed image.
"""
x = activeROI[0]
y = activeROI[1]
w = activeROI[2]