Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

LandmarksProcessor.py 32 KB

You have to be logged in to leave a comment. Sign In
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
  1. import colorsys
  2. import math
  3. from enum import IntEnum
  4. import cv2
  5. import numpy as np
  6. import numpy.linalg as npla
  7. from core import imagelib
  8. from core import mathlib
  9. from facelib import FaceType
  10. from core.mathlib.umeyama import umeyama
  11. landmarks_2D = np.array([
  12. [ 0.000213256, 0.106454 ], #17
  13. [ 0.0752622, 0.038915 ], #18
  14. [ 0.18113, 0.0187482 ], #19
  15. [ 0.29077, 0.0344891 ], #20
  16. [ 0.393397, 0.0773906 ], #21
  17. [ 0.586856, 0.0773906 ], #22
  18. [ 0.689483, 0.0344891 ], #23
  19. [ 0.799124, 0.0187482 ], #24
  20. [ 0.904991, 0.038915 ], #25
  21. [ 0.98004, 0.106454 ], #26
  22. [ 0.490127, 0.203352 ], #27
  23. [ 0.490127, 0.307009 ], #28
  24. [ 0.490127, 0.409805 ], #29
  25. [ 0.490127, 0.515625 ], #30
  26. [ 0.36688, 0.587326 ], #31
  27. [ 0.426036, 0.609345 ], #32
  28. [ 0.490127, 0.628106 ], #33
  29. [ 0.554217, 0.609345 ], #34
  30. [ 0.613373, 0.587326 ], #35
  31. [ 0.121737, 0.216423 ], #36
  32. [ 0.187122, 0.178758 ], #37
  33. [ 0.265825, 0.179852 ], #38
  34. [ 0.334606, 0.231733 ], #39
  35. [ 0.260918, 0.245099 ], #40
  36. [ 0.182743, 0.244077 ], #41
  37. [ 0.645647, 0.231733 ], #42
  38. [ 0.714428, 0.179852 ], #43
  39. [ 0.793132, 0.178758 ], #44
  40. [ 0.858516, 0.216423 ], #45
  41. [ 0.79751, 0.244077 ], #46
  42. [ 0.719335, 0.245099 ], #47
  43. [ 0.254149, 0.780233 ], #48
  44. [ 0.340985, 0.745405 ], #49
  45. [ 0.428858, 0.727388 ], #50
  46. [ 0.490127, 0.742578 ], #51
  47. [ 0.551395, 0.727388 ], #52
  48. [ 0.639268, 0.745405 ], #53
  49. [ 0.726104, 0.780233 ], #54
  50. [ 0.642159, 0.864805 ], #55
  51. [ 0.556721, 0.902192 ], #56
  52. [ 0.490127, 0.909281 ], #57
  53. [ 0.423532, 0.902192 ], #58
  54. [ 0.338094, 0.864805 ], #59
  55. [ 0.290379, 0.784792 ], #60
  56. [ 0.428096, 0.778746 ], #61
  57. [ 0.490127, 0.785343 ], #62
  58. [ 0.552157, 0.778746 ], #63
  59. [ 0.689874, 0.784792 ], #64
  60. [ 0.553364, 0.824182 ], #65
  61. [ 0.490127, 0.831803 ], #66
  62. [ 0.42689 , 0.824182 ] #67
  63. ], dtype=np.float32)
  64. landmarks_2D_new = np.array([
  65. [ 0.000213256, 0.106454 ], #17
  66. [ 0.0752622, 0.038915 ], #18
  67. [ 0.18113, 0.0187482 ], #19
  68. [ 0.29077, 0.0344891 ], #20
  69. [ 0.393397, 0.0773906 ], #21
  70. [ 0.586856, 0.0773906 ], #22
  71. [ 0.689483, 0.0344891 ], #23
  72. [ 0.799124, 0.0187482 ], #24
  73. [ 0.904991, 0.038915 ], #25
  74. [ 0.98004, 0.106454 ], #26
  75. [ 0.490127, 0.203352 ], #27
  76. [ 0.490127, 0.307009 ], #28
  77. [ 0.490127, 0.409805 ], #29
  78. [ 0.490127, 0.515625 ], #30
  79. [ 0.36688, 0.587326 ], #31
  80. [ 0.426036, 0.609345 ], #32
  81. [ 0.490127, 0.628106 ], #33
  82. [ 0.554217, 0.609345 ], #34
  83. [ 0.613373, 0.587326 ], #35
  84. [ 0.121737, 0.216423 ], #36
  85. [ 0.187122, 0.178758 ], #37
  86. [ 0.265825, 0.179852 ], #38
  87. [ 0.334606, 0.231733 ], #39
  88. [ 0.260918, 0.245099 ], #40
  89. [ 0.182743, 0.244077 ], #41
  90. [ 0.645647, 0.231733 ], #42
  91. [ 0.714428, 0.179852 ], #43
  92. [ 0.793132, 0.178758 ], #44
  93. [ 0.858516, 0.216423 ], #45
  94. [ 0.79751, 0.244077 ], #46
  95. [ 0.719335, 0.245099 ], #47
  96. [ 0.254149, 0.780233 ], #48
  97. [ 0.726104, 0.780233 ], #54
  98. ], dtype=np.float32)
  99. mouth_center_landmarks_2D = np.array([
  100. [-4.4202591e-07, 4.4916576e-01], #48
  101. [ 1.8399176e-01, 3.7537053e-01], #49
  102. [ 3.7018123e-01, 3.3719531e-01], #50
  103. [ 5.0000089e-01, 3.6938059e-01], #51
  104. [ 6.2981832e-01, 3.3719531e-01], #52
  105. [ 8.1600773e-01, 3.7537053e-01], #53
  106. [ 1.0000000e+00, 4.4916576e-01], #54
  107. [ 8.2213330e-01, 6.2836081e-01], #55
  108. [ 6.4110327e-01, 7.0757812e-01], #56
  109. [ 5.0000089e-01, 7.2259867e-01], #57
  110. [ 3.5889623e-01, 7.0757812e-01], #58
  111. [ 1.7786618e-01, 6.2836081e-01], #59
  112. [ 7.6765373e-02, 4.5882553e-01], #60
  113. [ 3.6856663e-01, 4.4601500e-01], #61
  114. [ 5.0000089e-01, 4.5999300e-01], #62
  115. [ 6.3143289e-01, 4.4601500e-01], #63
  116. [ 9.2323411e-01, 4.5882553e-01], #64
  117. [ 6.3399029e-01, 5.4228687e-01], #65
  118. [ 5.0000089e-01, 5.5843467e-01], #66
  119. [ 3.6601129e-01, 5.4228687e-01] #67
  120. ], dtype=np.float32)
  121. # 68 point landmark definitions
  122. landmarks_68_pt = { "mouth": (48,68),
  123. "right_eyebrow": (17, 22),
  124. "left_eyebrow": (22, 27),
  125. "right_eye": (36, 42),
  126. "left_eye": (42, 48),
  127. "nose": (27, 36), # missed one point
  128. "jaw": (0, 17) }
  129. landmarks_68_3D = np.array( [
  130. [-73.393523 , -29.801432 , 47.667532 ], #00
  131. [-72.775014 , -10.949766 , 45.909403 ], #01
  132. [-70.533638 , 7.929818 , 44.842580 ], #02
  133. [-66.850058 , 26.074280 , 43.141114 ], #03
  134. [-59.790187 , 42.564390 , 38.635298 ], #04
  135. [-48.368973 , 56.481080 , 30.750622 ], #05
  136. [-34.121101 , 67.246992 , 18.456453 ], #06
  137. [-17.875411 , 75.056892 , 3.609035 ], #07
  138. [0.098749 , 77.061286 , -0.881698 ], #08
  139. [17.477031 , 74.758448 , 5.181201 ], #09
  140. [32.648966 , 66.929021 , 19.176563 ], #10
  141. [46.372358 , 56.311389 , 30.770570 ], #11
  142. [57.343480 , 42.419126 , 37.628629 ], #12
  143. [64.388482 , 25.455880 , 40.886309 ], #13
  144. [68.212038 , 6.990805 , 42.281449 ], #14
  145. [70.486405 , -11.666193 , 44.142567 ], #15
  146. [71.375822 , -30.365191 , 47.140426 ], #16
  147. [-61.119406 , -49.361602 , 14.254422 ], #17
  148. [-51.287588 , -58.769795 , 7.268147 ], #18
  149. [-37.804800 , -61.996155 , 0.442051 ], #19
  150. [-24.022754 , -61.033399 , -6.606501 ], #20
  151. [-11.635713 , -56.686759 , -11.967398 ], #21
  152. [12.056636 , -57.391033 , -12.051204 ], #22
  153. [25.106256 , -61.902186 , -7.315098 ], #23
  154. [38.338588 , -62.777713 , -1.022953 ], #24
  155. [51.191007 , -59.302347 , 5.349435 ], #25
  156. [60.053851 , -50.190255 , 11.615746 ], #26
  157. [0.653940 , -42.193790 , -13.380835 ], #27
  158. [0.804809 , -30.993721 , -21.150853 ], #28
  159. [0.992204 , -19.944596 , -29.284036 ], #29
  160. [1.226783 , -8.414541 , -36.948060 ], #00
  161. [-14.772472 , 2.598255 , -20.132003 ], #01
  162. [-7.180239 , 4.751589 , -23.536684 ], #02
  163. [0.555920 , 6.562900 , -25.944448 ], #03
  164. [8.272499 , 4.661005 , -23.695741 ], #04
  165. [15.214351 , 2.643046 , -20.858157 ], #05
  166. [-46.047290 , -37.471411 , 7.037989 ], #06
  167. [-37.674688 , -42.730510 , 3.021217 ], #07
  168. [-27.883856 , -42.711517 , 1.353629 ], #08
  169. [-19.648268 , -36.754742 , -0.111088 ], #09
  170. [-28.272965 , -35.134493 , -0.147273 ], #10
  171. [-38.082418 , -34.919043 , 1.476612 ], #11
  172. [19.265868 , -37.032306 , -0.665746 ], #12
  173. [27.894191 , -43.342445 , 0.247660 ], #13
  174. [37.437529 , -43.110822 , 1.696435 ], #14
  175. [45.170805 , -38.086515 , 4.894163 ], #15
  176. [38.196454 , -35.532024 , 0.282961 ], #16
  177. [28.764989 , -35.484289 , -1.172675 ], #17
  178. [-28.916267 , 28.612716 , -2.240310 ], #18
  179. [-17.533194 , 22.172187 , -15.934335 ], #19
  180. [-6.684590 , 19.029051 , -22.611355 ], #20
  181. [0.381001 , 20.721118 , -23.748437 ], #21
  182. [8.375443 , 19.035460 , -22.721995 ], #22
  183. [18.876618 , 22.394109 , -15.610679 ], #23
  184. [28.794412 , 28.079924 , -3.217393 ], #24
  185. [19.057574 , 36.298248 , -14.987997 ], #25
  186. [8.956375 , 39.634575 , -22.554245 ], #26
  187. [0.381549 , 40.395647 , -23.591626 ], #27
  188. [-7.428895 , 39.836405 , -22.406106 ], #28
  189. [-18.160634 , 36.677899 , -15.121907 ], #29
  190. [-24.377490 , 28.677771 , -4.785684 ], #30
  191. [-6.897633 , 25.475976 , -20.893742 ], #31
  192. [0.340663 , 26.014269 , -22.220479 ], #32
  193. [8.444722 , 25.326198 , -21.025520 ], #33
  194. [24.474473 , 28.323008 , -5.712776 ], #34
  195. [8.449166 , 30.596216 , -20.671489 ], #35
  196. [0.205322 , 31.408738 , -21.903670 ], #36
  197. [-7.198266 , 30.844876 , -20.328022 ] #37
  198. ], dtype=np.float32)
  199. FaceType_to_padding_remove_align = {
  200. FaceType.HALF: (0.0, False),
  201. FaceType.MID_FULL: (0.0675, False),
  202. FaceType.FULL: (0.2109375, False),
  203. FaceType.FULL_NO_ALIGN: (0.2109375, True),
  204. FaceType.WHOLE_FACE: (0.40, False),
  205. FaceType.HEAD: (0.70, False),
  206. FaceType.HEAD_NO_ALIGN: (0.70, True),
  207. }
  208. def convert_98_to_68(lmrks):
  209. #jaw
  210. result = [ lmrks[0] ]
  211. for i in range(2,16,2):
  212. result += [ ( lmrks[i] + (lmrks[i-1]+lmrks[i+1])/2 ) / 2 ]
  213. result += [ lmrks[16] ]
  214. for i in range(18,32,2):
  215. result += [ ( lmrks[i] + (lmrks[i-1]+lmrks[i+1])/2 ) / 2 ]
  216. result += [ lmrks[32] ]
  217. #eyebrows averaging
  218. result += [ lmrks[33],
  219. (lmrks[34]+lmrks[41])/2,
  220. (lmrks[35]+lmrks[40])/2,
  221. (lmrks[36]+lmrks[39])/2,
  222. (lmrks[37]+lmrks[38])/2,
  223. ]
  224. result += [ (lmrks[42]+lmrks[50])/2,
  225. (lmrks[43]+lmrks[49])/2,
  226. (lmrks[44]+lmrks[48])/2,
  227. (lmrks[45]+lmrks[47])/2,
  228. lmrks[46]
  229. ]
  230. #nose
  231. result += list ( lmrks[51:60] )
  232. #left eye (from our view)
  233. result += [ lmrks[60],
  234. lmrks[61],
  235. lmrks[63],
  236. lmrks[64],
  237. lmrks[65],
  238. lmrks[67] ]
  239. #right eye
  240. result += [ lmrks[68],
  241. lmrks[69],
  242. lmrks[71],
  243. lmrks[72],
  244. lmrks[73],
  245. lmrks[75] ]
  246. #mouth
  247. result += list ( lmrks[76:96] )
  248. return np.concatenate (result).reshape ( (68,2) )
  249. def transform_points(points, mat, invert=False):
  250. if invert:
  251. mat = cv2.invertAffineTransform (mat)
  252. points = np.expand_dims(points, axis=1)
  253. points = cv2.transform(points, mat, points.shape)
  254. points = np.squeeze(points)
  255. return points
  256. def get_transform_mat (image_landmarks, output_size, face_type, scale=1.0):
  257. if not isinstance(image_landmarks, np.ndarray):
  258. image_landmarks = np.array (image_landmarks)
  259. # estimate landmarks transform from global space to local aligned space with bounds [0..1]
  260. mat = umeyama( np.concatenate ( [ image_landmarks[17:49] , image_landmarks[54:55] ] ) , landmarks_2D_new, True)[0:2]
  261. # get corner points in global space
  262. g_p = transform_points ( np.float32([(0,0),(1,0),(1,1),(0,1),(0.5,0.5) ]) , mat, True)
  263. g_c = g_p[4]
  264. # calc diagonal vectors between corners in global space
  265. tb_diag_vec = (g_p[2]-g_p[0]).astype(np.float32)
  266. tb_diag_vec /= npla.norm(tb_diag_vec)
  267. bt_diag_vec = (g_p[1]-g_p[3]).astype(np.float32)
  268. bt_diag_vec /= npla.norm(bt_diag_vec)
  269. # calc modifier of diagonal vectors for scale and padding value
  270. padding, remove_align = FaceType_to_padding_remove_align.get(face_type, 0.0)
  271. mod = (1.0 / scale)* ( npla.norm(g_p[0]-g_p[2])*(padding*np.sqrt(2.0) + 0.5) )
  272. if face_type == FaceType.WHOLE_FACE:
  273. # adjust vertical offset for WHOLE_FACE, 7% below in order to cover more forehead
  274. vec = (g_p[0]-g_p[3]).astype(np.float32)
  275. vec_len = npla.norm(vec)
  276. vec /= vec_len
  277. g_c += vec*vec_len*0.07
  278. elif face_type == FaceType.HEAD:
  279. # assuming image_landmarks are 3D_Landmarks extracted for HEAD,
  280. # adjust horizontal offset according to estimated yaw
  281. yaw = estimate_averaged_yaw(transform_points (image_landmarks, mat, False))
  282. hvec = (g_p[0]-g_p[1]).astype(np.float32)
  283. hvec_len = npla.norm(hvec)
  284. hvec /= hvec_len
  285. yaw *= np.abs(math.tanh(yaw*2)) # Damp near zero
  286. g_c -= hvec * (yaw * hvec_len / 2.0)
  287. # adjust vertical offset for HEAD, 50% below
  288. vvec = (g_p[0]-g_p[3]).astype(np.float32)
  289. vvec_len = npla.norm(vvec)
  290. vvec /= vvec_len
  291. g_c += vvec*vvec_len*0.50
  292. # calc 3 points in global space to estimate 2d affine transform
  293. if not remove_align:
  294. l_t = np.array( [ g_c - tb_diag_vec*mod,
  295. g_c + bt_diag_vec*mod,
  296. g_c + tb_diag_vec*mod ] )
  297. else:
  298. # remove_align - face will be centered in the frame but not aligned
  299. l_t = np.array( [ g_c - tb_diag_vec*mod,
  300. g_c + bt_diag_vec*mod,
  301. g_c + tb_diag_vec*mod,
  302. g_c - bt_diag_vec*mod,
  303. ] )
  304. # get area of face square in global space
  305. area = mathlib.polygon_area(l_t[:,0], l_t[:,1] )
  306. # calc side of square
  307. side = np.float32(math.sqrt(area) / 2)
  308. # calc 3 points with unrotated square
  309. l_t = np.array( [ g_c + [-side,-side],
  310. g_c + [ side,-side],
  311. g_c + [ side, side] ] )
  312. # calc affine transform from 3 global space points to 3 local space points size of 'output_size'
  313. pts2 = np.float32(( (0,0),(output_size,0),(output_size,output_size) ))
  314. mat = cv2.getAffineTransform(l_t,pts2)
  315. return mat
  316. def get_rect_from_landmarks(image_landmarks):
  317. mat = get_transform_mat(image_landmarks, 256, FaceType.FULL_NO_ALIGN)
  318. g_p = transform_points ( np.float32([(0,0),(255,255) ]) , mat, True)
  319. (l,t,r,b) = g_p[0][0], g_p[0][1], g_p[1][0], g_p[1][1]
  320. return (l,t,r,b)
  321. def expand_eyebrows(lmrks, eyebrows_expand_mod=1.0):
  322. if len(lmrks) != 68:
  323. raise Exception('works only with 68 landmarks')
  324. lmrks = np.array( lmrks.copy(), dtype=np.int )
  325. # #nose
  326. ml_pnt = (lmrks[36] + lmrks[0]) // 2
  327. mr_pnt = (lmrks[16] + lmrks[45]) // 2
  328. # mid points between the mid points and eye
  329. ql_pnt = (lmrks[36] + ml_pnt) // 2
  330. qr_pnt = (lmrks[45] + mr_pnt) // 2
  331. # Top of the eye arrays
  332. bot_l = np.array((ql_pnt, lmrks[36], lmrks[37], lmrks[38], lmrks[39]))
  333. bot_r = np.array((lmrks[42], lmrks[43], lmrks[44], lmrks[45], qr_pnt))
  334. # Eyebrow arrays
  335. top_l = lmrks[17:22]
  336. top_r = lmrks[22:27]
  337. # Adjust eyebrow arrays
  338. lmrks[17:22] = top_l + eyebrows_expand_mod * 0.5 * (top_l - bot_l)
  339. lmrks[22:27] = top_r + eyebrows_expand_mod * 0.5 * (top_r - bot_r)
  340. return lmrks
  341. def get_image_hull_mask (image_shape, image_landmarks, eyebrows_expand_mod=1.0 ):
  342. hull_mask = np.zeros(image_shape[0:2]+(1,),dtype=np.float32)
  343. lmrks = expand_eyebrows(image_landmarks, eyebrows_expand_mod)
  344. r_jaw = (lmrks[0:9], lmrks[17:18])
  345. l_jaw = (lmrks[8:17], lmrks[26:27])
  346. r_cheek = (lmrks[17:20], lmrks[8:9])
  347. l_cheek = (lmrks[24:27], lmrks[8:9])
  348. nose_ridge = (lmrks[19:25], lmrks[8:9],)
  349. r_eye = (lmrks[17:22], lmrks[27:28], lmrks[31:36], lmrks[8:9])
  350. l_eye = (lmrks[22:27], lmrks[27:28], lmrks[31:36], lmrks[8:9])
  351. nose = (lmrks[27:31], lmrks[31:36])
  352. parts = [r_jaw, l_jaw, r_cheek, l_cheek, nose_ridge, r_eye, l_eye, nose]
  353. for item in parts:
  354. merged = np.concatenate(item)
  355. cv2.fillConvexPoly(hull_mask, cv2.convexHull(merged), (1,) )
  356. return hull_mask
  357. def get_image_eye_mask (image_shape, image_landmarks):
  358. if len(image_landmarks) != 68:
  359. raise Exception('get_image_eye_mask works only with 68 landmarks')
  360. h,w,c = image_shape
  361. hull_mask = np.zeros( (h,w,1),dtype=np.float32)
  362. image_landmarks = image_landmarks.astype(np.int)
  363. cv2.fillConvexPoly( hull_mask, cv2.convexHull( image_landmarks[36:42]), (1,) )
  364. cv2.fillConvexPoly( hull_mask, cv2.convexHull( image_landmarks[42:48]), (1,) )
  365. dilate = h // 32
  366. hull_mask = cv2.dilate(hull_mask, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(dilate,dilate)), iterations = 1 )
  367. blur = h // 16
  368. blur = blur + (1-blur % 2)
  369. hull_mask = cv2.GaussianBlur(hull_mask, (blur, blur) , 0)
  370. hull_mask = hull_mask[...,None]
  371. return hull_mask
  372. def get_image_mouth_mask (image_shape, image_landmarks):
  373. if len(image_landmarks) != 68:
  374. raise Exception('get_image_eye_mask works only with 68 landmarks')
  375. h,w,c = image_shape
  376. hull_mask = np.zeros( (h,w,1),dtype=np.float32)
  377. image_landmarks = image_landmarks.astype(np.int)
  378. cv2.fillConvexPoly( hull_mask, cv2.convexHull( image_landmarks[60:]), (1,) )
  379. dilate = h // 32
  380. hull_mask = cv2.dilate(hull_mask, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(dilate,dilate)), iterations = 1 )
  381. blur = h // 16
  382. blur = blur + (1-blur % 2)
  383. hull_mask = cv2.GaussianBlur(hull_mask, (blur, blur) , 0)
  384. hull_mask = hull_mask[...,None]
  385. return hull_mask
  386. def alpha_to_color (img_alpha, color):
  387. if len(img_alpha.shape) == 2:
  388. img_alpha = img_alpha[...,None]
  389. h,w,c = img_alpha.shape
  390. result = np.zeros( (h,w, len(color) ), dtype=np.float32 )
  391. result[:,:] = color
  392. return result * img_alpha
  393. def get_cmask (image_shape, lmrks, eyebrows_expand_mod=1.0):
  394. h,w,c = image_shape
  395. hull = get_image_hull_mask (image_shape, lmrks, eyebrows_expand_mod )
  396. result = np.zeros( (h,w,3), dtype=np.float32 )
  397. def process(w,h, data ):
  398. d = {}
  399. cur_lc = 0
  400. all_lines = []
  401. for s, pts_loop_ar in data:
  402. lines = []
  403. for pts, loop in pts_loop_ar:
  404. pts_len = len(pts)
  405. lines.append ( [ [ pts[i], pts[(i+1) % pts_len ] ] for i in range(pts_len - (0 if loop else 1) ) ] )
  406. lines = np.concatenate (lines)
  407. lc = lines.shape[0]
  408. all_lines.append(lines)
  409. d[s] = cur_lc, cur_lc+lc
  410. cur_lc += lc
  411. all_lines = np.concatenate (all_lines, 0)
  412. #calculate signed distance for all points and lines
  413. line_count = all_lines.shape[0]
  414. pts_count = w*h
  415. all_lines = np.repeat ( all_lines[None,...], pts_count, axis=0 ).reshape ( (pts_count*line_count,2,2) )
  416. pts = np.empty( (h,w,line_count,2), dtype=np.float32 )
  417. pts[...,1] = np.arange(h)[:,None,None]
  418. pts[...,0] = np.arange(w)[:,None]
  419. pts = pts.reshape ( (h*w*line_count, -1) )
  420. a = all_lines[:,0,:]
  421. b = all_lines[:,1,:]
  422. pa = pts-a
  423. ba = b-a
  424. ph = np.clip ( np.einsum('ij,ij->i', pa, ba) / np.einsum('ij,ij->i', ba, ba), 0, 1 )
  425. dists = npla.norm ( pa - ba*ph[...,None], axis=1).reshape ( (h,w,line_count) )
  426. def get_dists(name, thickness=0):
  427. s,e = d[name]
  428. result = dists[...,s:e]
  429. if thickness != 0:
  430. result = np.abs(result)-thickness
  431. return np.min (result, axis=-1)
  432. return get_dists
  433. l_eye = lmrks[42:48]
  434. r_eye = lmrks[36:42]
  435. l_brow = lmrks[22:27]
  436. r_brow = lmrks[17:22]
  437. mouth = lmrks[48:60]
  438. up_nose = np.concatenate( (lmrks[27:31], lmrks[33:34]) )
  439. down_nose = lmrks[31:36]
  440. nose = np.concatenate ( (up_nose, down_nose) )
  441. gdf = process ( w,h,
  442. (
  443. ('eyes', ((l_eye, True), (r_eye, True)) ),
  444. ('brows', ((l_brow, False), (r_brow,False)) ),
  445. ('up_nose', ((up_nose, False),) ),
  446. ('down_nose', ((down_nose, False),) ),
  447. ('mouth', ((mouth, True),) ),
  448. )
  449. )
  450. eyes_fall_dist = w // 32
  451. eyes_thickness = max( w // 64, 1 )
  452. brows_fall_dist = w // 32
  453. brows_thickness = max( w // 256, 1 )
  454. nose_fall_dist = w / 12
  455. nose_thickness = max( w // 96, 1 )
  456. mouth_fall_dist = w // 32
  457. mouth_thickness = max( w // 64, 1 )
  458. eyes_mask = gdf('eyes',eyes_thickness)
  459. eyes_mask = 1-np.clip( eyes_mask/ eyes_fall_dist, 0, 1)
  460. #eyes_mask = np.clip ( 1- ( np.sqrt( np.maximum(eyes_mask,0) ) / eyes_fall_dist ), 0, 1)
  461. #eyes_mask = np.clip ( 1- ( np.cbrt( np.maximum(eyes_mask,0) ) / eyes_fall_dist ), 0, 1)
  462. brows_mask = gdf('brows', brows_thickness)
  463. brows_mask = 1-np.clip( brows_mask / brows_fall_dist, 0, 1)
  464. #brows_mask = np.clip ( 1- ( np.sqrt( np.maximum(brows_mask,0) ) / brows_fall_dist ), 0, 1)
  465. mouth_mask = gdf('mouth', mouth_thickness)
  466. mouth_mask = 1-np.clip( mouth_mask / mouth_fall_dist, 0, 1)
  467. #mouth_mask = np.clip ( 1- ( np.sqrt( np.maximum(mouth_mask,0) ) / mouth_fall_dist ), 0, 1)
  468. def blend(a,b,k):
  469. x = np.clip ( 0.5+0.5*(b-a)/k, 0.0, 1.0 )
  470. return (a-b)*x+b - k*x*(1.0-x)
  471. #nose_mask = (a-b)*x+b - k*x*(1.0-x)
  472. #nose_mask = np.minimum (up_nose_mask , down_nose_mask )
  473. #nose_mask = 1-np.clip( nose_mask / nose_fall_dist, 0, 1)
  474. nose_mask = blend ( gdf('up_nose', nose_thickness), gdf('down_nose', nose_thickness), nose_thickness*3 )
  475. nose_mask = 1-np.clip( nose_mask / nose_fall_dist, 0, 1)
  476. up_nose_mask = gdf('up_nose', nose_thickness)
  477. up_nose_mask = 1-np.clip( up_nose_mask / nose_fall_dist, 0, 1)
  478. #up_nose_mask = np.clip ( 1- ( np.cbrt( np.maximum(up_nose_mask,0) ) / nose_fall_dist ), 0, 1)
  479. down_nose_mask = gdf('down_nose', nose_thickness)
  480. down_nose_mask = 1-np.clip( down_nose_mask / nose_fall_dist, 0, 1)
  481. #down_nose_mask = np.clip ( 1- ( np.cbrt( np.maximum(down_nose_mask,0) ) / nose_fall_dist ), 0, 1)
  482. #nose_mask = np.clip( up_nose_mask + down_nose_mask, 0, 1 )
  483. #nose_mask /= np.max(nose_mask)
  484. #nose_mask = np.maximum (up_nose_mask , down_nose_mask )
  485. #nose_mask = down_nose_mask
  486. #nose_mask = np.zeros_like(nose_mask)
  487. eyes_mask = eyes_mask * (1-mouth_mask)
  488. nose_mask = nose_mask * (1-eyes_mask)
  489. hull_mask = hull[...,0].copy()
  490. hull_mask = hull_mask * (1-eyes_mask) * (1-brows_mask) * (1-nose_mask) * (1-mouth_mask)
  491. #eyes_mask = eyes_mask * (1-nose_mask)
  492. mouth_mask= mouth_mask * (1-nose_mask)
  493. brows_mask = brows_mask * (1-nose_mask)* (1-eyes_mask )
  494. hull_mask = alpha_to_color(hull_mask, (0,1,0) )
  495. eyes_mask = alpha_to_color(eyes_mask, (1,0,0) )
  496. brows_mask = alpha_to_color(brows_mask, (0,0,1) )
  497. nose_mask = alpha_to_color(nose_mask, (0,1,1) )
  498. mouth_mask = alpha_to_color(mouth_mask, (0,0,1) )
  499. #nose_mask = np.maximum( up_nose_mask, down_nose_mask )
  500. result = hull_mask + mouth_mask+ nose_mask + brows_mask + eyes_mask
  501. result *= hull
  502. #result = np.clip (result, 0, 1)
  503. return result
  504. def blur_image_hull_mask (hull_mask):
  505. maxregion = np.argwhere(hull_mask==1.0)
  506. miny,minx = maxregion.min(axis=0)[:2]
  507. maxy,maxx = maxregion.max(axis=0)[:2]
  508. lenx = maxx - minx;
  509. leny = maxy - miny;
  510. masky = int(minx+(lenx//2))
  511. maskx = int(miny+(leny//2))
  512. lowest_len = min (lenx, leny)
  513. ero = int( lowest_len * 0.085 )
  514. blur = int( lowest_len * 0.10 )
  515. hull_mask = cv2.erode(hull_mask, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(ero,ero)), iterations = 1 )
  516. hull_mask = cv2.blur(hull_mask, (blur, blur) )
  517. hull_mask = np.expand_dims (hull_mask,-1)
  518. return hull_mask
  519. mirror_idxs = [
  520. [0,16],
  521. [1,15],
  522. [2,14],
  523. [3,13],
  524. [4,12],
  525. [5,11],
  526. [6,10],
  527. [7,9],
  528. [17,26],
  529. [18,25],
  530. [19,24],
  531. [20,23],
  532. [21,22],
  533. [36,45],
  534. [37,44],
  535. [38,43],
  536. [39,42],
  537. [40,47],
  538. [41,46],
  539. [31,35],
  540. [32,34],
  541. [50,52],
  542. [49,53],
  543. [48,54],
  544. [59,55],
  545. [58,56],
  546. [67,65],
  547. [60,64],
  548. [61,63] ]
  549. def mirror_landmarks (landmarks, val):
  550. result = landmarks.copy()
  551. for idx in mirror_idxs:
  552. result [ idx ] = result [ idx[::-1] ]
  553. result[:,0] = val - result[:,0] - 1
  554. return result
  555. def get_face_struct_mask (image_shape, image_landmarks, eyebrows_expand_mod=1.0, color=(1,) ):
  556. mask = np.zeros(image_shape[0:2]+( len(color),),dtype=np.float32)
  557. lmrks = expand_eyebrows(image_landmarks, eyebrows_expand_mod)
  558. draw_landmarks (mask, image_landmarks, color=color, draw_circles=False, thickness=2)
  559. return mask
  560. def draw_landmarks (image, image_landmarks, color=(0,255,0), draw_circles=True, thickness=1, transparent_mask=False):
  561. if len(image_landmarks) != 68:
  562. raise Exception('get_image_eye_mask works only with 68 landmarks')
  563. int_lmrks = np.array(image_landmarks, dtype=np.int)
  564. jaw = int_lmrks[slice(*landmarks_68_pt["jaw"])]
  565. right_eyebrow = int_lmrks[slice(*landmarks_68_pt["right_eyebrow"])]
  566. left_eyebrow = int_lmrks[slice(*landmarks_68_pt["left_eyebrow"])]
  567. mouth = int_lmrks[slice(*landmarks_68_pt["mouth"])]
  568. right_eye = int_lmrks[slice(*landmarks_68_pt["right_eye"])]
  569. left_eye = int_lmrks[slice(*landmarks_68_pt["left_eye"])]
  570. nose = int_lmrks[slice(*landmarks_68_pt["nose"])]
  571. # open shapes
  572. cv2.polylines(image, tuple(np.array([v]) for v in ( right_eyebrow, jaw, left_eyebrow, np.concatenate((nose, [nose[-6]])) )),
  573. False, color, thickness=thickness, lineType=cv2.LINE_AA)
  574. # closed shapes
  575. cv2.polylines(image, tuple(np.array([v]) for v in (right_eye, left_eye, mouth)),
  576. True, color, thickness=thickness, lineType=cv2.LINE_AA)
  577. if draw_circles:
  578. # the rest of the cicles
  579. for x, y in np.concatenate((right_eyebrow, left_eyebrow, mouth, right_eye, left_eye, nose), axis=0):
  580. cv2.circle(image, (x, y), 1, color, 1, lineType=cv2.LINE_AA)
  581. # jaw big circles
  582. for x, y in jaw:
  583. cv2.circle(image, (x, y), 2, color, lineType=cv2.LINE_AA)
  584. if transparent_mask:
  585. mask = get_image_hull_mask (image.shape, image_landmarks)
  586. image[...] = ( image * (1-mask) + image * mask / 2 )[...]
  587. def draw_rect_landmarks (image, rect, image_landmarks, face_type, face_size=256, transparent_mask=False, landmarks_color=(0,255,0)):
  588. draw_landmarks(image, image_landmarks, color=landmarks_color, transparent_mask=transparent_mask)
  589. imagelib.draw_rect (image, rect, (255,0,0), 2 )
  590. image_to_face_mat = get_transform_mat (image_landmarks, face_size, face_type)
  591. points = transform_points ( [ (0,0), (0,face_size-1), (face_size-1, face_size-1), (face_size-1,0) ], image_to_face_mat, True)
  592. imagelib.draw_polygon (image, points, (0,0,255), 2)
  593. points = transform_points ( [ ( int(face_size*0.05), 0), ( int(face_size*0.1), int(face_size*0.1) ), ( 0, int(face_size*0.1) ) ], image_to_face_mat, True)
  594. imagelib.draw_polygon (image, points, (0,0,255), 2)
  595. def calc_face_pitch(landmarks):
  596. if not isinstance(landmarks, np.ndarray):
  597. landmarks = np.array (landmarks)
  598. t = ( (landmarks[6][1]-landmarks[8][1]) + (landmarks[10][1]-landmarks[8][1]) ) / 2.0
  599. b = landmarks[8][1]
  600. return float(b-t)
  601. def estimate_averaged_yaw(landmarks):
  602. # Works much better than solvePnP if landmarks from "3DFAN"
  603. if not isinstance(landmarks, np.ndarray):
  604. landmarks = np.array (landmarks)
  605. l = ( (landmarks[27][0]-landmarks[0][0]) + (landmarks[28][0]-landmarks[1][0]) + (landmarks[29][0]-landmarks[2][0]) ) / 3.0
  606. r = ( (landmarks[16][0]-landmarks[27][0]) + (landmarks[15][0]-landmarks[28][0]) + (landmarks[14][0]-landmarks[29][0]) ) / 3.0
  607. return float(r-l)
  608. def estimate_pitch_yaw_roll(aligned_landmarks, size=256):
  609. """
  610. returns pitch,yaw,roll [-pi/2...+pi/2]
  611. """
  612. shape = (size,size)
  613. focal_length = shape[1]
  614. camera_center = (shape[1] / 2, shape[0] / 2)
  615. camera_matrix = np.array(
  616. [[focal_length, 0, camera_center[0]],
  617. [0, focal_length, camera_center[1]],
  618. [0, 0, 1]], dtype=np.float32)
  619. (_, rotation_vector, _) = cv2.solvePnP(
  620. np.concatenate( (landmarks_68_3D[:27], landmarks_68_3D[30:36]) , axis=0) ,
  621. np.concatenate( (aligned_landmarks[:27], aligned_landmarks[30:36]) , axis=0).astype(np.float32),
  622. camera_matrix,
  623. np.zeros((4, 1)) )
  624. pitch, yaw, roll = mathlib.rotationMatrixToEulerAngles( cv2.Rodrigues(rotation_vector)[0] )
  625. half_pi = math.pi / 2.0
  626. pitch = np.clip ( pitch, -half_pi, half_pi )
  627. yaw = np.clip ( yaw , -half_pi, half_pi )
  628. roll = np.clip ( roll, -half_pi, half_pi )
  629. return -pitch, yaw, roll
  630. #if remove_align:
  631. # bbox = transform_points ( [ (0,0), (0,output_size), (output_size, output_size), (output_size,0) ], mat, True)
  632. # #import code
  633. # #code.interact(local=dict(globals(), **locals()))
  634. # area = mathlib.polygon_area(bbox[:,0], bbox[:,1] )
  635. # side = math.sqrt(area) / 2
  636. # center = transform_points ( [(output_size/2,output_size/2)], mat, True)
  637. # pts1 = np.float32(( center+[-side,-side], center+[side,-side], center+[side,-side] ))
  638. # pts2 = np.float32([[0,0],[output_size,0],[0,output_size]])
  639. # mat = cv2.getAffineTransform(pts1,pts2)
  640. #if full_face_align_top and (face_type == FaceType.FULL or face_type == FaceType.FULL_NO_ALIGN):
  641. # #lmrks2 = expand_eyebrows(image_landmarks)
  642. # #lmrks2_ = transform_points( [ lmrks2[19], lmrks2[24] ], mat, False )
  643. # #y_diff = np.float32( (0,np.min(lmrks2_[:,1])) )
  644. # #y_diff = transform_points( [ np.float32( (0,0) ), y_diff], mat, True)
  645. # #y_diff = y_diff[1]-y_diff[0]
  646. #
  647. # x_diff = np.float32((0,0))
  648. #
  649. # lmrks2_ = transform_points( [ image_landmarks[0], image_landmarks[16] ], mat, False )
  650. # if lmrks2_[0,0] < 0:
  651. # x_diff = lmrks2_[0,0]
  652. # x_diff = transform_points( [ np.float32( (0,0) ), np.float32((x_diff,0)) ], mat, True)
  653. # x_diff = x_diff[1]-x_diff[0]
  654. # elif lmrks2_[1,0] >= output_size:
  655. # x_diff = lmrks2_[1,0]-(output_size-1)
  656. # x_diff = transform_points( [ np.float32( (0,0) ), np.float32((x_diff,0)) ], mat, True)
  657. # x_diff = x_diff[1]-x_diff[0]
  658. #
  659. # mat = cv2.getAffineTransform( l_t+y_diff+x_diff ,pts2)
  660. """
  661. def get_averaged_transform_mat (img_landmarks,
  662. img_landmarks_prev,
  663. img_landmarks_next,
  664. average_frame_count,
  665. average_center_frame_count,
  666. output_size, face_type, scale=1.0):
  667. l_c_list = []
  668. tb_diag_vec_list = []
  669. bt_diag_vec_list = []
  670. mod_list = []
  671. count = max(average_frame_count,average_center_frame_count)
  672. for i in range ( -count, count+1, 1 ):
  673. if i < 0:
  674. lmrks = img_landmarks_prev[i] if -i < len(img_landmarks_prev) else None
  675. elif i > 0:
  676. lmrks = img_landmarks_next[i] if i < len(img_landmarks_next) else None
  677. else:
  678. lmrks = img_landmarks
  679. if lmrks is None:
  680. continue
  681. l_c, tb_diag_vec, bt_diag_vec, mod = get_transform_mat_data (lmrks, face_type, scale=scale)
  682. if i >= -average_frame_count and i <= average_frame_count:
  683. tb_diag_vec_list.append(tb_diag_vec)
  684. bt_diag_vec_list.append(bt_diag_vec)
  685. mod_list.append(mod)
  686. if i >= -average_center_frame_count and i <= average_center_frame_count:
  687. l_c_list.append(l_c)
  688. tb_diag_vec = np.mean( np.array(tb_diag_vec_list), axis=0 )
  689. bt_diag_vec = np.mean( np.array(bt_diag_vec_list), axis=0 )
  690. mod = np.mean( np.array(mod_list), axis=0 )
  691. l_c = np.mean( np.array(l_c_list), axis=0 )
  692. return get_transform_mat_by_data (l_c, tb_diag_vec, bt_diag_vec, mod, output_size, face_type)
  693. def get_transform_mat (image_landmarks, output_size, face_type, scale=1.0):
  694. if not isinstance(image_landmarks, np.ndarray):
  695. image_landmarks = np.array (image_landmarks)
  696. # get face padding value for FaceType
  697. padding, remove_align = FaceType_to_padding_remove_align.get(face_type, 0.0)
  698. # estimate landmarks transform from global space to local aligned space with bounds [0..1]
  699. mat = umeyama( np.concatenate ( [ image_landmarks[17:49] , image_landmarks[54:55] ] ) , landmarks_2D_new, True)[0:2]
  700. # get corner points in global space
  701. l_p = transform_points ( np.float32([(0,0),(1,0),(1,1),(0,1),(0.5,0.5)]) , mat, True)
  702. l_c = l_p[4]
  703. # calc diagonal vectors between corners in global space
  704. tb_diag_vec = (l_p[2]-l_p[0]).astype(np.float32)
  705. tb_diag_vec /= npla.norm(tb_diag_vec)
  706. bt_diag_vec = (l_p[1]-l_p[3]).astype(np.float32)
  707. bt_diag_vec /= npla.norm(bt_diag_vec)
  708. # calc modifier of diagonal vectors for scale and padding value
  709. mod = (1.0 / scale)* ( npla.norm(l_p[0]-l_p[2])*(padding*np.sqrt(2.0) + 0.5) )
  710. # calc 3 points in global space to estimate 2d affine transform
  711. if not remove_align:
  712. l_t = np.array( [ np.round( l_c - tb_diag_vec*mod ),
  713. np.round( l_c + bt_diag_vec*mod ),
  714. np.round( l_c + tb_diag_vec*mod ) ] )
  715. else:
  716. # remove_align - face will be centered in the frame but not aligned
  717. l_t = np.array( [ np.round( l_c - tb_diag_vec*mod ),
  718. np.round( l_c + bt_diag_vec*mod ),
  719. np.round( l_c + tb_diag_vec*mod ),
  720. np.round( l_c - bt_diag_vec*mod ),
  721. ] )
  722. # get area of face square in global space
  723. area = mathlib.polygon_area(l_t[:,0], l_t[:,1] )
  724. # calc side of square
  725. side = np.float32(math.sqrt(area) / 2)
  726. # calc 3 points with unrotated square
  727. l_t = np.array( [ np.round( l_c + [-side,-side] ),
  728. np.round( l_c + [ side,-side] ),
  729. np.round( l_c + [ side, side] ) ] )
  730. # calc affine transform from 3 global space points to 3 local space points size of 'output_size'
  731. pts2 = np.float32(( (0,0),(output_size,0),(output_size,output_size) ))
  732. mat = cv2.getAffineTransform(l_t,pts2)
  733. return mat
  734. """
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...