Object Tracking with Python and OpenCV

In this Python OpenCV article we are going to learn about Object Tracking with Python and OpenCV, so first of all let’s talk about Object Tracking, Object tracking is the process of locating and following an object in video or image sequence over time. this technique different use cases, from surveillance systems to robotics and autonomous vehicles. In this article we are going to learn how to perform object tracking using Python and OpenCV.

 

 

What is Python OpenCV ?

OpenCV (Open Source Computer Vision Library) is an open source computer vision and machine learning software library. it provides different functions for image and video processing including object detection and tracking. OpenCV is written in C++ and has Python bindings and this makes it easy to use in Python applications.

 

For this article we need these libraries to be installed.

 

 

 

Object Tracking with Python and OpenCV

Now let’s write some code to perform object tracking using frame by frame tracking approach. we are going to use builtin cv2.Tracker class in OpenCV to perform the tracking. cv2.Tracker class provides several tracking algorithms including MOSSE, KCF, and MIL. for this example, we will use the KCF (Kernelized Correlation Filters) algorithm.

 

 

Now let’s talk about above code, we open video file using the cv2.VideoCapture() function. after that we read the first frame of the video and use the cv2.selectROI() function to define the initial bounding box around the object.

 

 

After that we initialize the tracker using the cv2.TrackerKCF_create() function and tracker.init() method. we pass in the first frame of the video and the initial bounding box.

 

 

After that we enter our loop that reads each frame of the video using video.read() function. if there are no more frames to read we break out of the loop. after we update the tracker using tracker.update() method and current frame of the video. tracker.update() method returns boolean value indicating whether tracking was successful and the new bounding box coordinates.

If the tracking was successful, we draw new bounding box on the current frame using the cv2.rectangle() function. and after that we display the frame using the cv2.imshow() function.

 

 

and finally we have checked if the user has pressed q key. if so, we break out of the loop and release the video capture object using video.release() function. also we close all windows using the cv2.destroyAllWindows() function.

 

 

This is the result

Object Tracking with Python and OpenCV
Object Tracking with Python and OpenCV

 

 

 

Learn More on Python GUI

Leave a Comment