Spaces:
Sleeping
Sleeping
Update face_utils.py
Browse files- face_utils.py +71 -14
face_utils.py
CHANGED
|
@@ -1,19 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from deepface import DeepFace
|
| 2 |
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
)
|
| 13 |
|
| 14 |
-
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from typing import List, Dict, Union
|
| 4 |
+
|
| 5 |
+
import cv2
|
| 6 |
+
import numpy as np
|
| 7 |
from deepface import DeepFace
|
| 8 |
|
| 9 |
+
# Avoid RetinaFace/tf-keras mismatch: use OpenCV face detector backend
|
| 10 |
+
DETECTOR = os.getenv("FACE_DETECTOR", "opencv")
|
| 11 |
+
MODEL_NAME = os.getenv("FACE_MODEL", "VGG-Face") # or "Facenet512", "ArcFace", ...
|
| 12 |
+
DIST_THRESHOLD = float(os.getenv("FACE_DIST_THRESHOLD", "0.35")) # lower => stricter
|
| 13 |
+
|
| 14 |
+
def _list_images(folder: Path) -> list[Path]:
|
| 15 |
+
exts = {".jpg", ".jpeg", ".png", ".bmp"}
|
| 16 |
+
return [p for p in folder.glob("*") if p.suffix.lower() in exts]
|
| 17 |
+
|
| 18 |
+
def _ensure_faces_dir(dir_path: str) -> Path:
|
| 19 |
+
p = Path(dir_path)
|
| 20 |
+
if not p.exists() or not any(p.iterdir()):
|
| 21 |
+
# Return as-is; caller will print friendly message
|
| 22 |
+
return p
|
| 23 |
+
return p
|
| 24 |
+
|
| 25 |
+
def _embed(img_bgr: np.ndarray):
|
| 26 |
+
# DeepFace.represent expects RGB
|
| 27 |
+
rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
|
| 28 |
+
reps = DeepFace.represent(
|
| 29 |
+
rgb, model_name=MODEL_NAME, detector_backend=DETECTOR, enforce_detection=False
|
| 30 |
+
)
|
| 31 |
+
# represent returns list of dicts. If none detected, empty list.
|
| 32 |
+
if not reps:
|
| 33 |
+
return None
|
| 34 |
+
# take first face (for counting/verification, that’s fine)
|
| 35 |
+
return np.array(reps[0]["embedding"], dtype=np.float32)
|
| 36 |
+
|
| 37 |
+
def _cosine(a, b):
|
| 38 |
+
a = a / (np.linalg.norm(a) + 1e-9)
|
| 39 |
+
b = b / (np.linalg.norm(b) + 1e-9)
|
| 40 |
+
return float(np.dot(a, b))
|
| 41 |
+
|
| 42 |
+
def recognize_faces(frame_bgr: np.ndarray, faces_dir: str, topk: int = 3) -> Union[str, List[Dict]]:
|
| 43 |
+
"""
|
| 44 |
+
Returns:
|
| 45 |
+
- str message if faces dir missing/empty or no faces detected.
|
| 46 |
+
- List[{"name": str, "score": float}] otherwise (score = 1 - cosine distance).
|
| 47 |
+
"""
|
| 48 |
+
gallery_root = _ensure_faces_dir(faces_dir)
|
| 49 |
+
if not gallery_root.exists():
|
| 50 |
+
return f"Warning: faces folder '{faces_dir}' not found."
|
| 51 |
+
gallery_imgs = _list_images(gallery_root)
|
| 52 |
+
if not gallery_imgs:
|
| 53 |
+
return f"Warning: faces folder '{faces_dir}' is empty."
|
| 54 |
|
| 55 |
+
# embed incoming frame (first face)
|
| 56 |
+
probe = _embed(frame_bgr)
|
| 57 |
+
if probe is None:
|
| 58 |
+
return "No face in frame"
|
|
|
|
| 59 |
|
| 60 |
+
# compare to gallery
|
| 61 |
+
scores = []
|
| 62 |
+
for p in gallery_imgs:
|
| 63 |
+
img = cv2.imread(str(p))
|
| 64 |
+
if img is None:
|
| 65 |
+
continue
|
| 66 |
+
emb = _embed(img)
|
| 67 |
+
if emb is None:
|
| 68 |
+
continue
|
| 69 |
+
cos = _cosine(probe, emb)
|
| 70 |
+
# convert to distance-like: higher is better (similarity)
|
| 71 |
+
scores.append({"name": p.stem, "score": cos})
|
| 72 |
|
| 73 |
+
scores.sort(key=lambda x: x["score"], reverse=True)
|
| 74 |
+
# Filter with threshold if provided (using cosine similarity ~ 1.0 is perfect)
|
| 75 |
+
filtered = [s for s in scores if (1.0 - s["score"]) <= DIST_THRESHOLD]
|
| 76 |
+
return filtered[:topk]
|