Last update: December 2026. The code has been rewritten for the current OpenCV C++ and Python APIs and tested on OpenCV 4.6 (C++) and OpenCV 5.0.0 (Python). See What I tested for the details.

Introduction

This is one of the oldest tutorials I have ever written. It started on my old website, robot-home.it, and was republished on my WordPress blog in January 2018, which is the date you see on this page. It all began with a short YouTube video showing a “simple” program that finds a blue ball moving on a table and keeps tracking it even when the ball passes behind a bottle. At the time the video had been viewed more than 5000 times, and a lot of people asked me for the source code and for an explanation of how it works. The code went all around the world through GitHub, and this tutorial is the explanation.

Here is the original demo:

OpenCV Demo: Object tracking with Kalman Filter Plays from YouTube, which may set cookies. Privacy · Watch on YouTube

Moving the tutorial to this site was a good occasion to look at that code again with fresh eyes. The idea still holds, but the code was written for the OpenCV 2 API, it used the old C constants (CV_RETR_EXTERNAL, CV_BGR2HSV, CV_CAP_PROP_FRAME_WIDTH, …) that are gone from OpenCV 4 and 5, and it contained a few bugs that I explain below. So this is not a copy of the old post: the theory part is rewritten and much more detailed, and the code is modernized, fixed, and tested.

By the end of this tutorial you will know:

  • how to isolate an object by its color with the HSV color space;
  • how to clean the binary mask and select the right contours;
  • how a Kalman filter models a moving object: state vector, transition matrix, measurement matrix and noise covariances;
  • how the predict / correct cycle keeps the track alive when the object is hidden (occlusion);
  • how to use cv::KalmanFilter correctly, including the initialization detail that the original code got wrong.

The problem

We have a camera looking at a table. A blue ball moves on the table, and sometimes it passes behind an obstacle (a bottle, in the original video). We want to know, at every frame, where the ball is.

Detecting the ball in a single frame is easy when it is visible: it is the only blue, round thing in the scene. The hard parts are:

  1. Measurements are noisy. The detected position jitters by a pixel or two from frame to frame, and the bounding box changes shape when the ball is partially hidden.
  2. Measurements are sometimes missing. When the ball is behind the bottle, the detector returns nothing. A pure detector would say “no ball”, but we know the ball is still there and is still moving.

The Kalman filter solves both problems with one idea: combine a model of how the ball moves with the measurements, and weigh each of them by how much we trust it. When a measurement is available, the estimate follows it closely. When it is missing, the model keeps predicting where the ball should be.

The detection pipeline

The detection part is a classic color-based pipeline. Each step is simple, and the order matters.

1. Smoothing

cv::GaussianBlur(frame, blur, cv::Size(5, 5), 3.0, 3.0);

A small Gaussian blur removes the sensor noise that would otherwise create isolated pixels in the color mask.

2. From BGR to HSV

cv::cvtColor(blur, hsv, cv::COLOR_BGR2HSV);

In the BGR space, “blue” is spread across all three channels and changes a lot with the light: a blue ball in the shadow has completely different B, G and R values than the same ball under a lamp. The HSV space separates the color (Hue) from its purity (Saturation) and its brightness (Value), so a single range on the Hue channel selects the color regardless of most lighting changes.

One OpenCV detail that confuses everybody the first time: for 8-bit images the Hue channel goes from 0 to 179, not 0 to 360, because 360 does not fit in a byte. OpenCV stores degrees / 2. That is why the code defines the range in degrees and divides by two:

constexpr int MIN_H_DEG = 200;
constexpr int MAX_H_DEG = 300;
...
cv::inRange(hsv, cv::Scalar(MIN_H_DEG / 2, 100, 80),
            cv::Scalar(MAX_H_DEG / 2, 255, 255), mask);

Pure blue is at 240°, so the range 200° to 300° (100 to 150 in OpenCV units) is centered a bit towards violet; it is the range I used with my ball, and it is the first thing to adjust for your object. The lower limits on Saturation (100) and Value (80) reject grayish and dark pixels, whose hue is meaningless. To track a different color, change only the two *_H_DEG constants.

3. Morphological cleaning

cv::erode(mask, mask, cv::Mat(), cv::Point(-1, -1), 2);
cv::dilate(mask, mask, cv::Mat(), cv::Point(-1, -1), 2);

