0% found this document useful (0 votes)
10 views5 pages

Bien

This document outlines a Python program for real-time face recognition using OpenCV and DeepFace. It initializes a face database, processes video frames for face detection and recognition, and allows for new face enrollment with quality checks. The program also includes performance metrics and user controls for adjusting recognition thresholds and enrolling new faces.

Uploaded by

mseif1573
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views5 pages

Bien

This document outlines a Python program for real-time face recognition using OpenCV and DeepFace. It initializes a face database, processes video frames for face detection and recognition, and allows for new face enrollment with quality checks. The program also includes performance metrics and user controls for adjusting recognition thresholds and enrolling new faces.

Uploaded by

mseif1573
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 5

import cv2

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)

# Face database with metadata


face_database = []
database_lock = threading.Lock()

# System metrics
performance_stats = {
"fps": 0,
"detection_time": 0,
"recognition_time": 0,
"frame_counter": 0,
"start_time": time.time()
}

# Load or initialize face database


def initialize_database():
print("🔍 Initializing face database...")
if not os.path.exists(DATABASE_FOLDER):
os.makedirs(DATABASE_FOLDER)
print("📁 Created database directory")

for filename in os.listdir(DATABASE_FOLDER):


if filename.lower().endswith((".jpg", ".jpeg", ".png")):
path = os.path.join(DATABASE_FOLDER, filename)
try:
# Validate and process face
result = DeepFace.represent(
img_path=path,
model_name=MODEL_NAME,
detector_backend=DETECTOR_BACKEND,
enforce_detection=True,
align=True
)

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)}")

print(f"📊 Database initialized with {len(face_database)} entries")

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"]

# Find best match


best_match = max(
((
np.dot(embedding, entry["embedding"]) /
(np.linalg.norm(embedding) *
np.linalg.norm(entry["embedding"])),
entry["name"]
) for entry in face_database),
default=(0, None)
)

confidence = (best_match[0] + 1) / 2 # Convert to 0-1


scale
if confidence > SIMILARITY_THRESHOLD:
label = best_match[1]

except Exception as e:
pass

recognize_time = time.time() - start_recognize


results.append(( (x, y, w, h), label, confidence, detect_time,
recognize_time ))

with system_lock:
processing_results = results

except Exception as e:
print(f"⚠️ Processing error: {str(e)}")

# Start processing threads


threading.Thread(target=face_processing_worker, daemon=True).start()

# Real-time enrollment system


def enroll_new_face(frame, name):
try:
# Quality check
face = DeepFace.extract_faces(
img_path=frame,
detector_backend=DETECTOR_BACKEND,
enforce_detection=True,
align=True
)[0]

if face["confidence"] < ENROLLMENT_QUALITY_THRESHOLD:


print("⚠️ Enrollment failed: Low quality face")
return False

# Generate filename
filename = f"{name}_{int(time.time())}.jpg"
path = os.path.join(DATABASE_FOLDER, filename)

# Save face image


cv2.imwrite(path, frame)

# 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
})

print(f"✅ Successfully enrolled: {name}")


return True

except Exception as e:
print(f"❌ Enrollment error: {str(e)}")
return False

# Main loop
while True:
ret, frame = cap.read()
if not ret:
break

# Update shared frame


with system_lock:
latest_frame = frame.copy()

# Get processing results


with system_lock:
current_results = processing_results.copy()

# Update performance stats


performance_stats["frame_counter"] += 1
if time.time() - performance_stats["start_time"] >= 1:
performance_stats["fps"] = performance_stats["frame_counter"]
performance_stats["frame_counter"] = 0
performance_stats["start_time"] = time.time()

# 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

# Main face rectangle


cv2.rectangle(frame, (x, y), (x+w, y+h), color, thickness)

# 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)

# Handle keyboard input


key = cv2.waitKey(1)
if key == ord('q'):
break
elif key == ord('e'):
name = input("Enter name for enrollment: ").strip()
if name:
threading.Thread(target=enroll_new_face, args=(frame.copy(),
name)).start()
elif key == ord('+'):
SIMILARITY_THRESHOLD = min(0.95, SIMILARITY_THRESHOLD + 0.05)
elif key == ord('-'):
SIMILARITY_THRESHOLD = max(0.3, SIMILARITY_THRESHOLD - 0.05)

cap.release()
cv2.destroyAllWindows()

You might also like