Fps +% +track+rec
Fps +% +track+rec
import os
import numpy as np
import threading
from deepface import DeepFace
# Configuration
DATABASE_FOLDER = "database"
MODEL_NAME = "ArcFace" # More accurate than Facenet
DETECTOR_BACKEND = "ssd" # Better than Haar cascades
SIMILARITY_THRESHOLD = 0.6 # More intuitive 0-1 range (higher = stricter)
MIN_FACE_CONFIDENCE = 0.9 # Filter weak detections
# Initialize webcam
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
if obj:
name = os.path.splitext(filename)[0]
face_database.append({
"name": name,
"embedding": obj[0]["embedding"]
})
print(f"✅ Loaded: {name}")
else:
print(f"⚠️ No face found in {filename}")
except Exception as e:
print(f"❌ Error loading {filename}: {str(e)}")
# Thread-safe variables
latest_frame = None
results = []
lock = threading.Lock()
def process_faces():
global latest_frame, results
while True:
frame = None
with lock:
if latest_frame is not None:
frame = latest_frame.copy()
if frame is None:
continue
try:
# Detect faces with modern detector
face_objs = DeepFace.extract_faces(
img_path=frame,
detector_backend=DETECTOR_BACKEND,
enforce_detection=False,
align=True
)
current_results = []
for face in face_objs:
if face["confidence"] < MIN_FACE_CONFIDENCE:
continue
region = face["facial_area"]
x, y, w, h = region["x"], region["y"], region["w"], region["h"]
label = "Unknown"
max_similarity = 0
if face_database:
try:
# Get face embedding
current_embedding = DeepFace.represent(
img_path=frame[y:y+h, x:x+w],
model_name=MODEL_NAME,
detector_backend="skip",
enforce_detection=False,
align=False
)[0]["embedding"]
except Exception as e:
pass
with lock:
results = current_results
except Exception as e:
print(f"⚠️ Processing error: {str(e)}")
# Performance counters
fps_counter = 0
fps = 0
start_time = cv2.getTickCount()
while True:
ret, frame = cap.read()
if not ret:
break
# Get results
with lock:
current_results = results.copy()
# Draw results
for (x, y, w, h), label, similarity in current_results:
color = (0, 255, 0) if label != "Unknown" else (0, 0, 255)
# Calculate FPS
fps_counter += 1
if (cv2.getTickCount() - start_time) / cv2.getTickFrequency() > 1:
fps = fps_counter
fps_counter = 0
start_time = cv2.getTickCount()