CamKode

Building a Real-Time Face Recognition System Using Python, OpenCV, and face_recognition

Avatar of Kosal Ang

Kosal Ang

Thu Aug 22 2024

Building a Real-Time Face Recognition System Using Python, OpenCV, and face_recognition

In this article, we'll explore how to build a real-time face recognition system using Python, OpenCV, and the face_recognition library. This project leverages powerful machine learning algorithms to identify and label faces in a video feed. The complete code is provided below, along with a detailed explanation of how it works.

Install packages:

1pip install opencv-python face-recognition numpy
2

The Code Explained

Here's the complete code for the face recognition system:

1import face_recognition
2import cv2
3import numpy as np
4
5# Initialize the webcam
6video_capture = cv2.VideoCapture(0)
7
8# Load and encode known faces
9kosal_image = face_recognition.load_image_file("kosal.jpg")
10kosal_face_encoding = face_recognition.face_encodings(kosal_image)[0]
11
12lika_image = face_recognition.load_image_file("lika.jpg")
13lika_face_encoding = face_recognition.face_encodings(lika_image)[0]
14
15# Store the encodings and corresponding names in arrays
16known_face_encodings = [
17    kosal_face_encoding,
18    lika_face_encoding,
19]
20known_face_names = [
21    "Kosal",
22    "Molika",
23]
24
25# Initialize variables for face recognition
26face_locations = []
27face_encodings = []
28face_names = []
29process_this_frame = True
30
31while True:
32    # Capture a frame from the webcam
33    ret, frame = video_capture.read()
34
35    if not ret:
36        print("Failed to grab frame")
37        break
38
39    # Process every other frame for performance
40    if process_this_frame:
41        # Resize the frame to 1/4 for faster processing
42        small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
43
44        # Convert BGR image to RGB
45        rgb_small_frame = cv2.cvtColor(small_frame, cv2.COLOR_BGR2RGB)
46
47        # Detect faces and get encodings
48        face_locations = face_recognition.face_locations(rgb_small_frame)
49        face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)
50
51        face_names = []
52        for face_encoding in face_encodings:
53            # Check if the face matches any known faces
54            matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
55            name = "Unknown"
56
57            # Find the closest match
58            face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
59            best_match_index = np.argmin(face_distances)
60            if matches[best_match_index]:
61                name = known_face_names[best_match_index]
62
63            face_names.append(name)
64
65    process_this_frame = not process_this_frame
66
67    # Draw boxes around faces and label them
68    for (top, right, bottom, left), name in zip(face_locations, face_names):
69        # Scale the coordinates back to the original size
70        top *= 4
71        right *= 4
72        bottom *= 4
73        left *= 4
74
75        # Draw a box around the face
76        cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
77
78        # Label the face with a name
79        cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
80        font = cv2.FONT_HERSHEY_DUPLEX
81        cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)
82
83    # Display the video feed
84    cv2.imshow('Video', frame)
85
86    # Break the loop on 'q' key press
87    if cv2.waitKey(1) & 0xFF == ord('q'):
88        break
89
90# Release the webcam and close windows
91video_capture.release()
92cv2.destroyAllWindows()
93

How It Works

  1. Video Capture Initialization: The script starts by capturing video from the default webcam using cv2.VideoCapture(0).
  2. Face Encoding: Images of known individuals (kosal.png and lika.jpg) are loaded and encoded using the face_recognition library. These encodings are stored in arrays, which will be used to compare faces detected in the video feed.
  3. Processing Frames: The video is processed frame by frame. To enhance performance, only every other frame is processed. The frames are resized to a quarter of their original size to speed up the face detection and recognition process.
  4. Face Detection and Recognition: The script detects all faces in the frame using the face_recognition.face_locations() method. It then computes face encodings for the detected faces and compares them with the known encodings.
  5. Matching Faces: The detected face encodings are compared with the known face encodings to find the best match. The name corresponding to the best match is then assigned to the face.
  6. Displaying Results: The script draws rectangles around detected faces and labels them with the corresponding name. The processed frames are displayed in a window using OpenCV.
  7. Exit Condition: The loop runs until the 'q' key is pressed, after which the video capture is released, and all OpenCV windows are closed.

