The video module in OpenCV
The video module in OpenCV provides functions for video processing and analysis, such as object tracking, motion estimation, and video stabilization.
Here is an example of how to use the video module to track an object in a video using the Lucas-Kanade optical flow algorithm:
import cv2
import numpy as np
# Read the video file
video = cv2.VideoCapture('video.mp4')
# Read the first frame
success, frame = video.read()
# Check if the video is opened correctly
if not success:
print('Error: Could not read the video file')
exit()
# Select the object to track
bbox = cv2.selectROI(frame, False)
# Create the tracker
tracker = cv2.TrackerKCF_create()
# Initialize the tracker with the object's bounding box
tracker.init(frame, bbox)
while True:
# Read the next frame
success, frame = video.read()
# Check if the video has ended
if not success:
break
# Update the tracker
success, bbox = tracker.update(frame)
# Check if the tracker is still tracking the object
if success:
# Draw the bounding box on the frame
p1 = (int(bbox[0]), int(bbox[1]))
p2 = (int(bbox[0] + bbox[2]), int(bbox[1] + bbox[3]))
cv2.rectangle(frame, p1, p2, (0, 0, 255), 2)
# Display the frame
cv2.imshow('frame', frame)
# Check if the user pressed the 'q' key
key = cv2.waitKey(1)
if key == ord('q'):
break
# Release the video capture and destroy the window
video.release()
cv2.destroyAllWindows()
In this example, the video file is read using the VideoCapture
class, and the first frame is displayed using the selectROI
function, which allows the user to select the object to track by drawing a bounding box around it. The TrackerKCF_create
function is used to create the tracker, and the init
function is used to initialize it with the object's bound.
Leave a Comment