Artificial Intelligence 7 min read

Python Face Recognition with OpenCV and face_recognition Library

This tutorial demonstrates how to set up a Python environment, install required libraries, and implement a real‑time face recognition system using OpenCV and the face_recognition package, including code for encoding known faces, classifying unknown faces, and displaying results.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Python Face Recognition with OpenCV and face_recognition Library

This article explains how to build a simple face‑recognition application in Python. It covers the necessary environment setup, required libraries, data preparation, and the core code that captures video, encodes known faces, and identifies faces in real time.

System preparation : Install the required packages via pip.

<code>pip install cmake
pip install dlib
pip install face_recognition
pip install numpy
pip install opencv-python</code>

If installing dlib fails, download the wheel manually and install it, for example:

<code>cd C:\Users\Dhanush\Downloads\
pip install dlib</code>

Place the Haar cascade XML file ( haarcascade_frontalface_default.xml ) in the same directory as the script.

Training the system : Create a folder named Faces in the script directory and store images of each person, naming each image with the person's name. The program will use these images to learn face encodings.

Face recognition code (the main script):

<code>import face_recognition as fr
import os
import cv2
import numpy as np
from time import sleep

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture(0)
_, img = cap.read()

def get_encoded_faces():
    """Walk through the ./faces folder and encode all face images.
    :return: dict of {name: encoding}
    """
    encoded = {}
    for dirpath, dnames, fnames in os.walk("./faces"):
        for f in fnames:
            if f.endswith('.jpg') or f.endswith('.png'):
                face = fr.load_image_file('faces/' + f)
                encoding = fr.face_encodings(face)[0]
                encoded[f.split('.')[0]] = encoding
    return encoded

def unknown_image_encoded(img):
    """Encode a face given the file name"""
    face = fr.load_image_file('faces/' + img)
    encoding = fr.face_encodings(face)[0]
    return encoding

def classify_face(im):
    """Find all faces in an image and label them if known.
    :param im: str of file path
    :return: list of face names
    """
    faces = get_encoded_faces()
    faces_encoded = list(faces.values())
    known_face_names = list(faces.keys())
    face_locations = face_recognition.face_locations(img)
    unknown_face_encodings = face_recognition.face_encodings(img, face_locations)
    face_names = []
    for face_encoding in unknown_face_encodings:
        matches = face_recognition.compare_faces(faces_encoded, face_encoding)
        name = "Unknown"
        face_distances = face_recognition.face_distance(faces_encoded, face_encoding)
        best_match_index = np.argmin(face_distances)
        if matches[best_match_index]:
            name = known_face_names[best_match_index]
        face_names.append(name)
    for (top, right, bottom, left), name in zip(face_locations, face_names):
        cv2.rectangle(img, (left-20, top-20), (right+20, bottom+20), (255, 0, 0), 2)
        cv2.rectangle(img, (left-20, bottom-15), (right+20, bottom+20), (255, 0, 0), cv2.FILLED)
        font = cv2.FONT_HERSHEY_DUPLEX
        cv2.putText(img, name, (left-20, bottom+15), font, 1.0, (255, 255, 255), 2)
    while True:
        cv2.imshow('IMAGE', img)
        return face_names

print(classify_face("test"))
</code>

Output verification : Running the script opens the webcam, captures frames, and displays the detected faces with bounding boxes and labels. Unknown faces are marked as "Unknown".

Conclusion : The guide provides a complete, runnable example for face detection and recognition in Python, and points readers to additional resources for real‑time video processing.

computer visionface recognitionopencvmachine-learning
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.