How To Build A Face Recognition App With Python?

Amit Dhanwani on February 8, 2024

Face recognition app Python tutorial

Learn to build your own face recognition app using Python with this step-by-step guide for beginners. Functional face recognition Python code inside!

Introduction

 

Face recognition is an emerging technology that has many exciting real-world applications. With the power of Python and its machine-learning libraries, you can build your facial recognition app! 

In this blog, we will walk through the key steps to create a basic face recognition app using Python.

Face recognition, or facial recognition, refers to the automated process of identifying human faces in digital images and videos. It works by analyzing the unique facial features of each face in an image and then comparing it against a database of known faces to find a match.

Over the past decade, facial recognition technology has advanced rapidly thanks to machine learning techniques like deep neural networks. Today, it has many uses, spanning security, biometric authentication, photo management, and more.

How Does a Face Recognition App Work?

 

At a high level, a facial recognition system relies on the following core steps:

  • Face Detection – Locate and isolate faces in an input image.
  • Feature Extraction – Analyze facial features and create a face print.
  • Face Matching – Compare face prints to a database of known faces to identify an individual.

By leveraging the power of computer vision and machine learning, face recognition AI provides a fascinating application of AI in the real world.

Why Build a Face Recognition App With Python?

 

There are many reasons Python programming is great for kids and teens. In building a face recognition app, some key advantages of using Python include:

  • User-friendly syntax and readability
  • Mature libraries for computer vision and machine learning,  like OpenCV and TensorFlow
  • Cross-platform support for training and deployment
  • Rapid prototyping capabilities for experimenting

Now, let’s walk through a basic project to create a face recognizer with Python!

Let’s Build a Face Recognition App!

 

For this project, we’ll build an app that can be trained to recognize specific people’s faces. Then we can test it with new images!

Here is a face recognition Python code for you: 

Step 1: Install OpenCV  

 The first step is to install OpenCV, the open-source computer vision library that provides pre-built algorithms and models for tasks like face detection.

OpenCV is a hugely popular library for computer vision and image processing. Some key features that make it useful for face recognition include:

  • Face detection – OpenCV comes with pre-trained Haar Cascade classifiers to detect frontal faces, eyes, smiles etc. This provides a quick way to find faces in images.
  • Image processing – Useful functions like conversions between colour spaces, resizing, transformations, filters etc. These preprocess images before feeding into machine learning models.
  • Machine learning – OpenCV has implementations of classic ML algorithms like SVM and KNN that can be used for basic face recognition.
  • Optimization – The algorithms are highly optimized to run fast, especially with GPU acceleration. This is important for real-time performance.

To install OpenCV for Python:

 pip install opencv-python

This will handle all the dependencies and compile the OpenCV library for your Python environment. With OpenCV installed, we can now load the pre-trained face detector classifier and start finding faces!

 

Step 2: Import OpenCV and Load Face Classifier

Once OpenCV is installed, we need to import it in our Python script:

import cv2

We also need a pre-trained classifier model that can detect faces in images. For this, OpenCV provides Haar Cascade Classifiers.

A Haar Cascade is a machine learning model that uses Haar-like features to detect objects like faces in an image. The “frontal face” classifier is trained specifically to identify forward facing faces.

Some key advantages of the Haar Cascade face detector:

  • It is fast and computationally efficient, making it suitable for real-time applications.
  • The pre-trained model is highly accurate in detecting frontal faces.
  • Being part of OpenCV, it’s easy to integrate in our pipeline.

We load the frontal face detector classifier like this:

face_classifier = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")

This XML file contains the preprocessed model data that detects faces. With the classifier loaded, we can now detect faces in images by calling its detectMultiScale method.

 

Step 3: Access Webcam

Now we need to access the webcam video stream as input. OpenCV provides a simple VideoCapture class to interface with cameras:

video_capture = cv2.VideoCapture(0)

Passing 0 accesses the default system camera. You can pass different values to select other cameras if multiple are available.

VideoCapture's .read() method returns a tuple with the next video frame and whether it was read correctly:

ret, frame = video_capture.read()

We’ll use this in a loop to read subsequent frames.

 

Step 4: Create a Face Detection Function

Let’s encapsulate the face detection Python code logic while drawing a bounding box around it:

 

def detect_bounding_box(vid):
    gray_image = cv2.cvtColor(vid, cv2.COLOR_BGR2GRAY)
    faces = face_classifier.detectMultiScale(gray_image, 1.1, 5, minSize=(40, 40))
    for (x, y, w, h) in faces:
        cv2.rectangle(vid, (x, y), (x + w, y + h), (0, 255, 0), 4)
    return faces

 

Step 5: Identifying Faces in the Video Stream

We need a function to process each video frame from the webcam feed. This is:

def detect_bounding_box(vid):
    gray_image = cv2.cvtColor(vid, cv2.COLOR_BGR2GRAY)
    faces = face_classifier.detectMultiScale(gray_image, 1.1, 5, minSize=(40, 40))
    for (x, y, w, h) in faces:
        cv2.rectangle(vid, (x, y), (x + w, y + h), (0, 255, 0), 4)
    return faces

 

Step 6: Process Webcam Frames

Loop over webcam frames and apply face detection:

while True:
    result, video_frame = video_capture.read()  # read frames from the video
    if result is False:
        break  # terminate the loop if the frame is not read successfully

    faces = detect_bounding_box(
        video_frame
    )  # use the function we created earlier to the video frame

    cv2.imshow(
        "My Face Detection Project", video_frame
    )  # display the processed frame in a window named "My Face Detection Project"

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

video_capture.release()
cv2.destroyAllWindows()

This will perform real-time face detection on your webcam video stream.

Code

 

import cv2
import os

# Load the pre-trained face detection model
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

# Load the pre-trained face recognition model
recognizer = cv2.face.LBPHFaceRecognizer_create()

# Load the training data
recognizer.read('training_data.yml')

# Initialize the video capture
video_capture = cv2.VideoCapture(0)

while True:

    # Read the current frame from the video capture
    ret, frame = video_capture.read()

    # Convert the frame to grayscale
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Detect faces in the grayscale frame
    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))

    # Iterate over each detected face
    for (x, y, w, h) in faces:

        # Draw a rectangle around the face
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)

        # Recognize the face
        label, confidence = recognizer.predict(gray[y:y+h, x:x+w])

        # Display the name of the recognized person
        if confidence < 100:
            name = "Person " + str(label)
        else:
            name = "Unknown"

        cv2.putText(frame, name, (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)

    # Display the resulting frame
    cv2.imshow('Face Recognizer', frame)

    # Break the loop if 'q' is pressed
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# Release the video capture and close all windows
video_capture.release()
cv2.destroyAllWindows()

Conclusion

Face recognition is an amazing technology that keeps advancing every year. While simple techniques like those we used here can be quite effective, modern face recognition apps rely on powerful deep neural networks to achieve incredible accuracy.

The world of coding and AI is full of possibilities. We hope this beginner-friendly face recognizer project sparked your interest to keep learning and creating new things with Python! Write your first Python code in a free Python class.

Next, create a random password generator program using Python. Happy Coding!

Sign up to our newsletter

Get the latest blogs, articles, and updates delivered straight to your inbox.

Share with your friends

Try a free class