Detecting and tracking motion
Let's build a system for detecting and tracking motion in real time with the RPi, OpenCV, and Python. We will use a very simple technique to detect motion. Basically, we will compute the difference between the successive frames of a video feed (a video file or a live feed from a USB webcam). Then, we will plot contours around the area of pixels where we wish to detect the difference between successive frames:
- We will begin by importing OpenCV and NumPy. Also, initialize an object corresponding to the USB webcam:
import cv2 import numpy as np cap = cv2.VideoCapture(0)
- We will apply the dilation operation to the frames in the video. We need a kernel for that. We will define it before the video loop. Let's define it as follows:
k = np.ones((3, 3), np.uint8)
- The following code captures and stores the successive frames in separate variables:
t0 = cap.read()[1] t1 = cap.read()[1]
- Now, let's write the block for the
while
loop....