File size: 1,784 Bytes
6aa6081
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import io
import base64
import numpy as np
import cv2
from typing import Optional


def decode_base64_image(data: str) -> Optional[np.ndarray]:
    try:
        if "," in data:
            data = data.split(",")[1]
        img_bytes = base64.b64decode(data)
        arr = np.frombuffer(img_bytes, np.uint8)
        img = cv2.imdecode(arr, cv2.IMREAD_COLOR)
        return img
    except Exception:
        return None


def detect_face(image: np.ndarray) -> Optional[np.ndarray]:
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    face_cascade = cv2.CascadeClassifier(
        cv2.data.haarcascades + "haarcascade_frontalface_default.xml"
    )
    faces = face_cascade.detectMultiScale(gray, 1.1, 5, minSize=(100, 100))
    if len(faces) == 0:
        return None
    (x, y, w, h) = faces[0]
    face = gray[y : y + h, x : x + w]
    face = cv2.resize(face, (160, 160))
    return face


def encode_face(face_image: np.ndarray) -> Optional[list]:
    try:
        import face_recognition

        rgb = cv2.cvtColor(face_image, cv2.COLOR_GRAY2RGB) if len(face_image.shape) == 2 else face_image
        encodings = face_recognition.face_encodings(rgb)
        if encodings:
            return encodings[0].tolist()
        return None
    except ImportError:
        return None


def compare_encodings(known: list[list[float]], target: list[float], tolerance: float = 0.5) -> tuple[Optional[int], float]:
    try:
        import face_recognition

        distances = face_recognition.face_distance(np.array(known), np.array(target))
        best_idx = int(np.argmin(distances))
        best_dist = float(distances[best_idx])
        if best_dist <= tolerance:
            return best_idx, best_dist
        return None, best_dist
    except ImportError:
        return None, 1.0