masukmia

Object Tracking with OpenCV and Python: A Beginner’s Guide to Detection & Tracking

best object tracking python project

object tracking

Before diving into object tracking and detection, ensure you have installed all the necessary libraries.

Find Amazon python books from here:

Python Programming for Beginners: A Complete Step-by-Step Guide to Mastering Python Coding in Less Than a Month 

Install OpenCV

If you haven’t installed OpenCV yet, run the following command:

bashCopyEditpip install opencv-python

Download Required Files

You’ll need specific files for this tutorial. Download them using the link provided at the bottom of this page.

1. Object Detection

To simplify the process, I’ve already written the object detection script, which you can find in the object_detection.py file. This tutorial uses YOLO v4 with a pre-trained model. If you need a custom model, I recommend following a guide on training YOLO to detect custom objects using a free GPU online.

To use object detection, simply call the script in your main file:

pythonCopyEditfrom object_detection import ObjectDetection

# Initialize Object Detection
od = ObjectDetection()

while True:
    # Detect objects in the frame
    (class_ids, scores, boxes) = od.detect(frame)

    for box in boxes:
        (x, y, w, h) = box
        cx = int((x + x + w) / 2)
        cy = int((y + y + h) / 2)
        center_points_cur_frame.append((cx, cy))

This will detect objects and mark their center points in each frame.


2. Object Tracking

How Object Tracking Works

By saving the center point position of each object, you can trace its previous locations and predict where it will move next. Below is an example of tracking an object’s movement.

Note: Object tracking is more complex than this basic example. This tutorial introduces the fundamental concepts, but for real-world applications, consider using SORT or Deep SORT.

Assigning IDs to Objects

To track objects accurately, we only need to keep the last few positions. We then calculate the distance between points to determine if they belong to the same object. The closer the points, the higher the probability that we are tracking the same object.

Step 1: Initialize Tracking Variables

pythonCopyEdit# Initialize variables
count = 0
center_points_prev_frame = []
tracking_objects = {}
track_id = 0

Step 2: Compare Previous and Current Frames

pythonCopyEditif count <= 2:
    for pt in center_points_cur_frame:
        for pt2 in center_points_prev_frame:
            distance = math.hypot(pt2[0] - pt[0], pt2[1] - pt[1])
            if distance < 20:
                tracking_objects[track_id] = pt
                track_id += 1

This code calculates the distance between two points using math.hypot(). If the distance is less than 20, the system assigns an ID to the object.

Updating IDs for Moving Objects

Once an object has an assigned ID, it should retain that ID throughout its movement. If an object disappears, its ID is removed.

pythonCopyEditelse:
    tracking_objects_copy = tracking_objects.copy()
    for object_id, pt2 in tracking_objects_copy.items():
        object_exists = False
        for pt in center_points_cur_frame_copy:
            distance = math.hypot(pt2[0] - pt[0], pt2[1] - pt[1])
            # Update existing object IDs
            if distance < 20:
                tracking_objects[object_id] = pt
                object_exists = True
                continue
        # Remove lost objects
        if not object_exists:
            tracking_objects.pop(object_id)

Now, each object retains the same ID while it is detected, and once it is lost, the ID is removed.

Assigning IDs to Newly Detected Objects

If a new object enters the frame, it must be assigned a unique ID. The following code updates the list to include new objects while removing old ones.

pythonCopyEditelse:
    tracking_objects_copy = tracking_objects.copy()
    center_points_cur_frame_copy = center_points_cur_frame.copy()
    
    for object_id, pt2 in tracking_objects_copy.items():
        object_exists = False
        for pt in center_points_cur_frame_copy:
            distance = math.hypot(pt2[0] - pt[0], pt2[1] - pt[1])
            # Update IDs
            if distance < 20:
                tracking_objects[object_id] = pt
                object_exists = True
                if pt in center_points_cur_frame:
                    center_points_cur_frame.remove(pt)
                continue
        # Remove lost objects
        if not object_exists:
            tracking_objects.pop(object_id)

    # Assign IDs to new objects
    for pt in center_points_cur_frame:
        tracking_objects[track_id] = pt
        track_id += 1

This ensures that new objects receive an ID while maintaining existing IDs for tracked objects.


3. Object Tracking for Industrial Applications

This tutorial introduces the fundamentals of object tracking. I encourage you to practice by creating simple tracking programs.

For more advanced tracking solutions, consider:

  • Object Tracking with OpenCV and Python
  • Deep SORT for robust tracking in real-world applications

If you need a complete guide on object tracking, check out my Build COMPUTER VISION PROJECTS course, which covers Deep SORT-based tracking and real-world use cases.

Share your love
masukmia
masukmia

I am Masuk Mia, currently pursuing a degree in Computer Science and Information Technology at the International Islamic University Malaysia. My academic journey is fueled by a deep passion for technology, web development, digital marketing, and research, driving me to continually expand my knowledge and skills in these fields.

Articles: 27

Newsletter Updates

Enter your email address below and subscribe to our newsletter

Leave a Reply

Your email address will not be published. Required fields are marked *