Download preprocessing.py from luigui300/lsp-expression-recognition: direct link, hf CLI and curl.
- Browser
- Download file 13 kB
-
https://huggingface.co/spaces/luigui300/lsp-expression-recognition/resolve/main/preprocessing.py
- Command line
-
hf download hf://spaces/luigui300/lsp-expression-recognition/preprocessing.py
-
curl -L -o preprocessing.py https://huggingface.co/spaces/luigui300/lsp-expression-recognition/resolve/main/preprocessing.py
13 kB
| """ | |
| Preprocessing pipeline for LSP Facial Expression Recognition. | |
| Input : video file path (mp4 / mov, ~2 s, 30 fps) | |
| Output: (video_tensor (1, 16, 3, 224, 224), graphs [16 x Data]) | |
| Pipeline | |
| -------- | |
| 1. Extract all frames from video with OpenCV | |
| 2. Select 16 frames (always first, middle, last + uniform sampling) | |
| 3. Resize each frame to 224x224 (INTER_AREA) | |
| 4. Run MediaPipe FaceMesh to extract 138 landmarks per frame | |
| 5. Spatial normalization (inter-ocular distance scale, eye-midpoint center) | |
| 6. Build anatomic edge index (loop/chain/inter-region connections) | |
| 7. Return video tensor + list of PyG Data graphs | |
| """ | |
| import os | |
| import cv2 | |
| import mediapipe as mp | |
| import numpy as np | |
| import torch | |
| from PIL import Image | |
| from torchvision import transforms | |
| from torch_geometric.data import Data | |
| from torch_geometric.utils import remove_self_loops, to_undirected | |
| # Suppress MediaPipe / TensorFlow verbose logs | |
| os.environ["GLOG_minloglevel"] = "3" | |
| os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" | |
| os.environ["MEDIAPIPE_DISABLE_GPU"] = "1" | |
| # ββ Constants ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| T_FRAMES = 16 | |
| IMG_SIZE = 224 | |
| MEAN = [0.485, 0.456, 0.406] | |
| STD = [0.229, 0.224, 0.225] | |
| _to_tensor = transforms.Compose([ | |
| transforms.ToTensor(), | |
| transforms.Normalize(MEAN, STD), | |
| ]) | |
| # ββ Landmark index groups (must match training exactly) ββββββββββββββββββββββββ | |
| _contorno = [ | |
| 109, 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, | |
| ] | |
| _ceja_der = [70, 63, 105, 66, 107, 46, 53, 52, 65, 55] | |
| _ceja_izq = [336, 296, 334, 293, 300, 285, 295, 282, 283, 276] | |
| _ojo_der = [33, 246, 161, 160, 159, 158, 157, 173, 133, 155, 154, 153, 145, 144, 163, 7] | |
| _ojo_izq = [362, 398, 384, 385, 386, 387, 388, 466, 263, 249, 390, 373, 374, 380, 381, 382] | |
| _nariz = [48, 220, 4, 440, 278, 5, 195, 197, 6, 168] | |
| _boca = [62, 191, 80, 81, 82, 13, 312, 311, 310, 415, 292, 324, 318, 402, 317, 14, 87, 178, 88, 95] | |
| _labios = [57, 185, 40, 39, 37, 0, 267, 269, 270, 409, 287, 375, 321, 405, 314, 17, 84, 181, 91, 146] | |
| LANDMARK_INDICES: list = list(dict.fromkeys( | |
| _contorno + _ceja_der + _ceja_izq + | |
| _ojo_der + _ojo_izq + _nariz + _boca + _labios | |
| )) | |
| NUM_LM: int = len(LANDMARK_INDICES) # 138 | |
| # Eye center positions within LANDMARK_INDICES (for spatial normalization) | |
| _eye_r_pos = [LANDMARK_INDICES.index(i) for i in _ojo_der] | |
| _eye_l_pos = [LANDMARK_INDICES.index(i) for i in _ojo_izq] | |
| EYE_R_CENTER = _eye_r_pos[len(_eye_r_pos) // 2] | |
| EYE_L_CENTER = _eye_l_pos[len(_eye_l_pos) // 2] | |
| # ββ Frame selection ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def select_16_frames(n_frames: int, t: int = T_FRAMES) -> list: | |
| """ | |
| Select T frame indices from a clip of n_frames. | |
| Always includes first, middle, and last frame. | |
| Remaining slots filled with uniform sampling. | |
| If n_frames <= t: pad by repeating the last frame index. | |
| """ | |
| if n_frames <= t: | |
| indices = list(range(n_frames)) | |
| while len(indices) < t: | |
| indices.append(indices[-1]) | |
| return indices[:t] | |
| fixed = {0, n_frames // 2, n_frames - 1} | |
| remaining = t - len(fixed) | |
| candidates = [i for i in range(n_frames) if i not in fixed] | |
| step = len(candidates) / remaining | |
| sampled = {candidates[int(j * step)] for j in range(remaining)} | |
| return sorted(fixed | sampled)[:t] | |
| # ββ Edge index (built once, reused for all requests) ββββββββββββββββββββββββββ | |
| def build_anatomic_edge_index() -> torch.Tensor: | |
| """ | |
| Build the fixed anatomic edge index used during training. | |
| Connections: | |
| - Loop : eyes, mouth, lips | |
| - Chain : eyebrows, face contour, nose | |
| - Inter : eyebrowsβeyes, mouthβlips, noseβmouth | |
| """ | |
| def to_pos(region: list) -> list: | |
| return [LANDMARK_INDICES.index(i) for i in region if i in LANDMARK_INDICES] | |
| def chain(pos: list) -> list: | |
| return [[pos[i], pos[i + 1]] for i in range(len(pos) - 1)] | |
| def loop(pos: list) -> list: | |
| return chain(pos) + [[pos[-1], pos[0]]] | |
| def inter(a: list, b: list, n: int = 3) -> list: | |
| sa = max(1, len(a) // n) | |
| sb = max(1, len(b) // n) | |
| return [[a[min(k * sa, len(a) - 1)], b[min(k * sb, len(b) - 1)]] | |
| for k in range(n)] | |
| P = {k: to_pos(v) for k, v in { | |
| "contorno": _contorno, | |
| "ceja_der": _ceja_der, | |
| "ceja_izq": _ceja_izq, | |
| "ojo_der" : _ojo_der, | |
| "ojo_izq" : _ojo_izq, | |
| "nariz" : _nariz, | |
| "boca" : _boca, | |
| "labios" : _labios, | |
| }.items()} | |
| edges = ( | |
| loop(P["ojo_der"]) + loop(P["ojo_izq"]) + | |
| loop(P["boca"]) + loop(P["labios"]) + | |
| chain(P["ceja_der"]) + chain(P["ceja_izq"]) + | |
| chain(P["contorno"]) + chain(P["nariz"]) + | |
| inter(P["ceja_der"], P["ojo_der"]) + | |
| inter(P["ceja_izq"], P["ojo_izq"]) + | |
| inter(P["boca"], P["labios"], 4) + | |
| inter(P["nariz"], P["boca"], 2) | |
| ) | |
| ei = torch.tensor(edges, dtype=torch.long).t().contiguous() | |
| ei = to_undirected(ei) | |
| ei, _ = remove_self_loops(ei) | |
| return ei | |
| # ββ Internal helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def _get_rotation(video_path: str) -> int: | |
| """ | |
| Read rotation angle from video metadata. | |
| Returns 0, 90, 180 or 270. | |
| Falls back to 0 if the property is unavailable. | |
| """ | |
| cap = cv2.VideoCapture(video_path) | |
| try: | |
| rotation = int(cap.get(cv2.CAP_PROP_ORIENTATION_META)) | |
| except Exception: | |
| rotation = 0 | |
| cap.release() | |
| # Some versions return negative values | |
| return rotation % 360 | |
| def _fix_rotation(frame: np.ndarray, rotation: int) -> np.ndarray: | |
| """Rotate frame to correct orientation based on video metadata.""" | |
| if rotation == 90: | |
| return cv2.rotate(frame, cv2.ROTATE_90_CLOCKWISE) | |
| if rotation == 180: | |
| return cv2.rotate(frame, cv2.ROTATE_180) | |
| if rotation == 270: | |
| return cv2.rotate(frame, cv2.ROTATE_90_COUNTERCLOCKWISE) | |
| return frame | |
| def _extract_frames(video_path: str) -> list: | |
| """ | |
| Read all frames from a video file and correct rotation from metadata. | |
| Returns list of BGR numpy arrays in correct orientation. | |
| """ | |
| rotation = _get_rotation(video_path) | |
| cap = cv2.VideoCapture(video_path) | |
| if not cap.isOpened(): | |
| raise ValueError(f"Cannot open video: {video_path}") | |
| frames = [] | |
| while True: | |
| ret, frame = cap.read() | |
| if not ret: | |
| break | |
| frames.append(_fix_rotation(frame, rotation)) | |
| cap.release() | |
| if not frames: | |
| raise ValueError("Video file contains no readable frames") | |
| return frames | |
| def _normalize_landmarks(lm_seq: np.ndarray): | |
| """ | |
| Spatial normalization per sequence. | |
| - Scale XY : mean inter-ocular distance across valid frames | |
| - Center : midpoint between both eye centers (averaged over sequence) | |
| - Scale Z : std of centered Z values (isotropic depth normalization) | |
| Returns normalized array (T, NUM_LM, 3) float32, or None on failure. | |
| """ | |
| eye_dists = np.array([ | |
| np.linalg.norm(f[EYE_R_CENTER, :2] - f[EYE_L_CENTER, :2]) | |
| for f in lm_seq | |
| ]) | |
| valid_dists = eye_dists[eye_dists > 1e-6] | |
| if len(valid_dists) == 0: | |
| return None | |
| scale_xy = float(np.mean(valid_dists)) | |
| center_ref = np.mean( | |
| [(f[EYE_R_CENTER] + f[EYE_L_CENTER]) / 2.0 for f in lm_seq], axis=0 | |
| ) | |
| centered = lm_seq - center_ref | |
| scale_z = np.std(centered[:, :, 2]) | |
| if scale_z < 1e-6: | |
| return None | |
| out = centered.copy() | |
| out[:, :, :2] /= scale_xy | |
| out[:, :, 2] /= scale_z | |
| if np.isnan(out).any(): | |
| return None | |
| return out.astype(np.float32) | |
| # ββ Public API βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def preprocess_video(video_path: str, edge_index: torch.Tensor) -> tuple: | |
| """ | |
| Full preprocessing pipeline for a raw video file. | |
| Parameters | |
| ---------- | |
| video_path : path to .mp4 / .mov file | |
| edge_index : fixed anatomic edge index tensor (built at startup) | |
| Returns | |
| ------- | |
| video_tensor : torch.Tensor shape (1, 16, 3, 224, 224), normalized | |
| graphs : list of 16 torch_geometric.data.Data objects | |
| Raises | |
| ------ | |
| ValueError if any preprocessing step fails (no face detected, etc.) | |
| """ | |
| # 1. Extract frames | |
| raw_frames = _extract_frames(video_path) | |
| # 2. Select 16 frames | |
| indices = select_16_frames(len(raw_frames)) | |
| selected = [raw_frames[i] for i in indices] | |
| # 3. Resize to 224x224 | |
| resized = [ | |
| cv2.resize(f, (IMG_SIZE, IMG_SIZE), interpolation=cv2.INTER_AREA) | |
| for f in selected | |
| ] | |
| # 4. MediaPipe FaceMesh β extract 138 landmarks per frame | |
| face_mesh = mp.solutions.face_mesh.FaceMesh( | |
| static_image_mode=True, | |
| max_num_faces=1, | |
| refine_landmarks=True, | |
| min_detection_confidence=0.4, | |
| ) | |
| all_lm: list = [] | |
| prev: np.ndarray | None = None | |
| for frame_bgr in resized: | |
| frame_rgb = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB) | |
| result = face_mesh.process(frame_rgb) | |
| if result.multi_face_landmarks: | |
| lm = result.multi_face_landmarks[0] | |
| coords = np.array( | |
| [[lm.landmark[i].x, lm.landmark[i].y, lm.landmark[i].z] | |
| for i in LANDMARK_INDICES], | |
| dtype=np.float32, | |
| ) | |
| all_lm.append(coords) | |
| prev = coords | |
| else: | |
| # Forward-fill: use previous detection or zeros | |
| fallback = prev.copy() if prev is not None else np.zeros((NUM_LM, 3), dtype=np.float32) | |
| all_lm.append(fallback) | |
| face_mesh.close() | |
| lm_seq = np.stack(all_lm) # (16, 138, 3) | |
| # 5. Spatial normalization | |
| lm_norm = _normalize_landmarks(lm_seq) | |
| if lm_norm is None: | |
| raise ValueError( | |
| "Landmark normalization failed: no valid face detected in video" | |
| ) | |
| # 6. Build video tensor (1, 16, 3, 224, 224) | |
| frame_tensors = [] | |
| for frame_bgr in resized: | |
| frame_rgb = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB) | |
| pil_img = Image.fromarray(frame_rgb) | |
| frame_tensors.append(_to_tensor(pil_img)) | |
| video_tensor = torch.stack(frame_tensors).unsqueeze(0) # (1, T, C, H, W) | |
| # 7. Build graph sequence β 16 Data objects sharing the fixed edge_index | |
| lm_torch = torch.tensor(lm_norm, dtype=torch.float32) # (16, 138, 3) | |
| graphs = [ | |
| Data(x=lm_torch[t], edge_index=edge_index.clone()) | |
| for t in range(T_FRAMES) | |
| ] | |
| return video_tensor, graphs | |
| def preprocess_video_tta(video_path: str, edge_index: torch.Tensor) -> list: | |
| """ | |
| Preprocessing con TTA x5 igual que en evaluaciΓ³n del dataset. | |
| Variantes: | |
| 1. Original | |
| 2. Flip horizontal (X de landmarks invertido) | |
| 3. RotaciΓ³n +10Β° | |
| 4. RotaciΓ³n -10Β° | |
| 5. InversiΓ³n temporal | |
| Returns | |
| ------- | |
| Lista de 5 tuplas (video_tensor, graphs) para promediar logits. | |
| """ | |
| import torchvision.transforms.functional as TF | |
| base_tensor, base_graphs = preprocess_video(video_path, edge_index) | |
| variants = [(base_tensor, base_graphs)] | |
| # ββ RotaciΓ³n +10Β° βββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| rot_p = torch.stack([ | |
| TF.rotate(base_tensor[0, t], 10) | |
| for t in range(T_FRAMES) | |
| ]).unsqueeze(0) | |
| variants.append((rot_p, base_graphs)) | |
| # ββ RotaciΓ³n -10Β° βββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| rot_n = torch.stack([ | |
| TF.rotate(base_tensor[0, t], -10) | |
| for t in range(T_FRAMES) | |
| ]).unsqueeze(0) | |
| variants.append((rot_n, base_graphs)) | |
| # ββ InversiΓ³n temporal ββββββββββββββββββββββββββββββββββββββββββββββββ | |
| rev_tensor = torch.flip(base_tensor, dims=[1]) | |
| rev_graphs = list(reversed(base_graphs)) | |
| variants.append((rev_tensor, rev_graphs)) | |
| return variants |