Real-time Face Recognition with Python & OpenCV

Real-time Face recognition python project with OpenCV

In this beginner’s project, we will learn how to implement real-time human face recognition. We will build this project in Python using OpenCV.

We will study the Haar Cascade Classifier algorithms in OpenCV. Haar Cascade Classifier is a popular algorithm for object detection.

Face Recognition Python Project

Face Recognition Python Project:

Face Recognition is a technology in computer vision. In Face recognition / detection we locate and visualize the human faces in any digital image.

It is a subdomain of Object Detection, where we try to observe the instance of semantic objects. These objects are of particular class such as animals, cars, humans, etc. Face Detection technology has importance in many fields like marketing and security.

Cascade Classifiers and Haar Features:

Cascade Classifiers and Haar Features are the methods used for Object Detection.

It is a machine learning algorithm where we train a cascade function with tons of images. These images are in two categories: positive images containing the target object and negative images not containing the target object.

There are different types of cascade classifiers according to different target objects. In our project, we will use a classifier that considers the human face to recognize it as the target object.

Haar Feature selection technique has a target to extract human face features. Haar features are like convolution kernels. These features are different permutations of black and white rectangles. In each feature calculation, we find the sum of pixels under white and black rectangles.

Follow TechVidvan on Google & Stay updated with latest technology trends

Haar-cascade Detection in OpenCV:

OpenCV provides pre-trained models on Haar features and Cascade classifiers. These models are located in OpenCV installation. You can find the necessary XML files at:

/home/<username>/.local/lib/<python-version>/site-packages/cv2/data/

In the below code we will see how to use these pre-trained Haar cascade models to detect Human Face. We will implement a real-time human face recognition with python

Steps to implement human face recognition with Python & OpenCV:

First, create a python file face_detection.py and paste the below code:

1. Imports:

import cv2
import os

2. Initialize the classifier:

cascPath=os.path.dirname(cv2.__file__)+"/data/haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascPath)

3. Apply faceCascade on webcam frames:

video_capture = cv2.VideoCapture(0)

while True:
    # Capture frame-by-frame
    ret, frames = video_capture.read()

    gray = cv2.cvtColor(frames, cv2.COLOR_BGR2GRAY)

    faces = faceCascade.detectMultiScale(
        gray,
        scaleFactor=1.1,
        minNeighbors=5,
        minSize=(30, 30),
        flags=cv2.CASCADE_SCALE_IMAGE
    )

    # Draw a rectangle around the faces
    for (x, y, w, h) in faces:
        cv2.rectangle(frames, (x, y), (x+w, y+h), (0, 255, 0), 2)

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

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

4. Release the capture frames:

video_capture.release()
cv2.destroyAllWindows()

5. Now, run the project file using:

python3 face_detection.py

You will observe the bounding boxes in webcam frames. To stop the webcam capture press “q”.

Summary:

In this deep learning project, we developed a model for real-time human face recognition with python and opencv.

We discussed about Face detection, Cascade classifier, and Haar features, and finally how to use pre-trained model to detect human face in real-time.

Did you like the tutorial? Please rate TechVidvan on Facebook.

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google | Facebook


25 Responses

  1. Venkat Ramana says:

    where is face recognition???

  2. Venkat Ramana says:

    It is only face detection….

  3. Shiv Patel says:

    I’m having error : NameError Traceback (most recent call last)
    in
    3 # Capture frame-by-frame
    4 ret, frames = video_capture.read()
    —-> 5 gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    6 faces = faceCascade.detectMultiScale(
    7 gray,

    NameError: name ‘frame’ is not defined

  4. Shiv Patel says:

    NameError Traceback (most recent call last)
    in
    3 # Capture frame-by-frame
    4 ret, frames = video_capture.read()
    —-> 5 gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    6 faces = faceCascade.detectMultiScale(
    7 gray,

    NameError: name ‘frame’ is not defined

  5. Sonu says:

    Here, in this line they use ‘frames’ not ‘frame’ –
    ret, frames = video_capture.read()

    —-> 5 gray = cv2.cvtColor(frames, cv2.COLOR_BGR2GRAY)

    use this above line in your code and

  6. karim says:

    please i want a source to stdy deep learning from 0 so i can start doing projects

  7. James says:

    I keep getting this error:
    flags=cv2.CASCADE_SCALE_IMAGE
    cv2.error: OpenCV(4.5.1-dev) /home/pi/opencv/modules/objdetect/src/cascadedetect.cpp:1689:
    error: (-215:Assertion failed) !empty() in function ‘detectMultiScale’

    Please some help me

    James

    • Bhopathi Vardhan Kumar Reddy says:

      I am facing the same problem. Please help me to slove

      • Ricky says:

        This means that CascadeClassifier() could not find the xml file. You’ll need to either find the correct path to it or download it from the opencv github and put in a path to that

  8. Rock says:

    import cv2
    import os

    cascPath=os.path.dirname(cv2.__file__)+”/data/haarcascade_frontalface_default.xml”
    faceCascade = cv2.CascadeClassifier(cascPath)

    video_capture = cv2.VideoCapture(0)

    while True:
    # Capture frame-by-frame
    ret, frame = video_capture.read()

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    faces = faceCascade.detectMultiScale(
    gray,
    scaleFactor=1.1,
    minNeighbors=5,
    minSize=(30, 30),
    flags=cv2.CASCADE_SCALE_IMAGE
    )

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

    # Display the resulting frame
    cv2.imshow(‘Video’, frame)

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

    video_capture.release()
    cv2.destroyAllWindows()

    • Tech Vidvan says:

      Thanks for helping the community, keep learning.

    • Bhopathi Vardhan Kumar Reddy says:

      OpenCV(4.0.1) C:\ci\opencv-suite_1573470242804\work\modules\objdetect\src\cascadedetect.cpp:1658: error: (-215:Assertion failed) !empty() in function ‘cv::CascadeClassifier::detectMultiScale’

      I am getting this error

  9. Vinayak Tiku says:

    Thank you this code worked absolutely fine. Its really so grateful that you are uploading very beneficial information, that is correct and accurate too.
    Please could you help me. I am developing a face detecting and counting project. So could you add the further code in this same program of yours which could show the number of faces detected.

  10. GARIMELLA SREE LAHARI says:

    error Traceback (most recent call last)
    in
    6 while True:
    7 ret,frames=video.read()
    —-> 8 cnvt=cv2.cvtColor(frames,cv2.COLOR_BGR2GRAY)
    9 face=faceCascade.detectMultiScale(cnvt,scaleFactor=1.1,minNeighbors=5,minSize=(30,30))
    10 for (x,y,w,h) in face:

    Can anyone help me to solve this error

  11. Pherez Sigu says:

    Would like to see the file structure arrangement so that we can replicate the same , also would like a link to YouTube to provide step by step scenarios to see the whole development process.

  12. James says:

    does it work with normal IP based CCTV cameras?

  13. ashlesha says:

    error: OpenCV(4.0.1) C:\ci\opencv-suite_1573470242804\work\modules\objdetect\src\cascadedetect.cpp:1658: error: (-215:Assertion failed) !empty() in function ‘cv::CascadeClassifier::detectMultiScale’
    I am getting this type of error how to solve it help me out

Leave a Reply

Your email address will not be published. Required fields are marked *