Python Central HubSign in

Python Projects / Advanced

Face Recognition System

A Python application for face recognition using computer vision, featuring image processing, model training, and a CLI interface.

Abstract

Face Recognition System is a Python project that uses computer vision for face recognition. The application features image processing, model training, and a CLI interface, demonstrating best practices in AI and security.

Prerequisites

  • Python 3.8 or above
  • A code editor or IDE
  • Basic understanding of computer vision and AI
  • Required libraries: opencv-python, face-recognition, numpy

Before you Start

Install Python and the required libraries:

Shell
pip install opencv-python face-recognition numpy

Getting Started

Create a Project

  1. Create a folder named face-recognition-system.
  2. Open the folder in your code editor or IDE.
  3. Create a file named facial_recognition_system.py.
  4. Copy the code below into your file.
diagram how the pieces call each other mermaid
Derived from projects/advance/facial_recognition_system.py by parsing it, not by hand. Arrows are calls between the file's own functions and methods; library calls are left out, and only calls the parser could resolve with certainty are shown.

Write the Code

Face Recognition SystemSource
Face Recognition System
"""
Facial Recognition System

This project implements a facial recognition system using OpenCV and face_recognition library. It supports face detection, encoding, registration, and real-time recognition from webcam. Includes CLI for registering new faces and running recognition.
"""
import cv2
import face_recognition
import os
import argparse
import pickle

def load_known_faces(db_path):
    """Load known faces and their encodings from the database."""
    if os.path.exists(db_path):
        with open(db_path, 'rb') as f:
            data = pickle.load(f)
        return data['encodings'], data['names']
    return [], []

def save_known_faces(encodings, names, db_path):
    """Save known faces and their encodings to the database."""
    with open(db_path, 'wb') as f:
        pickle.dump({'encodings': encodings, 'names': names}, f)

def register_face(image_path, name, db_path):
    """Register a new face by adding its encoding to the database."""
    img = face_recognition.load_image_file(image_path)
    encodings = face_recognition.face_encodings(img)
    if encodings:
        known_encodings, known_names = load_known_faces(db_path)
        known_encodings.append(encodings[0])
        known_names.append(name)
        save_known_faces(known_encodings, known_names, db_path)
        print(f"Registered face for {name}")
    else:
        print("No face found in image.")

def recognize_faces(db_path):
    """Run real-time face recognition on webcam feed."""
    known_encodings, known_names = load_known_faces(db_path)
    video = cv2.VideoCapture(0)
    print("Press 'q' to quit.")
    while True:
        ret, frame = video.read()
        rgb = frame[:, :, ::-1]
        faces = face_recognition.face_locations(rgb)
        encodings = face_recognition.face_encodings(rgb, faces)
        for (top, right, bottom, left), encoding in zip(faces, encodings):
            matches = face_recognition.compare_faces(known_encodings, encoding)
            name = "Unknown"
            if True in matches:
                name = known_names[matches.index(True)]
            cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)
            cv2.putText(frame, name, (left, top-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255,255,255), 2)
        show_or_save('Facial Recognition', frame)
        if wait_or_skip(1) & 0xFF == ord('q'):
            break
    video.release()
    cv2.destroyAllWindows() if "--show" in __import__("sys").argv else None

def main():
    parser = argparse.ArgumentParser(description="Facial Recognition System")
    parser.add_argument('--register', nargs=2, metavar=('IMAGE', 'NAME'), help='Register a new face')
    parser.add_argument('--db', type=str, default='faces.db', help='Path to face database')
    parser.add_argument('--recognize', action='store_true', help='Run real-time recognition')
    args = parser.parse_args()

    if args.register:
        image_path, name = args.register
        register_face(image_path, name, args.db)
    elif args.recognize:
        recognize_faces(args.db)
    else:
        parser.print_help()

def wait_or_skip(delay=0):
    """cv2.waitKey needs a window; without one it raises. Skip it instead."""
    import sys

    if "--show" in sys.argv:
        return cv2.waitKey(delay)
    return -1


