File size: 1,391 Bytes
6f2dcbc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# backend/core/face_recognition.py
import face_recognition
import numpy as np
import pickle
import os

class FaceRecognizer:
    def __init__(self, encodings_path='models/face_encodings.pkl'):
        self.known_face_encodings = []
        self.known_face_names = []
        self.load_encodings(encodings_path)
        
    def load_encodings(self, path):
        """Load pre-computed face encodings"""
        if os.path.exists(path):
            with open(path, 'rb') as f:
                data = pickle.load(f)
                self.known_face_encodings = data['encodings']
                self.known_face_names = data['names']
                
    def recognize_face(self, face_img):
        """Recognize a single face"""
        if face_img is None or face_img.size == 0:
            return None
            
        # Get face encoding
        face_locations = face_recognition.face_locations(face_img)
        if not face_locations:
            return None
            
        face_encoding = face_recognition.face_encodings(face_img, face_locations)[0]
        
        # Compare with known faces
        matches = face_recognition.compare_faces(
            self.known_face_encodings, 
            face_encoding
        )
        
        if True in matches:
            matched_index = matches.index(True)
            return self.known_face_names[matched_index]
        return None