Open In App

Build Your Own Face Recognition Tool With Python

Last Updated : 14 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

From unlocking smartphone to tagging friends on social media face recognition is everywhere. But have you ever wondered how it works? Well, you don’t need to be a computer science expert to create your own face recognition tool. With Python and some basic libraries, you can build one from scratch.

This guide walks through building a face recognition tool, covering the essential steps with practical examples.

Setting Up the Environment

Before diving into the code, let’s set up the environment.

  • Prerequisites: Make sure you have Python (3.x version) installed on your machine. You can download it from python.org.
  • Libraries Required:
    • OpenCV: For image and video processing.
    • NumPy: For numerical operations.
pip install opencv-python
pip install numpy

Haar Cascade File: Download the haarcascade_frontalface_default.xml file, which is a pre-trained model for face detection. You can get it from Haar Cascade File. It is specifically designed to detect objects like faces by applying machine learning algorithms trained on positive and negative images. The Haar Cascade is used to detect faces in images or video frames. Let's build a face recognition tool step-by-step process:

Step 1 : Importing the necessary libraries

Python
import cv2
import numpy as np

Step 2: Setting Up the Video Capture

Use OpenCV’s VideoCapture function to access webcam:

Python
video = cv2.VideoCapture(0)

The parameter 0 represents the default camera. If you have multiple cameras, change it to 1 or 2 accordingly to the settings of the camera.

Step 3: Loading the Haar Cascade

Python
facedetect = cv2.CascadeClassifier('data/haarcascade_frontalface_default.xml')

here, this haarcascade_frontalface_default.xml file is stored inside the data folder

Step 4: Initializing Variables

Python
faces_data = []
i = 0

With initializing the variables , we will create a list to store face data and a counter to manage frame processing

Step 5: Capturing and Processing Frames

The code is a simple face detection system using OpenCV, which includes grayscale conversion, face detection, data storage, and visual display of the results. It efficiently processes each frame, detecting faces, resizing and storing them, and displaying the results on the screen in real time.

This code takes a live video feed, looks for faces in each frame, and saves some of them. It captures each frame, turns it black and white to make face detection easier, and then finds faces using a face detection tool.

When a face is found, it cuts out that part of the frame, shrinks it to 50x50 pixels, and saves it in a list if the list has fewer than 100 images and the frame count is a multiple of 10. We do this to manage the data efficiently and avoid saving too many similar images, which can happen because the video feed captures frames continuously at a high rate.

The video feed is shown with red rectangle around faces and a number on the screen showing how many faces have been saved. You can stop the program by pressing 'q'

Python
while True:
    ret, frame = video.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = facedetect.detectMultiScale(gray, 1.3, 5)
    for (x, y, w, h) in faces:
        crop_img = frame[y:y+h, x:x+w, :]
        resized_img = cv2.resize(crop_img, (50, 50))
        if len(faces_data) <= 100 and i % 10 == 0:
            faces_data.append(resized_img)
        i += 1
        cv2.putText(frame, str(len(faces_data)), (50, 50), cv2.FONT_HERSHEY_COMPLEX, 1, (50, 50, 255), 1)
        cv2.rectangle(frame, (x, y), (x+w, y+h), (50, 50, 255), 1)
    cv2.imshow("Frame", frame)
    k = cv2.waitKey(1)
    if k == ord('q'):
        break

This code efficiently detects faces in a video stream, saves a limited number of resized face images, and visually highlights the detected faces in real time

Step 6: Releasing the Camera

Python
video.release()
cv2.destroyAllWindows()

When you’re done, release the camera and close the OpenCV window.

Complete code for the Face recognition Tool:

Python
import cv2
import numpy as np

video = cv2.VideoCapture(0)
facedetect = cv2.CascadeClassifier('data/haarcascade_frontalface_default.xml')

faces_data = []
i = 0

while True:
    ret, frame = video.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = facedetect.detectMultiScale(gray, 1.3, 5)
    for (x, y, w, h) in faces:
        crop_img = frame[y:y+h, x:x+w, :]
        resized_img = cv2.resize(crop_img, (50, 50))
        if len(faces_data) <= 100 and i % 10 == 0:
            faces_data.append(resized_img)
        i = i + 1
        cv2.putText(frame, str(len(faces_data)), (50, 50), cv2.FONT_HERSHEY_COMPLEX, 1, (50, 50, 255), 1)
        cv2.rectangle(frame, (x, y), (x+w, y+h), (50, 50, 255), 1)
    cv2.imshow("Frame", frame)
    k = cv2.waitKey(1)
    if k == ord('q'):
        break

video.release()
cv2.destroyAllWindows()

Output:

Screenshot-2025-01-09-172231
Face Recognition with OpenCV

Conclusion:

This code acts like a smart camera that processes a video to identify faces. When it detects faces, it draws rectangles around them to highlight their locations. Additionally, the faces are saved as smaller, cropped images, which can be used later for tasks like face recognition.

Covering each detected face with a red rectangle ensures the code can efficiently focus on the face areas for recognition and avoids processing unnecessary details from the background.



Next Article
Article Tags :
Practice Tags :

Similar Reads