-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathface_mesh_tracker.py
432 lines (393 loc) · 12.5 KB
/
face_mesh_tracker.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
import os
import urllib.request
import sys
import cv2
import mediapipe as mp
from mediapipe.tasks import python
from mediapipe.tasks.python import vision
from mediapipe.framework.formats import landmark_pb2
import time
import numpy as np
# import autopy
class FaceMeshTracker:
# face bounder indices
FACE_OVAL = [
10,
338,
297,
332,
284,
251,
389,
356,
454,
323,
361,
288,
397,
365,
379,
378,
400,
377,
152,
148,
176,
149,
150,
136,
172,
58,
132,
93,
234,
127,
162,
21,
54,
103,
67,
109,
]
# lips indices for Landmarks
LIPS = [
61,
146,
91,
181,
84,
17,
314,
405,
321,
375,
291,
308,
324,
318,
402,
317,
14,
87,
178,
88,
95,
185,
40,
39,
37,
0,
267,
269,
270,
409,
415,
310,
311,
312,
13,
82,
81,
42,
183,
78,
]
LOWER_LIPS = [
61,
146,
91,
181,
84,
17,
314,
405,
321,
375,
291,
308,
324,
318,
402,
317,
14,
87,
178,
88,
95,
]
UPPER_LIPS = [
185,
40,
39,
37,
0,
267,
269,
270,
409,
415,
310,
311,
312,
13,
82,
81,
42,
183,
78,
]
# Left eyes indices
LEFT_EYE = [
362,
382,
381,
380,
374,
373,
390,
249,
263,
466,
388,
387,
386,
385,
384,
398,
]
LEFT_EYEBROW = [336, 296, 334, 293, 300, 276, 283, 282, 295, 285]
LEFT_CENTER_EYE = [473]
# right eyes indices
RIGHT_EYE = [
33,
7,
163,
144,
145,
153,
154,
155,
133,
173,
157,
158,
159,
160,
161,
246,
]
RIGHT_EYEBROW = [70, 63, 105, 66, 107, 55, 65, 52, 53, 46]
RIGHT_CENTER_EYE = [468]
def __init__(
self,
model: str = None,
num_faces: int = 1,
min_face_detection_confidence: float = 0.5,
min_face_presence_confidence: float = 0.5,
min_tracking_confidence: float = 0.5,
):
"""
Initialize a FaceTracker instance.
Args:
model (str): The path to the model for face tracking.
num_faces (int): Maximum number of faces to detect.
min_face_detection_confidence (float): Minimum confidence value ([0.0, 1.0]) for successful face detection.
min_face_presence_confidence (float): Minimum confidence value ([0.0, 1.0]) for presence of a face to be tracked.
min_tracking_confidence (float): Minimum confidence value ([0.0, 1.0]) for successful face landmark tracking.
"""
self.model = model
if self.model == None:
self.model = self.download_model()
if self.model == None:
self.model = self.download_model()
self.detector = self.initialize_detector(
num_faces,
min_face_detection_confidence,
min_face_presence_confidence,
min_tracking_confidence,
)
self.mp_face_mesh = mp.solutions.face_mesh
self.mp_drawing = mp.solutions.drawing_utils
self.mp_drawing_styles = mp.solutions.drawing_styles
self.DETECTION_RESULT = None
def save_result(
self,
result: vision.FaceLandmarkerResult,
unused_output_image,
timestamp_ms: int,
fps: bool = False,
):
"""
Saves the result of the face detection.
Args:
result (vision.FaceLandmarkerResult): Result of the face detection.
unused_output_image (mp.Image): Unused.
timestamp_ms (int): Timestamp of the detection.
Returns:
None
"""
self.DETECTION_RESULT = result
def initialize_detector(
self,
num_faces: int,
min_face_detection_confidence: float,
min_face_presence_confidence: float,
min_tracking_confidence: float,
):
"""
Initializes the FaceLandmarker instance.
Args:
num_faces (int): Maximum number of faces to detect.
min_face_detection_confidence (float): Minimum confidence value ([0.0, 1.0]) for face detection to be considered successful.
min_face_presence_confidence (float): Minimum confidence value ([0.0, 1.0]) for the presence of a face for the face landmarks to be considered tracked successfully.
min_tracking_confidence (float): Minimum confidence value ([0.0, 1.0]) for the face landmarks to be considered tracked successfully.
Returns:
vision.FaceLandmarker: FaceLandmarker instance.
"""
base_options = python.BaseOptions(model_asset_path=self.model)
options = vision.FaceLandmarkerOptions(
base_options=base_options,
running_mode=vision.RunningMode.LIVE_STREAM,
num_faces=num_faces,
min_face_detection_confidence=min_face_detection_confidence,
min_face_presence_confidence=min_face_presence_confidence,
min_tracking_confidence=min_tracking_confidence,
output_face_blendshapes=True,
result_callback=self.save_result,
)
return vision.FaceLandmarker.create_from_options(options)
def draw_landmarks(
self,
image: np.ndarray,
text_color: tuple = (0, 0, 0),
font_size: int = 1,
font_thickness: int = 1,
) -> np.ndarray:
"""
Draws the face landmarks on the image.
Args:
image (numpy.ndarray): Image on which to draw the landmarks.
text_color (tuple, optional): Color of the text. Defaults to (0, 0, 0).
font_size (int, optional): Size of the font. Defaults to 1.
font_thickness (int, optional): Thickness of the font. Defaults to 1.
Returns:
numpy.ndarray: Image with the landmarks drawn.
"""
if self.DETECTION_RESULT:
# Draw landmarks.
for face_landmarks in self.DETECTION_RESULT.face_landmarks:
face_landmarks_proto = landmark_pb2.NormalizedLandmarkList()
face_landmarks_proto.landmark.extend(
[
landmark_pb2.NormalizedLandmark(
x=landmark.x, y=landmark.y, z=landmark.z
)
for landmark in face_landmarks
]
)
self.mp_drawing.draw_landmarks(
image=image,
landmark_list=face_landmarks_proto,
connections=self.mp_face_mesh.FACEMESH_TESSELATION,
landmark_drawing_spec=None,
connection_drawing_spec=self.mp_drawing_styles.get_default_face_mesh_tesselation_style(),
)
self.mp_drawing.draw_landmarks(
image=image,
landmark_list=face_landmarks_proto,
connections=self.mp_face_mesh.FACEMESH_CONTOURS,
landmark_drawing_spec=None,
connection_drawing_spec=self.mp_drawing_styles.get_default_face_mesh_contours_style(),
)
self.mp_drawing.draw_landmarks(
image=image,
landmark_list=face_landmarks_proto,
connections=self.mp_face_mesh.FACEMESH_IRISES,
landmark_drawing_spec=None,
connection_drawing_spec=self.mp_drawing_styles.get_default_face_mesh_iris_connections_style(),
)
return image
def draw_landmark_circles(
self,
image: np.ndarray,
landmark_indices: list,
circle_radius: int = 1,
circle_color: tuple = (0, 255, 0),
circle_thickness: int = 1,
) -> np.ndarray:
"""
Draws circles on the specified face landmarks on the image.
Args:
image (numpy.ndarray): Image on which to draw the landmarks.
landmark_indices (list of int): Indices of the landmarks to draw.
circle_radius (int, optional): Radius of the circles. Defaults to 1.
circle_color (tuple, optional): Color of the circles. Defaults to (0, 255, 0).
circle_thickness (int, optional): Thickness of the circles. Defaults to 1.
Returns:
numpy.ndarray: Image with the landmarks drawn.
"""
if self.DETECTION_RESULT:
# Draw landmarks.
for face_landmarks in self.DETECTION_RESULT.face_landmarks:
for i, landmark in enumerate(face_landmarks):
if i in landmark_indices:
# Convert the landmark position to image coordinates.
x = int(landmark.x * image.shape[1])
y = int(landmark.y * image.shape[0])
cv2.circle(
image,
(x, y),
circle_radius,
circle_color,
circle_thickness,
)
return image
def detect(self, frame: np.ndarray, draw: bool = False) -> np.ndarray:
"""
Detects the face landmarks in the frame.
Args:
frame (numpy.ndarray): Frame in which to detect the landmarks.
draw (bool, optional): Whether to draw the landmarks on the frame. Defaults to False.
Returns:
numpy.ndarray: Frame with the landmarks drawn.
"""
rgb_image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=rgb_image)
self.detector.detect_async(mp_image, time.time_ns() // 1_000_000)
return self.draw_landmarks(frame) if draw else frame
def get_face_landmarks(self, face_idx: int = 0, idxs: list = None) -> list:
"""
Returns the face landmarks.
Args:
face_idx (int, optional): Index of the face for which to return the landmarks. Defaults to 0.
idxs (list, optional): List of indices of the landmarks to return. Defaults to None.
Returns:
list: List of face world landmarks.
"""
if self.DETECTION_RESULT is not None:
if idxs is None:
return self.DETECTION_RESULT.face_landmarks[face_idx]
else:
return [
self.DETECTION_RESULT.face_landmarks[face_idx][idx] for idx in idxs
]
else:
return []
@staticmethod
def download_model() -> str:
"""
Download the face_landmarker task model from the mediapipe repository.
https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/latest/face_landmarker.task
Returns:
str: Path to the downloaded model.
"""
root = os.path.dirname(os.path.realpath(__file__))
# Unino to res folder
root = os.path.join(root, "..", "res")
filename = os.path.join(root, "face_landmarker.task")
if os.path.exists(filename):
print(f"O arquivo {filename} já existe, pulando o download.")
else:
base = "https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/latest/face_landmarker.task"
urllib.request.urlretrieve(base, filename)
return filename