0% found this document useful (0 votes)
8 views4 pages

Fps +% +track+rec

This document outlines a face recognition system using OpenCV and the DeepFace library. It initializes a webcam, loads a face database, and processes video frames to detect and recognize faces in real-time, displaying results on the screen. The system employs threading for efficient processing and uses cosine similarity to match detected faces against the database with configurable parameters for detection confidence and similarity thresholds.

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)
8 views4 pages

Fps +% +track+rec

This document outlines a face recognition system using OpenCV and the DeepFace library. It initializes a webcam, loads a face database, and processes video frames to detect and recognize faces in real-time, displaying results on the screen. The system employs threading for efficient processing and uses cosine similarity to match detected faces against the database with configurable parameters for detection confidence and similarity thresholds.

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/ 4

import cv2

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)

# Load face database with validation


face_database = []
print("⚙️ Loading face database...")

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 image
obj = DeepFace.represent(
img_path=path,
model_name=MODEL_NAME,
detector_backend=DETECTOR_BACKEND,
enforce_detection=True,
align=True
)

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

# Find best match using cosine similarity


for entry in face_database:
similarity = np.dot(current_embedding,
entry["embedding"]) / (
np.linalg.norm(current_embedding) *
np.linalg.norm(entry["embedding"])
)
similarity = (similarity + 1) / 2 # Convert to 0-1
scale

if similarity > max_similarity:


max_similarity = similarity
label = entry["name"] if similarity >
SIMILARITY_THRESHOLD else "Unknown"

except Exception as e:
pass

current_results.append(((x, y, w, h), label, max_similarity))

with lock:
results = current_results
except Exception as e:
print(f"⚠️ Processing error: {str(e)}")

# Start processing thread


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

# Performance counters
fps_counter = 0
fps = 0
start_time = cv2.getTickCount()

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

# Update shared frame


with lock:
latest_frame = frame.copy()

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

# Main face rectangle


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

# Label with similarity


text = f"{label} ({similarity:.2f})" if label != "Unknown" else label
cv2.putText(frame, text, (x, y-10),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, color, 2)

# Zoom preview (top-right corner)


try:
zoom = cv2.resize(frame[y:y+h, x:x+w], (100, 100))
frame[10:110, 530:630] = zoom
cv2.rectangle(frame, (530, 10), (630, 110), (255, 255, 255), 1)
except:
pass

# Calculate FPS
fps_counter += 1
if (cv2.getTickCount() - start_time) / cv2.getTickFrequency() > 1:
fps = fps_counter
fps_counter = 0
start_time = cv2.getTickCount()

cv2.putText(frame, f"FPS: {fps}", (10, 30),


cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)

cv2.imshow('Face Recognition System', frame)

if cv2.waitKey(1) & 0xFF == ord('q'):


break
cap.release()
cv2.destroyAllWindows()

You might also like