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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import cv2
|
| 2 |
+
from mediapipe.tasks import python
|
| 3 |
+
from mediapipe.tasks.python import vision
|
| 4 |
+
from mediapipe import Image, ImageFormat
|
| 5 |
+
import numpy as np
|
| 6 |
+
import urllib.request
|
| 7 |
+
import csv
|
| 8 |
+
|
| 9 |
+
### ÉTAPE 1 : CHARGER LE MODÈLE MEDIAPIPE ###
|
| 10 |
+
|
| 11 |
+
urllib.request.urlretrieve(
|
| 12 |
+
"https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task",
|
| 13 |
+
"face_landmarker.task"
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
### ÉTAPE 2 : CONFIGURATION DU MODÈLE ###
|
| 17 |
+
|
| 18 |
+
options = vision.FaceLandmarkerOptions( # Configuration d'un modèle de détection de visage
|
| 19 |
+
base_options = python.BaseOptions(model_asset_path="face_landmarker.task"), # Indique le chemin vers le fichier du modèle
|
| 20 |
+
running_mode=vision.RunningMode.VIDEO, # Activation du mode vidéo
|
| 21 |
+
num_faces = 1, # Nombre de visage à détecter
|
| 22 |
+
min_face_detection_confidence = 0.7, # Seuil minimum de confiance
|
| 23 |
+
min_tracking_confidence = 0.5) # Seuil de confiance dans le tracking
|
| 24 |
+
|
| 25 |
+
detector = vision.FaceLandmarker.create_from_options(options) # Création du détecteur
|
| 26 |
+
|
| 27 |
+
### ÉTAPE 3 : CHARGER LA VIDÉO ###
|
| 28 |
+
|
| 29 |
+
video_path = "video.mp4" # Chemin de la vidéo
|
| 30 |
+
cap = cv2.VideoCapture(video_path) # Créer un objet qui permet de lire la vidéo frame par frame
|
| 31 |
+
|
| 32 |
+
fps = cap.get(cv2.CAP_PROP_FPS) # Récupère le nombre de frame par seconde de la vidéo
|
| 33 |
+
frame_index = 0 # Initialise un compteur de frame
|
| 34 |
+
|
| 35 |
+
### ÉTAPE 4 : CRÉATION DU FICHIER CSV ###
|
| 36 |
+
|
| 37 |
+
csv_file = open("resultats.csv", "w", newline="", encoding="utf-8") # Crée/Ouvre un fichier csv en mode écriture
|
| 38 |
+
csv_writer = csv.writer(csv_file) # Crée un objet pour écrire sur le fichier csv
|
| 39 |
+
|
| 40 |
+
csv_writer.writerow([
|
| 41 |
+
"timestamp", "bouche", "oeil_g", "oeil_d",
|
| 42 |
+
"pitch", "yaw", "roll", "norm_x", "norm_y" #Écrit l'en-tête du fichier
|
| 43 |
+
])
|
| 44 |
+
|
| 45 |
+
### FONCTIONS UTILITAIRES ###
|
| 46 |
+
|
| 47 |
+
def generic_optic(width, height):
|
| 48 |
+
focal_length = width # Estimation d'une optique générique en fonction d'une largeur et d'un centre moyens
|
| 49 |
+
cx, cy = width / 2, height / 2
|
| 50 |
+
camera_matrix = np.array([
|
| 51 |
+
[focal_length, 0, cx],
|
| 52 |
+
[0, focal_length, cy],
|
| 53 |
+
[0, 0, 1 ]
|
| 54 |
+
], dtype=np.float64)
|
| 55 |
+
|
| 56 |
+
dist_coeffs = np.zeros((4, 1)) # Définition des distortions de l'objectif à 0
|
| 57 |
+
|
| 58 |
+
return camera_matrix, dist_coeffs
|
| 59 |
+
|
| 60 |
+
def compute_head_pose(landmarks, frame_w, frame_h):
|
| 61 |
+
|
| 62 |
+
model_points = np.array([ # Modèle 3D générique d'un visage humain moyen
|
| 63 |
+
[0.0, 0.0, 0.0 ], # Bout du nez
|
| 64 |
+
[0.0, -330.0, -65.0 ], # Menton
|
| 65 |
+
[-225.0, 170.0, -135.0], # Coin oeil gauche
|
| 66 |
+
[225.0, 170.0, -135.0], # Coin oeil droit
|
| 67 |
+
[-150.0,-150.0, -125.0], # Coin bouche gauche
|
| 68 |
+
[150.0, -150.0, -125.0], # Coin bouche droit
|
| 69 |
+
], dtype=np.float64)
|
| 70 |
+
|
| 71 |
+
indices = [1, 152, 33, 263, 61, 291] # Indices des landmarks correspondant à ces derniers
|
| 72 |
+
|
| 73 |
+
image_points = np.array([ # Récupère la position 2D des 6 landmarks et les convertit en pixels
|
| 74 |
+
[landmarks[i].x * frame_w, landmarks[i].y * frame_h]
|
| 75 |
+
for i in indices
|
| 76 |
+
], dtype=np.float64)
|
| 77 |
+
|
| 78 |
+
camera_matrix, dist_coeffs = generic_optic(frame_w, frame_h)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
success, rotation_vec, translation_vec = cv2.solvePnP( # Permet de trouver l'orientation de la tête à partir des différents points
|
| 82 |
+
model_points, image_points, camera_matrix, dist_coeffs,
|
| 83 |
+
flags=cv2.SOLVEPNP_ITERATIVE
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
if not success: # Si détection ne marche pas alors ne renvoie rien
|
| 87 |
+
return None, None, None, None, None
|
| 88 |
+
|
| 89 |
+
rotation_mat, _ = cv2.Rodrigues(rotation_vec) # Conversion vecteur rotation -> matrice -> angles d'Euler
|
| 90 |
+
pose_mat = cv2.hconcat([rotation_mat, translation_vec])
|
| 91 |
+
_, _, _, _, _, _, euler_angles = cv2.decomposeProjectionMatrix(pose_mat)
|
| 92 |
+
|
| 93 |
+
pitch = euler_angles[0, 0] # Haut / bas
|
| 94 |
+
yaw = euler_angles[1, 0] # Gauche / droite
|
| 95 |
+
roll = euler_angles[2, 0] # Inclinaison latérale
|
| 96 |
+
|
| 97 |
+
return pitch, yaw, roll, rotation_vec, translation_vec
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def compute_face_position(landmarks, frame_w, frame_h): # Calcule la position et la taille du visage dans l'image
|
| 101 |
+
|
| 102 |
+
xs = [lm.x for lm in landmarks]
|
| 103 |
+
ys = [lm.y for lm in landmarks]
|
| 104 |
+
|
| 105 |
+
x_min, x_max = min(xs), max(xs)
|
| 106 |
+
y_min, y_max = min(ys), max(ys)
|
| 107 |
+
|
| 108 |
+
center_x = int(((x_min + x_max) / 2) * frame_w) # Centre du visage en pixels
|
| 109 |
+
center_y = int(((y_min + y_max) / 2) * frame_h)
|
| 110 |
+
|
| 111 |
+
norm_x = ((x_min + x_max) / 2 - 0.5) * 2 # Position normalisée : 0,0 = centre de l'image, +=1 = bords
|
| 112 |
+
norm_y = ((y_min + y_max) / 2 - 0.5) * 2
|
| 113 |
+
|
| 114 |
+
face_w = int((x_max - x_min) * frame_w) # Taille de la boite en pixels
|
| 115 |
+
face_h = int((y_max - y_min) * frame_h)
|
| 116 |
+
|
| 117 |
+
face_size_ratio = ((x_max - x_min) * (y_max - y_min)) ** 0.5 # Ratio taille visage / taille image
|
| 118 |
+
|
| 119 |
+
return center_x, center_y, norm_x, norm_y, face_w, face_h, face_size_ratio, \
|
| 120 |
+
(int(x_min * frame_w), int(y_min * frame_h),
|
| 121 |
+
int(x_max * frame_w), int(y_max * frame_h)) # Renvoie la position du visage à partir des variables d'avant
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def draw_axes(frame, rotation_vec, translation_vec, camera_matrix, dist_coeffs, origin): # Affiche les axes 3D : X=rouge, Y=vert et Z=bleu
|
| 125 |
+
|
| 126 |
+
axis_length = 160.0
|
| 127 |
+
axis_points = np.array([
|
| 128 |
+
[axis_length, 0.0, 0.0 ], # X
|
| 129 |
+
[0.0, axis_length, 0.0 ], # Y
|
| 130 |
+
[0.0, 0.0, -axis_length], # Z (vers nous)
|
| 131 |
+
], dtype=np.float64)
|
| 132 |
+
|
| 133 |
+
projected, _ = cv2.projectPoints( # Projette les 3 points en coordonnées 2D
|
| 134 |
+
axis_points, rotation_vec, translation_vec,
|
| 135 |
+
camera_matrix, dist_coeffs
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
o = (int(origin[0]), int(origin[1])) # Convertit le point d'origine en un entier
|
| 139 |
+
|
| 140 |
+
cv2.arrowedLine(frame, o, (int(projected[0][0][0]), int(projected[0][0][1])), # Dessine l'axe X en rouge
|
| 141 |
+
(0, 0, 255), 2, tipLength=0.3)
|
| 142 |
+
cv2.arrowedLine(frame, o, (int(projected[1][0][0]), int(projected[1][0][1])), # Dessine l'axe Y en vert
|
| 143 |
+
(0, 255, 0), 2, tipLength=0.3)
|
| 144 |
+
cv2.arrowedLine(frame, o, (int(projected[2][0][0]), int(projected[2][0][1])), # Dessine l'axe Z en bleu
|
| 145 |
+
(255, 0, 0), 2, tipLength=0.3)
|
| 146 |
+
|
| 147 |
+
### ÉTAPE 5 : BOUCLE PRINCIPALE ###
|
| 148 |
+
|
| 149 |
+
while True:
|
| 150 |
+
ret, frame = cap.read() # Lit la frame suivante dans la vidéo
|
| 151 |
+
if not ret:
|
| 152 |
+
break
|
| 153 |
+
|
| 154 |
+
timestamp = frame_index / fps # Calcule le temps en secondes de la frame actuelle
|
| 155 |
+
frame_index += 1 # Incrémente le compteur de frame
|
| 156 |
+
|
| 157 |
+
h, w, _ = frame.shape # Extrait les dimensions de l'image
|
| 158 |
+
|
| 159 |
+
rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # Convertit l'image BGR en RGB
|
| 160 |
+
mp_image = Image(image_format=ImageFormat.SRGB, data=rgb_frame) # Englobe le tableau numpy dans un objet Iage Mediapipe
|
| 161 |
+
|
| 162 |
+
timestamp_ms = int(timestamp * 1000)
|
| 163 |
+
results = detector.detect_for_video(mp_image, timestamp_ms) # Detection des landmarks
|
| 164 |
+
|
| 165 |
+
if results.face_landmarks: # Si un visage est détécté :
|
| 166 |
+
landmarks = results.face_landmarks[0] # Récupère le premier et le seul visage détécté
|
| 167 |
+
|
| 168 |
+
mouth_open = abs(landmarks[13].y - landmarks[14].y) # Ouverture de la bouche
|
| 169 |
+
|
| 170 |
+
left_eye_open = abs(landmarks[159].y - landmarks[145].y) # Ouverture des yeux
|
| 171 |
+
right_eye_open = abs(landmarks[386].y - landmarks[374].y)
|
| 172 |
+
|
| 173 |
+
pitch, yaw, roll, rot_vec, trans_vec = compute_head_pose(landmarks, w, h) # Orientation complète de la tête (pitch / yaw / roll)
|
| 174 |
+
|
| 175 |
+
(center_x, center_y, # Position et taille du visage dans l'image
|
| 176 |
+
norm_x, norm_y,
|
| 177 |
+
face_w, face_h,
|
| 178 |
+
face_size_ratio,
|
| 179 |
+
bbox) = compute_face_position(landmarks, w, h)
|
| 180 |
+
|
| 181 |
+
print(
|
| 182 |
+
f"t={timestamp:.2f}s | "
|
| 183 |
+
f"bouche={mouth_open:.3f} | "
|
| 184 |
+
f"oeil_g={left_eye_open:.3f} | oeil_d={right_eye_open:.3f} | "
|
| 185 |
+
f"pitch={pitch:+.1f}° | yaw={yaw:+.1f}° | roll={roll:+.1f}° | "
|
| 186 |
+
f"pos=({norm_x:+.2f}, {norm_y:+.2f})"
|
| 187 |
+
)
|
| 188 |
+
csv_writer.writerow([
|
| 189 |
+
round(timestamp, 2),
|
| 190 |
+
round(mouth_open, 3),
|
| 191 |
+
round(left_eye_open, 3),
|
| 192 |
+
round(right_eye_open, 3),
|
| 193 |
+
round(pitch, 1),
|
| 194 |
+
round(yaw, 1),
|
| 195 |
+
round(roll, 1),
|
| 196 |
+
round(norm_x, 2),
|
| 197 |
+
round(norm_y, 2),
|
| 198 |
+
]) # Sauvegarde les informations de l'image dans le fichier csv
|
| 199 |
+
|
| 200 |
+
for landmark in landmarks: # Affichage des landmarks
|
| 201 |
+
x = int(landmark.x * w)
|
| 202 |
+
y = int(landmark.y * h)
|
| 203 |
+
cv2.circle(frame, (x, y), 1, (0, 255, 0), -1)
|
| 204 |
+
|
| 205 |
+
x1, y1, x2, y2 = bbox # Dessine le rectangle autour du visage
|
| 206 |
+
cv2.rectangle(frame, (x1, y1), (x2, y2), (255, 165, 0), 1)
|
| 207 |
+
|
| 208 |
+
cv2.circle(frame, (center_x, center_y), 5, (0, 165, 255), -1) # Dessine le centre du visage en orange
|
| 209 |
+
|
| 210 |
+
cv2.drawMarker(frame, (w // 2, h // 2), (128, 128, 128), # Croix au centre de l'image
|
| 211 |
+
cv2.MARKER_CROSS, 20, 1)
|
| 212 |
+
|
| 213 |
+
if rot_vec is not None: # Si compute_head_pose réussit on execute sinon on arrête pour éviter le crash
|
| 214 |
+
camera_matrix, dist_coeffs = generic_optic(w, h)
|
| 215 |
+
|
| 216 |
+
nose_tip = (int(landmarks[1].x * w), int(landmarks[1].y * h)) # Calcule la position du nez
|
| 217 |
+
draw_axes(frame, rot_vec, trans_vec, camera_matrix, dist_coeffs, nose_tip) # Dessine les axes
|
| 218 |
+
|
| 219 |
+
cv2.imshow("Motion Capture", frame) # Affiche la frame
|
| 220 |
+
if cv2.waitKey(25) & 0xFF == ord('q'): # Quitte la vidéo avec q
|
| 221 |
+
break
|
| 222 |
+
|
| 223 |
+
### ÉTAPE 6 : NETTOYAGE ###
|
| 224 |
+
|
| 225 |
+
cap.release() # Ferme la vidéo et libère la mémoire associée
|
| 226 |
+
cv2.destroyAllWindows() # Ferme la fenêtre
|
| 227 |
+
detector.close() # Libère le modèle
|
| 228 |
+
csv_file.close() # Ferme le ficher csv
|