Building a real-time face recognition system using Python, OpenCV, and face_recognition is both straightforward and powerful. With minimal code, you can create applications that can recognize and label faces in real time. This system can be extended to recognize more faces by adding additional face encodings and names to the arrays.

This project is a great starting point for anyone interested in computer vision and machine learning. It demonstrates how easily these technologies can be integrated into practical applications.

References:

  • OpenCV: https://pypi.org/project/opencv-python/
  • NumPy: https://https://numpy.org/
  • Face Regnition: https://pypi.org/project/face-recognition/

Related Posts

How to Create and Use Virtual Environments

How to Create and Use Virtual Environments

Unlock the full potential of Python development with our comprehensive guide on creating and using virtual environments

Creating a Real-Time Chat Application with Flask and Socket.IO

Creating a Real-Time Chat Application with Flask and Socket.IO

Learn how to enhance your real-time chat application built with Flask and Socket.IO by displaying the Socket ID of the message sender alongside each message. With this feature, you can easily identify the owner of each message in the chat interface, improving user experience and facilitating debugging. Follow this step-by-step tutorial to integrate Socket ID display functionality into your chat application, empowering you with deeper insights into message origins.

How to Perform Asynchronous Programming with asyncio

How to Perform Asynchronous Programming with asyncio

Asynchronous programming with asyncio in Python allows you to write concurrent code that can handle multiple tasks concurrently, making it particularly useful for I/O-bound operations like web scraping

Mastering Data Visualization in Python with Matplotlib

Mastering Data Visualization in Python with Matplotlib

Unlock the full potential of Python for data visualization with Matplotlib. This comprehensive guide covers everything you need to know to create stunning visualizations, from basic plotting to advanced customization techniques.

Building a Secure Web Application with User Authentication Using Flask-Login

Building a Secure Web Application with User Authentication Using Flask-Login

Web authentication is a vital aspect of web development, ensuring that only authorized users can access protected resources. Flask, a lightweight web framework for Python, provides Flask-Login

Simplifying Excel File Handling in Python with Pandas

Simplifying Excel File Handling in Python with Pandas

Learn how to handle Excel files effortlessly in Python using the Pandas library. This comprehensive guide covers reading, writing, and manipulating Excel data with Pandas, empowering you to perform data analysis and reporting tasks efficiently.

Creating a Custom Login Form with CustomTkinter

Creating a Custom Login Form with CustomTkinter

In the realm of Python GUI development, Tkinter stands out as one of the most popular and versatile libraries. Its simplicity and ease of use make it an ideal choice for building graphical user interfaces for various applications.

Building Scalable Microservices Architecture with Python and Flask

Building Scalable Microservices Architecture with Python and Flask

Learn how to build a scalable microservices architecture using Python and Flask. This comprehensive guide covers setting up Flask for microservices, defining API endpoints, implementing communication between services, containerizing with Docker, deployment strategies, and more.

FastAPI: Building High-Performance RESTful APIs with Python

FastAPI: Building High-Performance RESTful APIs with Python

Learn how to leverage FastAPI, a modern web framework for building APIs with Python, to create high-performance and easy-to-maintain RESTful APIs. FastAPI combines speed, simplicity, and automatic documentation generation, making it an ideal choice for developers looking to rapidly develop and deploy APIs.

Beginner's Guide to Web Scraping with BeautifulSoup in Python

Beginner's Guide to Web Scraping with BeautifulSoup in Python

Learn how to scrape websites effortlessly using Python's BeautifulSoup library. This beginner-friendly guide walks you through fetching webpages, parsing HTML content, and extracting valuable data with ease.

© 2024 CamKode. All rights reserved

FacebookTwitterYouTube