Face Detection in Video

Learn how to detect faces using video in Python.

We'll cover the following

Processing a video frame by frame

OpenCV grabs each frame from a live video via webcam. We’ll use the same processing techniques that we have for a single image. However, this time, we’ll do it frame by frame. This will require a lot of processing.

In the code widget below, we’re creating a face cascade.

In lines 17–18 in the code block below, we captured the video. The read() function reads one frame from the video source, which, in this example, is the webcam. This returns:

  • The actual video frame read (one frame on each loop)

  • A return code

The return code tells us whether we’ve run out of the frames being read from a file. This doesn’t matter when reading from the webcam, since it can be read forever.

The highlighted piece of code should be familiar as it’s the same one from before. We’re merely searching for the face in our captured frame.

We’ll wait for the “q” key to be pressed in line 45. If it’s pressed, we’ll exit the script.

We’re cleaning up in lines 48–49.

Get hands-on with 1400+ tech skills courses.