File size: 12,988 Bytes
a543540 441b0b6 a543540 441b0b6 a543540 441b0b6 a543540 441b0b6 a543540 441b0b6 a543540 cabfd1d | 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 | """
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 |