Motion Detection

Learn how to detect motion using a video in Python.

We'll cover the following

How to detect motion using frames

In this lesson, we’ll detect motion in a video using two consecutive frames and finding the differences between them. If the difference is minor, that means no motion occurred. If we find a significant difference between frames, then a motion must have occurred.

Look at lines 1–10 of the code block below. In this code, we’re creating a video capture instance. Then we’ll read the last and the current frames and convert them to grayscale in lines 13–15.

Here we’ll read two frames and convert them to grayscale. It might seem like we’re doing this outside the while loop. This is because we want two consecutive frames captured before the main loop starts. We’ll call them last_frame and current_frame. Why do we need two to see the difference between them.

In line 18 of the code block below, we’ll enter our “while” loop and store the current_frame as the last_frame. That’s because for each loop iteration, the current_frame from the previous iteration will become the last_frame of this iteration.

Now in line 26, we read a new frame and convert it to grayscale.

Next in line 28, we use the inbuilt absdiff() to find the absolute difference between consecutive frames.

Difference between two consecutive frames

Now, we have a code that will show us what the difference is. Before that, we must understand that OpenCv video and image frames are NumPy arrays that contain the values of all the pixels in the image or video. If we want, we can print the whole array as shown in the code below.

Get hands-on with 1000+ tech skills courses.

Learn to code, grow your skills, and succeed in your tech interview