Effortless Real-Time Face Recognition in Python and OpenCV

Mriganka BarmanMriganka Barman
4 min read

Introduction to Face recognition technology

Face recognition technology has gained significant attention in recent years due to its widespread applications in security, authentication, and even everyday devices. Whether you're securing a building or creating an AI-powered app, understanding how to implement face recognition is crucial. This tutorial will walk you through a Python and OpenCV based face recognition system using a simple yet effective script.

Let's break down the code and learn how you can create your own real-time face recognition system.


The Concept Behind Face Recognition

The script you're about to explore leverages the powerful face_recognition library in Python, which is built on top of dlib, a popular machine learning toolkit. This library simplifies face detection and recognition, allowing you to focus on building cool applications rather than getting bogged down in the details of the underlying algorithms.

The code is designed to perform the following tasks:

  1. Load a Known Face Encoding: This involves taking an image of a person, identifying the face within the image, and generating a unique encoding for that face. This encoding will be used to compare against faces detected in real-time video streams.

  2. Capture Video Stream: The code captures frames from a live video feed, typically from a webcam.

  3. Detect and Recognize Faces: For each frame, the script detects any faces, extracts their encodings, and compares them with the known encoding. If a match is found, it labels the face accordingly; otherwise, it labels it as "Unknown".


Breaking Down the Code

1. Importing the Necessary Libraries

import face_recognition
import cv2

The script begins by importing two essential libraries:

  • face_recognition: Handles the face detection and recognition process.

  • cv2 (OpenCV): Manages video capture and frame manipulation.

2. Loading Known Face Encodings

def load_known_face(image_path):
    image = face_recognition.load_image_file(image_path)
    face_encodings = face_recognition.face_encodings(image)
    if len(face_encodings) > 0:
        return face_encodings[0]
    return None

This function loads an image file, detects any faces in the image, and returns the first face encoding found. This encoding is a unique identifier that the script will later use to recognize faces in the video stream.

3. Real-Time Face Recognition

def recognize_face(video_capture, known_face_encoding, known_name):
    while True:
        ret, frame = video_capture.read()
        if not ret:
            break

        face_locations = face_recognition.face_locations(frame)
        for face_location in face_locations:
            top, right, bottom, left = face_location
            face_encodings = face_recognition.face_encodings(frame, [face_location])
            if len(face_encodings) > 0:
                face_encoding = face_encodings[0]
                match = face_recognition.compare_faces([known_face_encoding], face_encoding, tolerance=0.6)[0]
                name = known_name if match else "Unknown"

                # Draw a rectangle around the face
                cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
                # Display the name
                cv2.putText(frame, name, (left, top - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 255), 2)

        # Display the result
        cv2.imshow('Video', frame)

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

This function is the heart of the script. It continuously captures frames from the video stream, detects faces in each frame, and compares them to the known face encoding. If a match is found, it draws a rectangle around the face and labels it with the known name. The process stops when the user presses 'q'.

4. Integrating Everything Together

if __name__ == "__main__":
    video_capture = cv2.VideoCapture(0)
    known_face_encoding = load_known_face("path_to_image.jpg")
    recognize_face(video_capture, known_face_encoding, "Person's Name")
    video_capture.release()
    cv2.destroyAllWindows()

The script ties everything together in the main function. It starts the video capture, loads a known face from an image, and begins the real-time face recognition process. Once done, it releases the video capture and closes any OpenCV windows.


Conclusion

This script provides a straightforward approach to implementing real-time face recognition in Python. With just a few lines of code, you can create a system capable of recognizing familiar faces and identifying unknown ones. The project can be easily extended for various applications, such as security systems, smart doorbells, or personalized user experiences.

Try out this code, tweak it to your needs, and explore the vast potential of face recognition technology. Whether you're a seasoned developer or just starting, this project is a perfect stepping stone into the world of AI and computer vision.

code : github repo

Happy coding!

0
Subscribe to my newsletter

Read articles from Mriganka Barman directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Mriganka Barman
Mriganka Barman

I am an ML developer B.tech student(NIT Silchar / India)