Face Recognition System
Abstract
Section titled “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
Section titled “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
Section titled “Before you Start”Install Python and the required libraries:
pip install opencv-python face-recognition numpyGetting Started
Section titled “Getting Started”Create a Project
Section titled “Create a Project”- Create a folder named
face-recognition-system. - Open the folder in your code editor or IDE.
- Create a file named
facial_recognition_system.py. - Copy the code below into your file.
flowchart TD n0(["script start"]) n20["load_known_faces()"] n2["main()"] n21["recognize_faces()"] n22["register_face()"] n23["save_known_faces()"] n0 --> n2 n2 --> n21 n2 --> n22 n21 --> n20 n22 --> n20 n22 --> n23
Write the Code
Section titled “Write the Code”Face Recognition System
pch.viewSource"""
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
Section titled “Example Usage”python facial_recognition_system.pyExplanation
Section titled “Explanation”Key Features
Section titled “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
Section titled “Code Breakdown”- What it imports (lines 6–10)
import cv2
import face_recognition
import os
import argparse
import pickleload_known_faces— the function (lines 12–18)
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 [], []register_face— the function (lines 25–36)
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.")recognize_faces— the function (lines 38–59)
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()main— the function (lines 61–74)
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
Section titled “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
Section titled “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
Section titled “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
Section titled “Real-World Applications”- Security Systems
- Attendance Platforms
- AI Tools
Conclusion
Section titled “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.
pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading