Bien
Bien
import os
import numpy as np
import threading
import time
from deepface import DeepFace
# Configuration
DATABASE_FOLDER = "database"
MODEL_NAME = "ArcFace"
DETECTOR_BACKEND = "retinaface" # More accurate detector
SIMILARITY_THRESHOLD = 0.65
MIN_FACE_CONFIDENCE = 0.95
ENROLLMENT_QUALITY_THRESHOLD = 0.85 # Minimum quality for new enrollments
# Initialize webcam
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
# System metrics
performance_stats = {
"fps": 0,
"detection_time": 0,
"recognition_time": 0,
"frame_counter": 0,
"start_time": time.time()
}
if result:
with database_lock:
face_database.append({
"name": os.path.splitext(filename)[0],
"embedding": result[0]["embedding"],
"path": path
})
print(f"✅ Loaded: {os.path.splitext(filename)[0]}")
else:
print(f"⚠️ No valid face found in {filename}")
except Exception as e:
print(f"❌ Error loading {filename}: {str(e)}")
initialize_database()
# Thread-safe variables
latest_frame = None
processing_results = []
system_lock = threading.Lock()
def face_processing_worker():
global latest_frame, processing_results
while True:
frame = None
with system_lock:
if latest_frame is not None:
frame = latest_frame.copy()
if frame is None:
time.sleep(0.01)
continue
try:
# Face detection pipeline
start_detect = time.time()
faces = DeepFace.extract_faces(
img_path=frame,
detector_backend=DETECTOR_BACKEND,
enforce_detection=False,
align=True
)
detect_time = time.time() - start_detect
results = []
for face in faces:
if face["confidence"] < MIN_FACE_CONFIDENCE:
continue
region = face["facial_area"]
x, y, w, h = region["x"], region["y"], region["w"], region["h"]
# Face recognition
start_recognize = time.time()
label = "Unknown"
confidence = 0.0
if face_database:
try:
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 system_lock:
processing_results = results
except Exception as e:
print(f"⚠️ Processing error: {str(e)}")
# Generate filename
filename = f"{name}_{int(time.time())}.jpg"
path = os.path.join(DATABASE_FOLDER, filename)
# Add to database
embedding = DeepFace.represent(
img_path=path,
model_name=MODEL_NAME,
detector_backend="skip",
enforce_detection=True
)[0]["embedding"]
with database_lock:
face_database.append({
"name": name,
"embedding": embedding,
"path": path
})
except Exception as e:
print(f"❌ Enrollment error: {str(e)}")
return False
# Main loop
while True:
ret, frame = cap.read()
if not ret:
break
# Draw results
for (x, y, w, h), label, confidence, detect_time, recognize_time in
current_results:
# Determine box color based on confidence
color = (0, 255, 0) if label != "Unknown" else (0, 0, 255)
thickness = 2
# Information overlay
text = f"{label} ({confidence*100:.1f}%)" if label != "Unknown" else
"Unknown"
cv2.putText(frame, text, (x, y-10),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2)
# Performance metrics
cv2.putText(frame, f"Detect: {detect_time*1000:.1f}ms", (x, y+h+20),
cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255,255,255), 1)
cv2.putText(frame, f"Recognize: {recognize_time*1000:.1f}ms", (x, y+h+40),
cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255,255,255), 1)
# System HUD
cv2.putText(frame, f"FPS: {performance_stats['fps']}", (10, 30),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)
cv2.putText(frame, f"Threshold: {SIMILARITY_THRESHOLD:.2f}", (10, 60),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)
cv2.putText(frame, "Press E to enroll, +- to adjust threshold", (10, 90),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1)
# Show frame
cv2.imshow('Advanced Face Recognition', frame)
cap.release()
cv2.destroyAllWindows()