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 ...

Get Raspberry Pi: Amazing Projects from Scratch now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.