Two erosions remove small isolated blobs, two dilations restore the size of the blobs that survived. This is a morphological opening, and it removes most of the false positives caused by small blue-ish reflections.

Binary mask produced by the HSV threshold: a single white disc on a black background
The mask after HSV thresholding and morphological opening. Only the ball survives: the green square and the brown occluder are outside the hue range.

4. Contours and filtering

std::vector<std::vector<cv::Point>> contours;
cv::findContours(mask, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);

cv::RETR_EXTERNAL returns only the outer contours, which is what we want for solid blobs. cv::CHAIN_APPROX_SIMPLE compresses straight segments and gives exactly the same bounding boxes as CHAIN_APPROX_NONE, with fewer points.

Not every blob is a ball. Each contour is filtered with two simple tests on its bounding box:

  • Squareness: the ratio between the short and the long side must be greater than 0.75, because a ball seen from any direction has an almost square bounding box;
  • Area: at least 400 px², to reject what the opening did not remove.

Both tests must pass. The original code used || (OR) instead of && (AND): any blob larger than 400 px² was accepted whatever its shape, and that is a bug.

The squareness test has a nice side effect: when the ball is partially hidden by the obstacle, its visible part is no longer square and the blob is discarded. A half-visible ball would give a centroid shifted towards the visible side, and it is better to give the filter no measurement than a wrong one.

When more than one blob passes the filter, the code uses the largest one as the measurement (the original simply took the first one in the list).

The Kalman filter

The Kalman filter is a recursive estimator: at every step it keeps an estimate of the state of a system and of the uncertainty of that estimate, and it updates both in two phases:

  • Predict: use the motion model to move the state forward in time. The uncertainty grows, because the model is not perfect.
  • Correct (or update): when a measurement arrives, blend it with the prediction. The weight of each side depends on their uncertainties, and the uncertainty shrinks.

The theory requires some linear algebra and probability, but the model of a ball on a table is simple enough to write down completely.

The state vector

The state is what we want to know about the ball at time k:

state = [ x, y, vx, vy, w, h ]ᵀ
  • x, y: center of the ball in the image [px];
  • vx, vy: velocity of the center [px/s];
  • w, h: width and height of the bounding box [px].

The measurement vector

The detector gives us only four of those six values:

meas = [ zx, zy, zw, zh ]ᵀ

The velocity is never measured directly. The filter infers it from the sequence of positions, and this is exactly what allows it to keep predicting during an occlusion.

The transition matrix A

The motion model is a constant velocity model: in the time dT between two frames, the center moves by v · dT, the velocity does not change, and the size does not change:

x(k) = A · x(k-1)

    | 1  0  dT 0  0  0 |
    | 0  1  0  dT 0  0 |
A = | 0  0  1  0  0  0 |
    | 0  0  0  1  0  0 |
    | 0  0  0  0  1  0 |
    | 0  0  0  0  0  1 |

This is a strong assumption: a real ball slows down because of friction and changes direction when it bounces. The filter handles small violations of the model through the process noise (see below), and you will see in the test results what happens when the violation is big.

The matrix is set to identity once, and the two dT terms are written at every frame, because the time between frames is not constant with a real camera:

kf.transitionMatrix.at<float>(0, 2) = static_cast<float>(dT);
kf.transitionMatrix.at<float>(1, 3) = static_cast<float>(dT);

The measurement matrix H

H maps the state into the space of the measurements, z = H · x. We measure x, y, w and h, so H just picks those four elements:

    | 1  0  0  0  0  0 |
H = | 0  1  0  0  0  0 |
    | 0  0  0  0  1  0 |
    | 0  0  0  0  0  1 |

The original code filled these matrices with linear indices, like measurementMatrix.at<float>(16) = 1.0f. It works, but at<float>(row, col) is much easier to read and to check against the equation.

The noise covariances Q and R

  • Q, the process noise covariance, says how much we trust the model. It is added to the uncertainty at every prediction. Here it is diagonal: small for position and size (10⁻² px²), larger for the velocity (5 (px/s)²), because the velocity is what the constant velocity model gets wrong when the ball accelerates or bounces.
  • R, the measurement noise covariance, says how much we trust the detector. Here it is 0.1 · I: the color detection of a well-lit ball is precise to about a pixel.

The ratio between Q and R is what really matters. A large Q (or a small R) makes the filter follow the measurements closely and react quickly; a small Q (or a large R) makes the estimate smoother but slower to react. These values come from the original program and work well for a ball on a table; for a different object or camera, they are the knobs to tune.

A more rigorous model derives Q from the variance of an unknown acceleration, with terms that depend on dT. For this application, a fixed diagonal Q is good enough and much easier to tune by hand.

The predict / correct cycle

cv::KalmanFilter implements the standard equations. predict() computes:

x⁻(k) = A · x(k-1)
P⁻(k) = A · P(k-1) · Aᵀ + Q

and correct(z) computes the Kalman gain and blends prediction and measurement:

K(k) = P⁻(k) · Hᵀ · ( H · P⁻(k) · Hᵀ + R )⁻¹
x(k) = x⁻(k) + K(k) · ( z(k) - H · x⁻(k) )
P(k) = ( I - K(k) · H ) · P⁻(k)

In OpenCV the “minus” quantities are statePre and errorCovPre, the corrected ones are statePost and errorCovPost. An important detail of the implementation: predict() also copies statePre into statePost (and errorCovPre into errorCovPost). This is what makes occlusions work: if no measurement arrives, we simply do not call correct(), and the next predict() starts from the previous prediction. The uncertainty keeps growing at every step without a measurement, so when the ball comes back the filter trusts the new measurement a lot and snaps back onto it.

The main loop is therefore:

  1. if a track is active, predict;
  2. run the detector;
  3. if the ball is detected, correct with the measurement (or initialize the track if this is the first detection);
  4. if the ball has not been detected for MAX_LOST_FRAMES consecutive frames, drop the track and wait for a new detection.

Initialization: the bug in the original code

When a track starts, the state is initialized from the first measurement, with zero velocity because we do not know it yet. The original code then set the initial uncertainty like this:

kf.errorCovPre.at<float>(0) = 1; // wrong matrix

This has no effect. KalmanFilter::init() sets both errorCovPre and errorCovPost to zero, and the next call to predict() overwrites errorCovPre with A · P · Aᵀ + Q, where P is errorCovPost. The value that matters is errorCovPost, which was left at zero: the filter started convinced that its initial state, including the zero velocity, was perfect, and only Q slowly made it change its mind.

The fixed code sets errorCovPost, and gives the velocity a large initial uncertainty (10⁴ (px/s)²) because it is completely unknown:

kf.errorCovPost = cv::Mat::zeros(stateSize, stateSize, type);
kf.errorCovPost.at<float>(0, 0) = 1.0f;   // x
kf.errorCovPost.at<float>(1, 1) = 1.0f;   // y
kf.errorCovPost.at<float>(2, 2) = 1e4f;   // vx
kf.errorCovPost.at<float>(3, 3) = 1e4f;   // vy
kf.errorCovPost.at<float>(4, 4) = 1.0f;   // w
kf.errorCovPost.at<float>(5, 5) = 1.0f;   // h

With this change, in my test the estimated velocity converges to the true value within about five frames from the first detection.

The complete C++ code

Compared to the original program, besides the modern API and the fixes already described:

  • the source can be a camera index or a video file, so you can test the tracker on a recorded video;
  • with a video file, dT is the nominal frame period instead of the processing time, otherwise the velocity would be wrong when the file is processed faster or slower than real time;
  • the main loop exits correctly with q or ESC (the original condition ch != 'q' || ch != 'Q' is always true, so the loop never ended);
  • the track is dropped after 30 frames without detections (one second at 30 FPS; the original used 100);
  • every frame prints a CSV line with the measurement and the estimate, which I used to produce the plot below.
// Ball tracker: HSV color segmentation + Kalman filter (OpenCV 4.x / 5.x)
// Usage: ./ball_tracker [camera_index | video_file]

#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/video/tracking.hpp>
#include <opencv2/videoio.hpp>

#include <algorithm>
#include <cstdio>
#include <iostream>
#include <string>
#include <vector>

// ----> Color to be tracked (hue in degrees, 0-360)
constexpr int MIN_H_DEG = 200;
constexpr int MAX_H_DEG = 300;
// <---- Color to be tracked

constexpr int MIN_BLOB_AREA = 400;       // [px^2] reject small blobs
constexpr float MIN_SQUARENESS = 0.75f;  // short side / long side of the bbox
constexpr int MAX_LOST_FRAMES = 30;      // frames without a detection before reset

int main(int argc, char** argv)
{
    // ----> Video source: camera index (default 0) or video file
    std::string src = (argc > 1) ? argv[1] : "0";
    cv::VideoCapture cap;
    bool isFile = false;
    if (src.find_first_not_of("0123456789") == std::string::npos) {
        cap.open(std::stoi(src));
        cap.set(cv::CAP_PROP_FRAME_WIDTH, 1280);
        cap.set(cv::CAP_PROP_FRAME_HEIGHT, 720);
    } else {
        cap.open(src);
        isFile = true;
    }
    if (!cap.isOpened()) {
        std::cerr << "Cannot open video source '" << src << "'\n";
        return EXIT_FAILURE;
    }
    const double fileFps = isFile ? cap.get(cv::CAP_PROP_FPS) : 0.0;
    // <---- Video source

    // ----> Kalman filter: state [x, y, vx, vy, w, h], measurement [zx, zy, zw, zh]
    const int stateSize = 6;
    const int measSize = 4;
    const int contrSize = 0;
    const int type = CV_32F;
    cv::KalmanFilter kf(stateSize, measSize, contrSize, type);

    cv::Mat state(stateSize, 1, type);
    cv::Mat meas(measSize, 1, type);

    // Transition matrix A: constant velocity for (x, y), constant size for (w, h).
    // The dT terms in A(0,2) and A(1,3) are updated at every frame.
    cv::setIdentity(kf.transitionMatrix);

    // Measurement matrix H: we measure x, y, w, h, but not the velocity.
    kf.measurementMatrix = cv::Mat::zeros(measSize, stateSize, type);
    kf.measurementMatrix.at<float>(0, 0) = 1.0f;
    kf.measurementMatrix.at<float>(1, 1) = 1.0f;
    kf.measurementMatrix.at<float>(2, 4) = 1.0f;
    kf.measurementMatrix.at<float>(3, 5) = 1.0f;

    // Process noise covariance Q (diagonal)
    kf.processNoiseCov = cv::Mat::zeros(stateSize, stateSize, type);
    kf.processNoiseCov.at<float>(0, 0) = 1e-2f;  // x  [px^2]
    kf.processNoiseCov.at<float>(1, 1) = 1e-2f;  // y  [px^2]
    kf.processNoiseCov.at<float>(2, 2) = 5.0f;   // vx [(px/s)^2]
    kf.processNoiseCov.at<float>(3, 3) = 5.0f;   // vy [(px/s)^2]
    kf.processNoiseCov.at<float>(4, 4) = 1e-2f;  // w  [px^2]
    kf.processNoiseCov.at<float>(5, 5) = 1e-2f;  // h  [px^2]

    // Measurement noise covariance R
    cv::setIdentity(kf.measurementNoiseCov, cv::Scalar::all(1e-1));
    // <---- Kalman filter

    std::cout << "Press 'q' or ESC to exit\n";
    std::cout << "frame,detected,meas_x,meas_y,est_x,est_y\n";

    cv::Mat frame, blur, hsv, mask;
    bool found = false;
    int notFoundCount = 0;
    int frameIdx = 0;
    int64 prevTicks = cv::getTickCount();

    // ----> Main loop
    while (true) {
        if (!cap.read(frame) || frame.empty()) {
            break;
        }

        // Time elapsed since the previous frame [s]
        const int64 ticks = cv::getTickCount();
        double dT = static_cast<double>(ticks - prevTicks) / cv::getTickFrequency();
        prevTicks = ticks;
        if (fileFps > 0.0) {
            dT = 1.0 / fileFps;  // video file: use the nominal frame period
        }

        cv::Mat res = frame.clone();

        // ----> PREDICT
        if (found) {
            kf.transitionMatrix.at<float>(0, 2) = static_cast<float>(dT);
            kf.transitionMatrix.at<float>(1, 3) = static_cast<float>(dT);

            state = kf.predict();

            cv::Rect predRect;
            predRect.width = cvRound(state.at<float>(4));
            predRect.height = cvRound(state.at<float>(5));
            predRect.x = cvRound(state.at<float>(0) - state.at<float>(4) / 2);
            predRect.y = cvRound(state.at<float>(1) - state.at<float>(5) / 2);

            const cv::Point center(cvRound(state.at<float>(0)), cvRound(state.at<float>(1)));
            cv::circle(res, center, 2, cv::Scalar(0, 0, 255), cv::FILLED);
            cv::rectangle(res, predRect, cv::Scalar(0, 0, 255), 2);
        }
        // <---- PREDICT

        // ----> Color segmentation
        cv::GaussianBlur(frame, blur, cv::Size(5, 5), 3.0, 3.0);
        cv::cvtColor(blur, hsv, cv::COLOR_BGR2HSV);
        // OpenCV stores 8-bit hue as degrees / 2 (range 0-179)
        cv::inRange(hsv, cv::Scalar(MIN_H_DEG / 2, 100, 80),
                    cv::Scalar(MAX_H_DEG / 2, 255, 255), mask);
        cv::erode(mask, mask, cv::Mat(), cv::Point(-1, -1), 2);
        cv::dilate(mask, mask, cv::Mat(), cv::Point(-1, -1), 2);
        // <---- Color segmentation

        // ----> Contour detection and filtering
        std::vector<std::vector<cv::Point>> contours;
        cv::findContours(mask, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);

        std::vector<cv::Rect> ballsBox;
        for (const auto& c : contours) {
            const cv::Rect bBox = cv::boundingRect(c);
            float ratio = static_cast<float>(bBox.width) / static_cast<float>(bBox.height);
            if (ratio > 1.0f) {
                ratio = 1.0f / ratio;
            }
            // Keep blobs that are almost square AND big enough
            if (ratio > MIN_SQUARENESS && bBox.area() >= MIN_BLOB_AREA) {
                ballsBox.push_back(bBox);
                cv::rectangle(res, bBox, cv::Scalar(0, 255, 0), 2);
            }
        }
        // <---- Contour detection and filtering

        // ----> CORRECT
        if (ballsBox.empty()) {
            if (found && ++notFoundCount >= MAX_LOST_FRAMES) {
                found = false;  // track lost: wait for a new detection
            }
        } else {
            notFoundCount = 0;

            // Use the largest blob as the measurement
            const cv::Rect& best = *std::max_element(
                ballsBox.begin(), ballsBox.end(),
                [](const cv::Rect& a, const cv::Rect& b) { return a.area() < b.area(); });

            meas.at<float>(0) = best.x + best.width / 2.0f;
            meas.at<float>(1) = best.y + best.height / 2.0f;
            meas.at<float>(2) = static_cast<float>(best.width);
            meas.at<float>(3) = static_cast<float>(best.height);

            if (!found) {
                // First detection: initialize the state from the measurement
                state.at<float>(0) = meas.at<float>(0);
                state.at<float>(1) = meas.at<float>(1);
                state.at<float>(2) = 0.0f;
                state.at<float>(3) = 0.0f;
                state.at<float>(4) = meas.at<float>(2);
                state.at<float>(5) = meas.at<float>(3);
                kf.statePost = state.clone();

                // Initial uncertainty: position and size are known, velocity is not
                kf.errorCovPost = cv::Mat::zeros(stateSize, stateSize, type);
                kf.errorCovPost.at<float>(0, 0) = 1.0f;
                kf.errorCovPost.at<float>(1, 1) = 1.0f;
                kf.errorCovPost.at<float>(2, 2) = 1e4f;
                kf.errorCovPost.at<float>(3, 3) = 1e4f;
                kf.errorCovPost.at<float>(4, 4) = 1.0f;
                kf.errorCovPost.at<float>(5, 5) = 1.0f;

                found = true;
            } else {
                kf.correct(meas);
            }
        }
        // <---- CORRECT

        // Per-frame log (CSV): useful to plot the tracking result
        const bool detected = !ballsBox.empty();
        std::printf("%d,%d,%.1f,%.1f,%.1f,%.1f\n", frameIdx, detected ? 1 : 0,
                    detected ? meas.at<float>(0) : -1.0f, detected ? meas.at<float>(1) : -1.0f,
                    found ? kf.statePost.at<float>(0) : -1.0f,
                    found ? kf.statePost.at<float>(1) : -1.0f);

        cv::imshow("Threshold", mask);
        cv::imshow("Tracking", res);

        const int key = cv::waitKey(1) & 0xFF;
        if (key == 'q' || key == 'Q' || key == 27) {
            break;
        }
        ++frameIdx;
    }
    // <---- Main loop

    return EXIT_SUCCESS;
}

