OpenCV (Open Source Computer Vision Library) is a popular Python library used for computer vision tasks like image and video processing. One of the fascinating features of OpenCV is its ability to perform motion detection and tracking. In this article, we will explore how to utilize OpenCV to detect and track moving objects in a video feed.
Motion detection involves analyzing consecutive frames of a video stream or image sequence to identify areas where motion has occurred. OpenCV provides several techniques to achieve this, including frame differencing and background subtraction.
Frame differencing is a simple yet effective technique for detecting motion in a video feed. It involves subtracting consecutive frames from each other and thresholding the resulting difference image.
Here are the basic steps to implement frame differencing motion detection using OpenCV:
Background subtraction is another widely used technique for motion detection. It involves generating and maintaining a background model of the video feed and then subtracting this background model from each frame to obtain the foreground.
Here are the basic steps to implement background subtraction motion detection using OpenCV:
Now that we understand the concept of motion detection, let's dive into implementing it using OpenCV in Python.
To follow along with the code examples, make sure you have the following installations:
import cv2
import numpy as np
# Initialize video capture
cap = cv2.VideoCapture(0)
# Capture the first frame
ret, frame1 = cap.read()
# Convert the first frame to grayscale
prev_frame = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY)
while True:
# Read the current frame
ret, frame2 = cap.read()
# Convert the current frame to grayscale
curr_frame = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY)
# Calculate the absolute difference between the current and previous frame
frame_diff = cv2.absdiff(curr_frame, prev_frame)
# Apply a threshold to the difference image
thresh = cv2.threshold(frame_diff, 30, 255, cv2.THRESH_BINARY)[1]
# Perform noise removal by applying morphological operations
thresh = cv2.erode(thresh, None, iterations=2)
thresh = cv2.dilate(thresh, None, iterations=2)
# Find contours of moving objects
contours, _ = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Draw bounding rectangles around moving objects
for contour in contours:
if cv2.contourArea(contour) > 500:
(x, y, w, h) = cv2.boundingRect(contour)
cv2.rectangle(frame2, (x, y), (x + w, y + h), (0, 255, 0), 2)
# Display the resulting frame
cv2.imshow("Motion Detection", frame2)
# Update the previous frame
prev_frame = curr_frame
# Exit on 'q' key press
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Release video capture
cap.release()
# Destroy all windows
cv2.destroyAllWindows()
import cv2
import numpy as np
# Create a background subtractor object
bg_subtractor = cv2.createBackgroundSubtractorMOG2()
# Initialize video capture
cap = cv2.VideoCapture(0)
while True:
# Read the current frame
ret, frame = cap.read()
# Apply the background subtractor to obtain the foreground mask
fg_mask = bg_subtractor.apply(frame)
# Perform noise removal on the foreground mask
fg_mask = cv2.erode(fg_mask, None, iterations=2)
fg_mask = cv2.dilate(fg_mask, None, iterations=2)
# Find contours of moving objects
contours, _ = cv2.findContours(fg_mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Draw bounding rectangles around moving objects
for contour in contours:
if cv2.contourArea(contour) > 500:
(x, y, w, h) = cv2.boundingRect(contour)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
# Display the resulting frame
cv2.imshow("Motion Detection", frame)
# Exit on 'q' key press
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Release video capture
cap.release()
# Destroy all windows
cv2.destroyAllWindows()
Motion detection and tracking are essential techniques in computer vision applications. With OpenCV and Python, performing motion detection becomes straightforward. By using techniques like frame differencing or background subtraction, you can easily identify and track moving objects in video feeds. Try experimenting with different algorithms, parameters, and techniques to enhance your motion detection and tracking capabilities. Happy detecting!
noob to master © copyleft