Real-Time Face Recognition with DeepFace and OpenCV When Face Recognition plugin not supported

This project uses DeepFace to perform live face recognition from a webcam feed and compares the captured face against a local image database. It’s built with Python and OpenCV, and leverages DeepFace’s find() method to match faces in real time.

Why Not face_recognition?

The popular face_recognition library, built on dlib, is no longer compatible with newer Python versions like 3.12+. It fails during installation due to wheel build errors and outdated dependencies. This project solves that by switching to DeepFace, which supports modern Python environments and offers better flexibility with multiple recognition models.

Folder Setup

Create a folder named image_recognize inside your project directory. Add known face images named after the person you want to recognize. For example:

Code
image_recognize/
├── dhoni.jpg
├── dhinesh.jpg
├── ajay.jpg

The filename (without extension) is used as the person's name in the output.

Code Overview

python
import cv2
from deepface import DeepFace
import os

# Path to folder containing known faces (e.g., dhinesh.jpg, ajay.jpg)
db_path = "known_faces"
db_path = os.path.join(os.path.dirname(__file__), '', 'image_recognize')
print(db_path)
exit
# Initialize webcam
cap = cv2.VideoCapture(0)

print("🔍 Starting face recognition... Press 'q' to quit.")

while True:
    ret, frame = cap.read()
    if not ret:
        print("❌ Failed to capture frame.")
        break

    # Save current frame to a temporary file
    cv2.imwrite("current_frame.jpg", frame)

    try:
        # Compare captured frame with known faces
        results = DeepFace.find(img_path="current_frame.jpg", db_path=db_path, enforce_detection=False)

        if results and not results[0].empty:
            # Get best match
              best_match_path = results[0].iloc[0]["identity"]
              person_name = os.path.splitext(os.path.basename(best_match_path))[0]
              print(f"✅ Match found: {person_name}")
        else:
            print("❌ No match found. Person is unknown.")

    except Exception as e:
        print(f"⚠️ Error during recognition: {e}")

    # Display the frame
    cv2.imshow("Face Recognition", frame)

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

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

Output Verified ✅




The system successfully identified Mahendra Singh Dhoni from a live webcam feed. Below is a snapshot of the recognition process in action:

Output Image:

Insert your verified image here showing terminal output and Dhoni’s face on screen

Maintaining Attendance Using Server-Stored Images

This face recognition setup can be extended to maintain attendance logs by storing known face images on a server and matching incoming webcam frames against them.

How It Works:

  • Store employee/student images in a server directory (e.g., image_recognize/)

  • Each image should be named after the person (e.g., dhinesh.jpg)

  • When a match is found, log the name and timestamp into a database or CSV file

Sample Logging Code:

python
import csv
from datetime import datetime

def log_attendance(name):
    with open("attendance.csv", mode="a", newline="") as file:
        writer = csv.writer(file)
        writer.writerow([name, datetime.now().strftime("%Y-%m-%d %H:%M:%S")])

Call log_attendance(person_name) inside the match block to record attendance automatically.

Benefits:

  • No manual punch-in required

  • Works with any camera feed

  • Easily scalable for schools, offices, or events

Let me know if you want to integrate this with a dashboard, REST API, or Shopify backend—I can help you build the full attendance pipeline.

Comments