SoFunction
Updated on 2025-03-03

Use Python and OpenCV to achieve real-time facial recognition

Overview

Face recognition is an important computer vision task and is widely used in security monitoring, identity verification and other fields. This article will introduce in detail how to use Python and OpenCV libraries to implement real-time facial recognition, and demonstrate the entire process through specific code examples.

Environmental preparation

Before you start writing your code, make sure that the OpenCV library is installed. You can install it using the following command:

pip install opencv-python

Detailed code explanation

1. Import the necessary modules

import cv2

import cv2: Import the OpenCV library for image processing and face recognition.

2. Define the main function

def main():
    # Load Haar Cascade Classifier    face_cascade = ( + 'haarcascade_frontalface_default.xml')
    '''
    load Haar Cascade Classifier:
    face_cascade = ( + 'haarcascade_frontalface_default.xml')
    ():This is OpenCV A class in,用于load预先训练好of Haar Cascade Classifier。
     + 'haarcascade_frontalface_default.xml':This is OpenCV Introduced pre-training Haar Cascade Classifier文件路径,Used to detect positive faces。
    '''
    # Turn on the default camera    cap = (0)
    '''
    Turn on the default camera:
    cap = (0)
    ():This is OpenCV A class in,Used to capture video。parameter 0 表示Turn on the default camera。
    '''
    while True:
        # Read a frame in the video stream        ret, frame = ()
        '''
        Read a frame in the video stream:
        ret, frame = ()
        ():Read a frame of image from the camera。Return two values:
        ret:Boolean value,Indicates whether the read is successful。If the read is successful,ret for True;否则for False。
        frame:Read image frame。
        '''
        if not ret:
            break
        '''
         Check if the read is successful:
         if not ret:
             break
         If the read fails (such as the camera disconnects), the loop exits.
         '''
        # Convert frames to grayscale because Haar cascade classifiers require grayscale images        gray = (frame, cv2.COLOR_BGR2GRAY)
        '''
        Will帧转换for灰度:
        gray = (frame, cv2.COLOR_BGR2GRAY)
        ():This is OpenCV A function in,For color space conversion。
        frame:Enter an image。
        cv2.COLOR_BGR2GRAY:Will BGR 图像转换for灰度图像。
        '''
        # Detect faces        faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30),
                                             flags=cv2.CASCADE_SCALE_IMAGE)
        '''
        Detect faces:
        faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30),
                                             flags=cv2.CASCADE_SCALE_IMAGE)
        face_cascade.detectMultiScale():This is Haar Cascade Classifierof一个方法,Used to detect human faces in images。
        gray:The input grayscale image。
        scaleFactor=1.1:The ratio of image size reduction each time。
        minNeighbors=5:The number of neighbors that each candidate rectangle should retain。
        minSize=(30, 30):最小Detect facesof尺寸。
        flags=cv2.CASCADE_SCALE_IMAGE:Markers used to optimize detection process。
        '''
        # Draw a rectangle around the detected face        for (x, y, w, h) in faces:
            (frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
            '''
            Draw a rectangle around the detected face:
            for (x, y, w, h) in faces:
                (frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
            for (x, y, w, h) in faces:Iterate through every face detected。
            ():This is OpenCV A function in,Used to draw rectangles on images。
            frame:Enter an image。
            (x, y):Coordinates in the upper left corner of the rectangle。
            (x + w, y + h):Coordinates at the lower right corner of the rectangle。
            (0, 255, 0):Rectangle color(green)。
            2:Thickness of rectangular lines。
            '''
        # Show result frames        ('Face Detection', frame)
        '''
        Show result frames:
        ('Face Detection', frame)
        ():This is OpenCV A function in,Used to display images。
        'Face Detection':Window title。
        frame:Image to display。
        '''
        # Press 'q' to exit the loop        if (1) & 0xFF == ord('q'):
            break
        '''
         according to'q'Exit the loop:
        if (1) & 0xFF == ord('q'):
            break
        (1):wait 1 millisecond,wait用户按key。
        & 0xFF:Will按key值转换for ASCII code。
        ord('q'):Get characters 'q' of ASCII code。
        If the user presses 'q' key,则Exit the loop。
        '''
    # Release the camera and close all windows    ()
    ()
    '''
    Release the camera and close all windows:
    ()
    ()
    ():Release camera resources。
    ():Close all OpenCV window。
    '''
if __name__ == "__main__":
    main()
  • def main():: Define the main functionmain
  • face_cascade = ( + 'haarcascade_frontalface_default.xml'): Loading the Haar cascade classifier for detecting positive faces.
  • cap = (0): Turn on the default camera.
  • while True:: Enter an infinite loop and read the camera image in real time.
  • ret, frame = (): Read a frame of image from the camera.
  • if not ret:: Check whether the read is successful, and exit the loop if it fails.
  • gray = (frame, cv2.COLOR_BGR2GRAY): Convert the image to a grayscale image.
  • faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE): Detect faces in the image.
  • for (x, y, w, h) in faces:: Iterate through each detected face and draw a rectangle on the image.
  • ('Face Detection', frame): Displays an image with rectangular marks.
  • if (1) & 0xFF == ord('q'):: Press the ‘q’ key to exit the loop.
  • (): Release camera resources.
  • (): Close all OpenCV windows.

test

  • Make sure your camera is working properly.
  • Run the script:
python3 face_detection.py
  • Once the camera is turned on, you will see a window showing the live video stream and a green rectangle is drawn around the detected face.
  • Press the ‘q’ key to exit the program.

Summarize

This article details how to use Python and OpenCV libraries to implement real-time facial recognition, and shows the entire process through specific code examples. By usingLoad the pretrained Haar cascade classifier,Turn on the camera,Convert image color space,Drawing rectangles ultimately implements the function of detecting and marking faces in real-time video streams.

This is the article about real-time facial recognition using Python and OpenCV. This is all about this. For more related Python and OpenCV facial recognition content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!