0% found this document useful (0 votes)
9 views2 pages

Track +rec

This document outlines a Python script that utilizes OpenCV and DeepFace for real-time face recognition using a webcam. It captures video frames, detects faces, and compares them to a reference image, labeling recognized faces accordingly. The script includes error handling for loading images and processing frames, and it displays the video feed with detected faces and their labels.

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)
9 views2 pages

Track +rec

This document outlines a Python script that utilizes OpenCV and DeepFace for real-time face recognition using a webcam. It captures video frames, detects faces, and compares them to a reference image, labeling recognized faces accordingly. The script includes error handling for loading images and processing frames, and it displays the video feed with detected faces and their labels.

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

import cv2

from deepface import DeepFace

# Initialize webcam
cap = cv2.VideoCapture(0)
cap.set(3, 640) # Width
cap.set(4, 480) # Height

# Load reference image with validation


reference_path = "reference.jpg"
try:
ref_img = cv2.imread(reference_path)
if ref_img is None:
raise FileNotFoundError
except Exception as e:
print(f"Error loading reference image: {e}")
ref_img = None

while True:
# Read frame from webcam
ret, frame = cap.read()
if not ret:
print("Error reading frame from webcam")
break

try:
# Detect all faces in the frame
faces = DeepFace.extract_faces(frame, enforce_detection=False)

for face in faces:


# Get face coordinates
x = face['facial_area']['x']
y = face['facial_area']['y']
w = face['facial_area']['w']
h = face['facial_area']['h']

# Draw rectangle around face


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

# Face recognition
label = "Unknown"
if ref_img is not None:
try:
# Compare with reference face
result = DeepFace.verify(
frame[y:y+h, x:x+w],
ref_img,
enforce_detection=False
)
if result['verified']:
label = "Known Person"
except Exception as e:
pass

# Display label
cv2.putText(frame, label, (x, y-10),
cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)

# Show zoomed face (top-right corner)


zoomed_face = cv2.resize(frame[y:y+h, x:x+w], (100, 100))
frame[10:110, 530:630] = zoomed_face

except Exception as e:
print(f"Face processing error: {e}")

# Display frame
cv2.imshow('Face Recognition', frame)

# Exit on 'q' press


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

# Cleanup
cap.release()
cv2.destroyAllWindows()

You might also like