|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +from __future__ import annotations |
| 3 | + |
| 4 | +import os |
| 5 | +import pickle |
| 6 | +import sys |
| 7 | +import urllib.request |
| 8 | +from pathlib import Path |
| 9 | + |
| 10 | +import cv2 |
| 11 | +import numpy as np |
| 12 | + |
| 13 | +IMAGE_EXTENSIONS: frozenset[str] = frozenset( |
| 14 | + (".jpg", ".jpeg", ".png", ".bmp", ".webp") |
| 15 | +) |
| 16 | +MODELS_BASE = "https://github.com/opencv/opencv_zoo/raw/main/models" |
| 17 | +YUNET_NAME = "face_detection_yunet/face_detection_yunet_2023mar.onnx" |
| 18 | +SFACE_NAME = "face_recognition_sface/face_recognition_sface_2021dec.onnx" |
| 19 | +CACHE_NAME = ".face_embeddings_cache.pkl" |
| 20 | +ENV_MODELS = "FACE_MATCH_MODELS" |
| 21 | + |
| 22 | + |
| 23 | +def get_models_dir() -> Path: |
| 24 | + override = os.environ.get(ENV_MODELS) |
| 25 | + if override: |
| 26 | + p = Path(override).expanduser().resolve() |
| 27 | + else: |
| 28 | + p = Path.home() / ".cache" / "face_match" / "models" |
| 29 | + p.mkdir(parents=True, exist_ok=True) |
| 30 | + return p |
| 31 | + |
| 32 | + |
| 33 | +def ensure_model(filename: str) -> Path: |
| 34 | + name = filename.split("/")[-1] |
| 35 | + path = get_models_dir() / name |
| 36 | + if path.is_file() and path.stat().st_size > 1000: |
| 37 | + return path |
| 38 | + url = f"{MODELS_BASE}/{filename}" |
| 39 | + print(f"Descargando modelo: {name} (puede tardar)...", file=sys.stderr) |
| 40 | + part = path.with_suffix(path.suffix + ".part") |
| 41 | + urllib.request.urlretrieve(url, str(part)) |
| 42 | + part.replace(path) |
| 43 | + return path |
| 44 | + |
| 45 | + |
| 46 | +def load_bgr(path: Path) -> np.ndarray | None: |
| 47 | + return cv2.imdecode(np.fromfile(str(path), dtype=np.uint8), cv2.IMREAD_COLOR) |
| 48 | + |
| 49 | + |
| 50 | +def list_image_paths(root: Path) -> list[Path]: |
| 51 | + out: list[Path] = [] |
| 52 | + for p in root.rglob("*"): |
| 53 | + if p.is_file() and p.suffix.lower() in IMAGE_EXTENSIONS: |
| 54 | + out.append(p) |
| 55 | + return sorted(out) |
| 56 | + |
| 57 | + |
| 58 | +def pick_best_face(faces: np.ndarray | None) -> np.ndarray | None: |
| 59 | + if faces is None or faces.size == 0: |
| 60 | + return None |
| 61 | + f = np.atleast_2d(faces) |
| 62 | + if f.shape[1] < 15: |
| 63 | + return f[0] |
| 64 | + scores = f[:, 14] |
| 65 | + return f[int(np.argmax(scores))] |
| 66 | + |
| 67 | + |
| 68 | +def embed( |
| 69 | + bgr: np.ndarray, |
| 70 | + detector: cv2.FaceDetectorYN, |
| 71 | + recognizer: cv2.FaceRecognizerSF, |
| 72 | +) -> np.ndarray | None: |
| 73 | + h, w = bgr.shape[:2] |
| 74 | + detector.setInputSize((w, h)) |
| 75 | + _, faces = detector.detect(bgr) |
| 76 | + row = pick_best_face(faces) |
| 77 | + if row is None: |
| 78 | + return None |
| 79 | + aligned = recognizer.alignCrop(bgr, row) |
| 80 | + return recognizer.feature(aligned) |
| 81 | + |
| 82 | + |
| 83 | +def load_cache(cache_path: Path) -> dict: |
| 84 | + if not cache_path.is_file(): |
| 85 | + return {} |
| 86 | + try: |
| 87 | + with open(cache_path, "rb") as f: |
| 88 | + return pickle.load(f) |
| 89 | + except Exception: |
| 90 | + return {} |
| 91 | + |
| 92 | + |
| 93 | +def save_cache(cache_path: Path, data: dict) -> None: |
| 94 | + tmp = cache_path.with_suffix(".tmp") |
| 95 | + with open(tmp, "wb") as f: |
| 96 | + pickle.dump(data, f, protocol=4) |
| 97 | + tmp.replace(cache_path) |
0 commit comments