Detect faces in live video using Python and OpenCV

Detect faces in live video using Python and OpenCV

In the previous article, I have discussed how to detect faces from user input photos. If you haven’t read that, I highly recommend you read that before. There I have explained how does the OpenCV image detection takes place and did an in-depth code explanation. This article will be like the follow up of that article.
By the end of this article, you will be able to detect faces from a live video feed from the webcam of your device.

Prerequisite

I assume you have already installed and configured the OpenCV library and Python on your machine. There are many good tutorials available online on how to install OpenCV on your machine.
You can double-check if it’s installed properly by the following commands.

python
import cv2
cv2.__version__

Code

You can download the code and all files used in this project from here

import cv2
import sys

cascPath = sys.argv[1]
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.cv.CV_HAAR_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

# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()

Code Explanation

import cv2

Nothing much here, the required modules are imported

cap = cv2.VideoCapture(0)
faceCascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")

cv2.VideoCapture(0) will return video from the webcam of your laptop/pc. If you have multiple webcams you can choose between them by changing 0 – 1.
If you don’t have access to the webcam you can even mention the video like this
cap = cv2.VideoCapture(TestVideo.avi)

In this line it’s we are loading the classifier to detect the face. Like we have done in the last example

while(True):
	ret, frame = cap.read()

Here an infinite loop is initiated. The cap.read() the function returns a boolean expression (TRUE/FALSE). If the frame is properly read then it will return TRUE else it will return FALSE. Sometimes if the cap isn’t initialized you will receive an error. You can cross-check it by the method cap.isOpened().If it returns TRUE everything is fine, else you need to open it by the method cap.open().

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

Here the video is converted into grayscale

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

This is exactly same as previous example .We use detectMultiScale to detect faces in the video by passing four parameters

print("Detected {0} faces!".format(len(faces)))

	for (x, y, w, h) in faces:
		cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)

Prints the number of detected faces in a frame and a rectangle is drawn around the detected face.

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

The frame is displayed on a window with detected faces. This if statement executes once per each frame and if the key q is pressed it will break the infinite loop we created initially.

cap.release()
cv2.destroyAllWindows()

Releases the webcam and closes all the windows.

Output

Here I tried both, from a video input and from live webcam feed. In the terminal you can see the number of detected faces in real time. Like I mentioned in my previous article you won’t always get 100% accuracy. At present machine learning algorithm won’t give 100% always but I am sure soon in future it would be a piece of cake.

In a upcoming article I will show you how to create your own classifier to detected objects of your choice.

Leave a Reply

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