To build it, save it as ball_tracker.cpp next to this CMakeLists.txt:

cmake_minimum_required(VERSION 3.16)
project(ball_tracker LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

find_package(OpenCV REQUIRED COMPONENTS core imgproc highgui videoio video)

add_executable(ball_tracker ball_tracker.cpp)
target_link_libraries(ball_tracker PRIVATE ${OpenCV_LIBS})
cmake -S . -B build -DCMAKE_BUILD_TYPE=Release
cmake --build build
./build/ball_tracker          # webcam 0
./build/ball_tracker my_video.mp4

The red rectangle is the prediction of the Kalman filter, the green rectangle is the detection. While the ball moves in a straight line the two overlap; when the ball is behind the obstacle, only the red one is left, and it keeps moving.

The Python version

The same program in Python, with the same parameters and logic. The --no-gui option disables the windows, which is useful to run it on a headless machine and just collect the CSV output.

#!/usr/bin/env python3
"""Ball tracker: HSV color segmentation + Kalman filter (OpenCV 4.x / 5.x).
Usage: python3 ball_tracker.py [camera_index | video_file] [--no-gui]"""
import sys
import time

import cv2
import numpy as np

MIN_H_DEG, MAX_H_DEG = 200, 300  # hue range of the ball, in degrees (0-360)
MIN_BLOB_AREA = 400              # [px^2]
MIN_SQUARENESS = 0.75            # short side / long side of the bounding box
MAX_LOST_FRAMES = 30             # frames without a detection before reset


def make_kalman():
    kf = cv2.KalmanFilter(6, 4, 0, cv2.CV_32F)  # state [x,y,vx,vy,w,h], meas [x,y,w,h]
    kf.transitionMatrix = np.eye(6, dtype=np.float32)
    H = np.zeros((4, 6), np.float32)
    H[0, 0] = H[1, 1] = H[2, 4] = H[3, 5] = 1.0
    kf.measurementMatrix = H
    kf.processNoiseCov = np.diag([1e-2, 1e-2, 5.0, 5.0, 1e-2, 1e-2]).astype(np.float32)
    kf.measurementNoiseCov = np.eye(4, dtype=np.float32) * 1e-1
    return kf


def detect_balls(frame):
    blur = cv2.GaussianBlur(frame, (5, 5), 3.0)
    hsv = cv2.cvtColor(blur, cv2.COLOR_BGR2HSV)
    mask = cv2.inRange(hsv, (MIN_H_DEG // 2, 100, 80), (MAX_H_DEG // 2, 255, 255))
    mask = cv2.erode(mask, None, iterations=2)
    mask = cv2.dilate(mask, None, iterations=2)
    contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    boxes = []
    for c in contours:
        x, y, w, h = cv2.boundingRect(c)
        ratio = min(w, h) / max(w, h)
        if ratio > MIN_SQUARENESS and w * h >= MIN_BLOB_AREA:
            boxes.append((x, y, w, h))
    return boxes, mask


def main():
    args = [a for a in sys.argv[1:] if not a.startswith('--')]
    gui = '--no-gui' not in sys.argv
    src = args[0] if args else '0'
    is_file = not src.isdigit()
    cap = cv2.VideoCapture(src if is_file else int(src))
    if not cap.isOpened():
        sys.exit(f"Cannot open video source '{src}'")
    file_fps = cap.get(cv2.CAP_PROP_FPS) if is_file else 0.0

    kf = make_kalman()
    found, not_found, frame_idx = False, 0, 0
    prev_t = time.perf_counter()
    print('frame,detected,meas_x,meas_y,est_x,est_y')

    while True:
        ok, frame = cap.read()
        if not ok:
            break
        now = time.perf_counter()
        dT = 1.0 / file_fps if file_fps > 0 else now - prev_t
        prev_t = now
        res = frame.copy()

        if found:  # PREDICT
            kf.transitionMatrix[0, 2] = dT
            kf.transitionMatrix[1, 3] = dT
            x, y, _, _, w, h = kf.predict().ravel()
            cv2.rectangle(res, (int(x - w / 2), int(y - h / 2)),
                          (int(x + w / 2), int(y + h / 2)), (0, 0, 255), 2)

        boxes, mask = detect_balls(frame)
        for (bx, by, bw, bh) in boxes:
            cv2.rectangle(res, (bx, by), (bx + bw, by + bh), (0, 255, 0), 2)

        meas = None
        if not boxes:
            if found:
                not_found += 1
                if not_found >= MAX_LOST_FRAMES:
                    found = False
        else:  # CORRECT
            not_found = 0
            bx, by, bw, bh = max(boxes, key=lambda b: b[2] * b[3])
            meas = np.array([[bx + bw / 2], [by + bh / 2], [bw], [bh]], np.float32)
            if not found:
                kf.statePost = np.array([[meas[0, 0]], [meas[1, 0]], [0], [0],
                                         [meas[2, 0]], [meas[3, 0]]], np.float32)
                kf.errorCovPost = np.diag([1, 1, 1e4, 1e4, 1, 1]).astype(np.float32)
                found = True
            else:
                kf.correct(meas)

        est = kf.statePost.ravel() if found else [-1, -1]
        m = meas.ravel() if meas is not None else [-1, -1]
        print(f'{frame_idx},{int(meas is not None)},{m[0]:.1f},{m[1]:.1f},{est[0]:.1f},{est[1]:.1f}')

        if gui:
            cv2.imshow('Threshold', mask)
            cv2.imshow('Tracking', res)
            if cv2.waitKey(1) & 0xFF in (ord('q'), ord('Q'), 27):
                break
        frame_idx += 1


if __name__ == '__main__':
    main()

What I tested

I did not have the original table, ball and bottle anymore, so I tested the code on a synthetic video generated with OpenCV: a 640×480, 30 FPS, 7 seconds clip with a blue ball moving at constant velocity (240 px/s horizontally, 60 px/s vertically), bouncing on the image borders, a brown vertical bar acting as the “bottle”, a green square as a distractor, and some Gaussian noise added to every frame. Since the video is synthetic, the true position of the ball is known at every frame, and the estimate can be compared to it.

  • The C++ program was compiled with GCC and CMake against OpenCV 4.6.0 (the Ubuntu package) and run on the synthetic video under a virtual X display, so the imshow windows were really created.
  • The Python program was run with OpenCV 5.0.0 on the same video, both with and without GUI.
  • The two programs printed identical CSV output, frame by frame.
  • I did not test the C++ code against OpenCV 5, nor with a real webcam. The C++ API used here (cv::KalmanFilter, cv::findContours, cv::inRange, cv::VideoCapture) is unchanged in OpenCV 5, but untested is untested.
Two frames of the synthetic test video: on the left the blue ball with overlapping green detection and red prediction boxes; on the right the ball hidden behind the brown bar, with only the red predicted box drawn over the bar
Left: the ball is detected, and the green detection box hides the red prediction box because they overlap. Right: the ball is completely behind the occluder and only the Kalman prediction is left.
Plot of the ball horizontal position over 210 frames: true position, color measurements and Kalman estimate, with three gray bands marking the frames without detection, and a lower panel with the estimate error
Horizontal position of the ball (top) and distance between the estimate and the true center (bottom). Gray bands: frames with no accepted detection.

The results, which you can read on the plot:

  • While the ball is visible, the estimate stays within about one pixel of the true center.
  • Each occlusion lasts 14 frames without an accepted detection: 6 frames with the ball completely hidden, plus the frames where it is only partially visible and is rejected by the squareness test. During those frames the estimate keeps moving through the obstacle, and the error grows to about 12.6 px at the end of the gap, with a ball 45 px wide: the red box is still on the ball when it comes out.
  • The error during the occlusion is not zero because the last two accepted measurements, taken while the ball was starting to slide behind the obstacle, were already slightly cut. They pulled the estimated velocity down from 240 to about 218 px/s, and the box width from 45 to 42 px. Partial occlusions are the real enemy of this kind of tracker, more than total ones.
  • At each bounce the error jumps to about 10 px for a few frames: the constant velocity model keeps the ball going in the old direction until the measurements pull it back. This is the price of the linear model described above.

Replacing the color detector with an AI detector

The weak point of this tracker is not the Kalman filter, it is the detector. HSV segmentation works on a table with a blue ball and a uniform background, but it breaks easily: a change of lighting shifts the hue, any other blue object in the scene becomes a candidate, and a ball of a different color needs new thresholds. A neural network detector does not look for a color, it looks for an object class. The YOLO models trained on the COCO dataset, for example, already know a sports ball class, so they find a ball whatever its color, under different lighting and against a cluttered background.

The good news is that the two halves of this tutorial are independent. The Kalman filter does not care where its measurements come from: it only needs, at each frame, a measurement [zx, zy, zw, zh] or the information that there is none. So replacing the color detector with an AI detector means replacing only the function that returns the detections, detect_balls() in the Python version or the HSV and contour block in the C++ version. The model, the matrices and the predict / correct cycle stay exactly as they are, and so does the occlusion handling: frames without a detection still run only predict().

My YOLO with OpenCV and CUDA tutorial shows how to run such a detector with the OpenCV DNN module on an NVIDIA® GPU. To plug it into this tracker:

  1. Filter by class and confidence. Keep only the detections of the class you want to track (for example sports ball) with a confidence above a threshold, and convert each box to its center and size, which become zx, zy, zw, zh.
  2. Choose one detection. With a single object, the simplest choice is the detection with the highest confidence. A more robust choice is the detection closest to the position the filter has just predicted, ignoring detections too far from it (gating): this rejects false positives that a single wrong frame would otherwise feed into the filter.
  3. Retune R. The measurement noise of a neural detector is different from that of the HSV blobs: its boxes are usually more stable on the object, but they can jitter in size from frame to frame. Start from the current values and adjust the measurement noise covariance by looking at how much the estimated box shakes.
  4. Handle a slower detector. A neural network may run slower than the camera, especially on an embedded board. This is where the Kalman filter helps again: run predict() on every frame, and call correct() only on the frames where a new detection is available. Use the real time between frames for dT, as the code already does, so the motion model stays correct.

A sketch of the change in the Python version, where ai_detect() stands for your neural detector and returns a list of (x, y, w, h, confidence, class_name) tuples with x, y at the top-left corner of the box:

def detect_balls_ai(frame, predicted_center=None, min_conf=0.5, max_dist=100.0):
    """Same output as detect_balls(): a list with at most one box (x, y, w, h), and no mask."""
    boxes = [(x, y, w, h, conf) for (x, y, w, h, conf, cls) in ai_detect(frame)
             if cls == "sports ball" and conf >= min_conf]
    if not boxes:
        return [], None
    if predicted_center is None:  # no track yet: take the most confident detection
        best = max(boxes, key=lambda b: b[4])
    else:  # tracking: take the detection closest to the prediction (gating)
        px, py = predicted_center
        def dist(b):
            return ((b[0] + b[2] / 2 - px) ** 2 + (b[1] + b[3] / 2 - py) ** 2) ** 0.5
        best = min(boxes, key=dist)
        if dist(best) > max_dist:
            return [], None
    return [best[:4]], None

It returns the same (boxes, mask) pair as detect_balls(), so the rest of the loop does not change. I checked the selection logic with a fake detector, but it is a sketch, not tested with a real model: ai_detect() depends on the detector and the model you choose.

Tracking many objects at the same time is the natural next step: one Kalman filter for each object, plus a data association step that decides which detection belongs to which track, usually by comparing the predicted boxes with the detected ones. This is exactly the idea behind well-known trackers such as SORT, which combines a detector, a constant velocity Kalman filter like the one in this tutorial, and the Hungarian algorithm for the association.

Conclusions

The detection part of this tracker is deliberately basic, and today you would probably replace it with a neural network detector, as explained above. The Kalman filter part, instead, has not aged at all: the same predict / correct cycle, with a constant velocity model, is still at the core of many multi-object trackers used on top of modern detectors. Understanding it on a single blue ball is the easiest way to understand it everywhere.

If you have questions or suggestions, feel free to contact me.