How to Detect Pedestrians in a Video in Python using OpenCV



Python


In this article, we show how to detect pedestrians in a video in Python using the OpenCV module.

Using computer vision software such as OpenCV, we can create a pedestrian detector or classifier using the cv2.CascadeClassifier() function.

We then create an array of all the pedestrians in the video.

We then loop through each of the pedestrians in the array and draw a rectangle around each of them.

The video we will be using is shown at the following link: Pedestrians.

After we apply this code, our software program will mark pedestrians by putting rectangles around them.

Below is the full code of this software.



Let's now go over this code.

First, we import OpenCV using the line, import cv2

We then create a variable, body_classifier, which is equal to cv2.CascadeClassifier('haarcascade_fullbody.xml'). This file can be seen as the heart of the program. It gives the program the ability to classify objects as pedestrians. It's basically a ready-made file that we can use to classify pedestrians as pedestrians. You can download this file at the following link: haarcascade_fullbody.xml

Next, we read in the video, which in this case is, Pedestrians.avi

We then keep track of the frames of the video.

We resize the video.

We make a grayscale version of the image for greater simplicity.

We then create a variable, pedestrians, which is an array that keeps track of all pedestrians detected in the video.

We then have a for loop, which loops through each of the items in this variable, pedestrians.

We then draw a rectangle around each of the pedestrians. We do this in a yellow color.

We then show the video as all these pedestrians are being detected.

The video closes if the 'Enter' key is pressed.

We then close the video and destroy all windows.

So this is how we can detect pedestrians in a video in Python using OpenCV.


Related Resources

How to Draw a Rectangle in Python using OpenCV

How to Draw a Circle in Python using OpenCV

How to Draw a Line in Python using OpenCV

How to Add Text to an Image in Python using OpenCV

How to Display an OpenCV image in Python with Matplotlib

How to Use Callback functions to Connect Images to Events in Python using OpenCV

How to Check for Multiple Events in Python using OpenCV



HTML Comment Box is loading comments...