import cv2
import threading
import numpy as np
from deepface import DeepFace
# Initialize webcam
cap = [Link](0)
[Link](3, 640) # Width
[Link](4, 480) # Height
# Load and pre-process reference image
reference_name = "Reference Name" # Set this to the name you want displayed
reference_embedding = None
try:
ref_img = [Link]("[Link]")
if ref_img is not None:
# Pre-process once at startup
reference_embedding = [Link](ref_img, model_name='Facenet')[0]
["embedding"]
except Exception as e:
print(f"Reference error: {e}")
# Thread-safe variables
latest_frame = None
results = []
lock = [Link]()
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:
# Faster face detection with OpenCV
gray = [Link](frame, cv2.COLOR_BGR2GRAY)
faces = [Link](
[Link] + 'haarcascade_frontalface_default.xml'
).detectMultiScale(gray, 1.1, 4)
current_results = []
for (x, y, w, h) in faces:
label = "Unknown"
if reference_embedding is not None:
try:
# Face recognition
face_roi = frame[y:y+h, x:x+w]
face_embedding = [Link](face_roi,
model_name='Facenet')[0]["embedding"]
distance = [Link]([Link](face_embedding) -
[Link](reference_embedding))
if distance < 100: # Adjust this threshold as needed
label = reference_name
except:
pass
current_results.append(((x, y, w, h), label))
with lock:
results = current_results
except Exception as e:
print(f"Processing error: {e}")
# Start processing thread
[Link](target=process_faces, daemon=True).start()
while True:
ret, frame = [Link]()
if not ret:
break
# Update shared frame
with lock:
latest_frame = frame
# Display results
with lock:
current_results = [Link]()
# Draw on frame
for (x, y, w, h), label in current_results:
[Link](frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
[Link](frame, label, (x, y-10),
cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
# Zoom preview
zoom = [Link](frame[y:y+h, x:x+w], (100, 100))
frame[10:110, 530:630] = zoom
# Display frame
[Link]('Face Recognition', frame)
if [Link](1) & 0xFF == ord('q'):
break
[Link]()
[Link]()