O'Reilly logo

Raspberry Pi: Amazing Projects from Scratch by Richard Grimmett, Matthew Poole, Arush Kakkar, Ashwin Pajankar

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Motion detection and tracking

We will now build a sophisticated motion detection and tracking system with simple logic to find the difference between subsequent frames from a video feed, such as a webcam stream and plotting contours around the area where the difference is detected.

Let's import the required libraries and initialize the webcam:

import cv2
import numpy as np

cap = cv2.VideoCapture(0)

We will need a kernel for the dilation operation that we will create in advance rather than creating it every time in the loop:

k=np.ones((3,3),np.uint8)

The following code will capture and store the subsequent frames:

t0 = cap.read()[1]
t1 = cap.read()[1]

Now we initiate the while loop and calculate the difference between the frames and convert the output ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required