def show_or_save(title, image, _counter=[0]):
    """Display the frame, or write it to a file when no window is available.

    Headless OpenCV has no GUI at all, and even a full build cannot open a
    window over SSH or inside a container. Falling back to a file keeps the
    project runnable everywhere and leaves something to look at afterwards.
    """
    import os
    import re as _re

    if "--show" in __import__("sys").argv:
        cv2.imshow(title, image)
        return None
    _counter[0] += 1
    stem = _re.sub(r"\W+", "_", title).strip("_").lower() or "frame"
    name = f"{stem}.png" if _counter[0] == 1 else f"{stem}_{_counter[0]}.png"
    cv2.imwrite(name, image)
    print(f"saved {name}  ({os.path.getsize(name):,} bytes)")
    return name


if __name__ == "__main__":
    main()

Example Usage

Shell
python facial_recognition_system.py

Explanation

Key Features

  • Image Processing: Processes images for face detection.
  • Model Training: Trains a model to recognize faces.
  • Error Handling: Validates inputs and manages exceptions.
  • CLI Interface: Interactive command-line usage.

Code Breakdown

  1. What it imports (lines 6–10)
Python
import cv2
import face_recognition
import os
import argparse
import pickle
  1. load_known_faces — the function (lines 12–18)
Python
def load_known_faces(db_path):
    """Load known faces and their encodings from the database."""
    if os.path.exists(db_path):
        with open(db_path, 'rb') as f:
            data = pickle.load(f)
        return data['encodings'], data['names']
    return [], []
  1. register_face — the function (lines 25–36)
Python
def register_face(image_path, name, db_path):
    """Register a new face by adding its encoding to the database."""
    img = face_recognition.load_image_file(image_path)
    encodings = face_recognition.face_encodings(img)
    if encodings:
        known_encodings, known_names = load_known_faces(db_path)
        known_encodings.append(encodings[0])
        known_names.append(name)
        save_known_faces(known_encodings, known_names, db_path)
        print(f"Registered face for {name}")
    else:
        print("No face found in image.")
  1. recognize_faces — the function (lines 38–59)
Python
def recognize_faces(db_path):
    """Run real-time face recognition on webcam feed."""
    known_encodings, known_names = load_known_faces(db_path)
    video = cv2.VideoCapture(0)
    print("Press 'q' to quit.")
    while True:
        ret, frame = video.read()
        rgb = frame[:, :, ::-1]
        faces = face_recognition.face_locations(rgb)
        encodings = face_recognition.face_encodings(rgb, faces)
        for (top, right, bottom, left), encoding in zip(faces, encodings):
            matches = face_recognition.compare_faces(known_encodings, encoding)
            name = "Unknown"
            if True in matches:
                name = known_names[matches.index(True)]
            cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)
            cv2.putText(frame, name, (left, top-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255,255,255), 2)
        cv2.imshow('Facial Recognition', frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    video.release()
    cv2.destroyAllWindows()
  1. main — the function (lines 61–74)
Python
def main():
    parser = argparse.ArgumentParser(description="Facial Recognition System")
    parser.add_argument('--register', nargs=2, metavar=('IMAGE', 'NAME'), help='Register a new face')
    parser.add_argument('--db', type=str, default='faces.db', help='Path to face database')
    parser.add_argument('--recognize', action='store_true', help='Run real-time recognition')
    args = parser.parse_args()
 
    if args.register:
        image_path, name = args.register
        register_face(image_path, name, args.db)
    elif args.recognize:
        recognize_faces(args.db)
    else:
        parser.print_help()

The file defines 5 top-level symbols in all; the whole thing is above under Write the Code.

Features

  • Face Recognition: Image processing and model training
  • Modular Design: Separate functions for each task
  • Error Handling: Manages invalid inputs and exceptions
  • Production-Ready: Scalable and maintainable code

Next Steps

Enhance the project by:

  • Integrating with real image datasets
  • Supporting advanced recognition algorithms
  • Creating a GUI for recognition
  • Adding real-time detection
  • Unit testing for reliability

Educational Value

This project teaches:

  • AI and Security: Face recognition and computer vision
  • Software Design: Modular, maintainable code
  • Error Handling: Writing robust Python code

Real-World Applications

  • Security Systems
  • Attendance Platforms
  • AI Tools

Checkpoint exercise

This exercise practises matching a face embedding to enrolled people by Euclidean distance with a rejection threshold.

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Conclusion

Face Recognition System demonstrates how to build a scalable and accurate face recognition tool using Python. With modular design and extensibility, this project can be adapted for real-world applications in security, AI, and more. For more advanced projects, visit Python Central Hub.

Was this page helpful?

Let us know how we did