[Tutorial OpenCV] “Ball Tracker” using Kalman filter

A few times ago I published on YouTube a video about a “simple” software capable to identify a blue ball moving on a table and to track its movements, estimating its position even under occlusions. The video, available below, has got great success and has been viewed more than 5000 times. A lot of people requested me to write a tutorial or to get the source code… the source code has been distributed all around the world, and now it’s time to write the tutorial.

 This is the source code:

/******************************************
 * OpenCV Tutorial: Ball Tracking using   *
 * Kalman Filter                          *
 ******************************************/

// Module "core"
#include <opencv2/core/core.hpp>

// Module "highgui"
#include <opencv2/highgui/highgui.hpp>

// Module "imgproc"
#include <opencv2/imgproc/imgproc.hpp>

// Module "video"
#include <opencv2/video/video.hpp>

// Output
#include <iostream>

// Vector
#include <vector>

using namespace std;

// ----> Color to be tracked
#define MIN_H_BLUE 200
#define MAX_H_BLUE 300
// <---- Color to be tracked


int main()
{
    // Camera frame
    cv::Mat frame;

    // >>>> Kalman Filter
    int stateSize = 6;
    int measSize = 4;
    int contrSize = 0;

    unsigned int type = CV_32F;
    cv::KalmanFilter kf(stateSize, measSize, contrSize, type);

    cv::Mat state(stateSize, 1, type);  // [x,y,v_x,v_y,w,h]
    cv::Mat meas(measSize, 1, type);    // [z_x,z_y,z_w,z_h]
    //cv::Mat procNoise(stateSize, 1, type)
    // [E_x,E_y,E_v_x,E_v_y,E_w,E_h]

    // Transition State Matrix A
    // Note: set dT at each processing step!
    // [ 1 0 dT 0  0 0 ]
    // [ 0 1 0  dT 0 0 ]
    // [ 0 0 1  0  0 0 ]
    // [ 0 0 0  1  0 0 ]
    // [ 0 0 0  0  1 0 ]
    // [ 0 0 0  0  0 1 ]
    cv::setIdentity(kf.transitionMatrix);

    // Measure Matrix H
    // [ 1 0 0 0 0 0 ]
    // [ 0 1 0 0 0 0 ]
    // [ 0 0 0 0 1 0 ]
    // [ 0 0 0 0 0 1 ]
    kf.measurementMatrix = cv::Mat::zeros(measSize, stateSize, type);
    kf.measurementMatrix.at<float>(0) = 1.0f;
    kf.measurementMatrix.at<float>(7) = 1.0f;
    kf.measurementMatrix.at<float>(16) = 1.0f;
    kf.measurementMatrix.at<float>(23) = 1.0f;

    // Process Noise Covariance Matrix Q
    // [ Ex   0   0     0     0    0  ]
    // [ 0    Ey  0     0     0    0  ]
    // [ 0    0   Ev_x  0     0    0  ]
    // [ 0    0   0     Ev_y  0    0  ]
    // [ 0    0   0     0     Ew   0  ]
    // [ 0    0   0     0     0    Eh ]
    //cv::setIdentity(kf.processNoiseCov, cv::Scalar(1e-2));
    kf.processNoiseCov.at<float>(0) = 1e-2;
    kf.processNoiseCov.at<float>(7) = 1e-2;
    kf.processNoiseCov.at<float>(14) = 5.0f;
    kf.processNoiseCov.at<float>(21) = 5.0f;
    kf.processNoiseCov.at<float>(28) = 1e-2;
    kf.processNoiseCov.at<float>(35) = 1e-2;

    // Measures Noise Covariance Matrix R
    cv::setIdentity(kf.measurementNoiseCov, cv::Scalar(1e-1));
    // <<<< Kalman Filter

    // Camera Index
    int idx = 0;

    // Camera Capture
    cv::VideoCapture cap;

    // ----> Camera Settings
    if (!cap.open(idx))
    {
        cout << "Webcam not connected.\n" << "Please verify\n";
        return EXIT_FAILURE;
    }

    cap.set(CV_CAP_PROP_FRAME_WIDTH, 1024);
    cap.set(CV_CAP_PROP_FRAME_HEIGHT, 768);
    // <---- Camera Settings

    cout << "\nHit 'q' to exit...\n";

    char ch = 0;

    double ticks = 0;
    bool found = false;

    int notFoundCount = 0;

    // ----> Main loop
    while (ch != 'q' || ch != 'Q')
    {
        double precTick = ticks;
        ticks = (double) cv::getTickCount();

        double dT = (ticks - precTick) / cv::getTickFrequency(); //seconds

        // Frame acquisition
        cap >> frame;

        cv::Mat res;
        frame.copyTo( res );

        if (found)
        {
            // >>>> Matrix A
            kf.transitionMatrix.at<float>(2) = dT;
            kf.transitionMatrix.at<float>(9) = dT;
            // <<<< Matrix A

            cout << "dT:" << endl << dT << endl;

            state = kf.predict();
            cout << "State post:" << endl << state << endl;

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

            cv::Point center;
            center.x = state.at<float>(0);
            center.y = state.at<float>(1);
            cv::circle(res, center, 2, CV_RGB(255,0,0), -1);

            cv::rectangle(res, predRect, CV_RGB(255,0,0), 2);
        }

        // ----> Noise smoothing
        cv::Mat blur;
        cv::GaussianBlur(frame, blur, cv::Size(5, 5), 3.0, 3.0);
        // <---- Noise smoothing

        // ----> HSV conversion
        cv::Mat frmHsv;
        cv::cvtColor(blur, frmHsv, CV_BGR2HSV);
        // <---- HSV conversion

        // ----> Color Thresholding
        // Note: change parameters for different colors
        cv::Mat rangeRes = cv::Mat::zeros(frame.size(), CV_8UC1);
        cv::inRange(frmHsv, cv::Scalar(MIN_H_BLUE / 2, 100, 80),
                    cv::Scalar(MAX_H_BLUE / 2, 255, 255), rangeRes);
        // <---- Color Thresholding

        // ----> Improving the result
        cv::erode(rangeRes, rangeRes, cv::Mat(), cv::Point(-1, -1), 2);
        cv::dilate(rangeRes, rangeRes, cv::Mat(), cv::Point(-1, -1), 2);
        // <---- Improving the result

        // Thresholding viewing
        cv::imshow("Threshold", rangeRes);

        // ----> Contours detection
        vector<vector<cv::Point> > contours;
        cv::findContours(rangeRes, contours, CV_RETR_EXTERNAL,
                         CV_CHAIN_APPROX_NONE);
        // <---- Contours detection

        // ----> Filtering
        vector<vector<cv::Point> > balls;
        vector<cv::Rect> ballsBox;
        for (size_t i = 0; i < contours.size(); i++)
        {
            cv::Rect bBox;
            bBox = cv::boundingRect(contours[i]);

            float ratio = (float) bBox.width / (float) bBox.height;
            if (ratio > 1.0f)
                ratio = 1.0f / ratio;

            // Searching for a bBox almost square
            if (ratio > 0.75 || bBox.area() >= 400)
            {
                balls.push_back(contours[i]);
                ballsBox.push_back(bBox);
            }
        }
        // <---- Filtering

        cout << "Balls found:" << ballsBox.size() << endl;

        // ----> Detection result
        for (size_t i = 0; i < balls.size(); i++)
        {
            cv::drawContours(res, balls, i, CV_RGB(20,150,20), 1);
            cv::rectangle(res, ballsBox[i], CV_RGB(0,255,0), 2);

            cv::Point center;
            center.x = ballsBox[i].x + ballsBox[i].width / 2;
            center.y = ballsBox[i].y + ballsBox[i].height / 2;
            cv::circle(res, center, 2, CV_RGB(20,150,20), -1);

            stringstream sstr;
            sstr << "(" << center.x << "," << center.y << ")";
            cv::putText(res, sstr.str(),
                        cv::Point(center.x + 3, center.y - 3),
                        cv::FONT_HERSHEY_SIMPLEX, 0.5, CV_RGB(20,150,20), 2);
        }
        // <---- Detection result

        // ----> Kalman Update
        if (balls.size() == 0)
        {
            notFoundCount++;
            cout << "notFoundCount:" << notFoundCount << endl;
            if( notFoundCount >= 100 )
            {
                found = false;
            }
            /*else
                kf.statePost = state;*/
        }
        else
        {
            notFoundCount = 0;

            meas.at<float>(0) = ballsBox[0].x + ballsBox[0].width / 2;
            meas.at<float>(1) = ballsBox[0].y + ballsBox[0].height / 2;
            meas.at<float>(2) = (float)ballsBox[0].width;
            meas.at<float>(3) = (float)ballsBox[0].height;

            if (!found) // First detection!
            {
                // >>>> Initialization
                kf.errorCovPre.at<float>(0) = 1; // px
                kf.errorCovPre.at<float>(7) = 1; // px
                kf.errorCovPre.at<float>(14) = 1;
                kf.errorCovPre.at<float>(21) = 1;
                kf.errorCovPre.at<float>(28) = 1; // px
                kf.errorCovPre.at<float>(35) = 1; // px

                state.at<float>(0) = meas.at<float>(0);
                state.at<float>(1) = meas.at<float>(1);
                state.at<float>(2) = 0;
                state.at<float>(3) = 0;
                state.at<float>(4) = meas.at<float>(2);
                state.at<float>(5) = meas.at<float>(3);
                // <<<< Initialization

                kf.statePost = state;
                
                found = true;
            }
            else
                kf.correct(meas); // Kalman Correction

            cout << "Measure matrix:" << endl << meas << endl;
        }
        // <---- Kalman Update

        // Final result
        cv::imshow("Tracking", res);

        // User key
        ch = cv::waitKey(1);
    }
    // <---- Main loop

    return EXIT_SUCCESS;
}

The software is tuned to identify a blue ball. You can modify the color by simply changing the values of the HUE “MIN_H_BLUE” and “MAX_H_BLUE” at the very beginning of the code.

Even if the code is really short, the theory behind it is really complicated and requires high-level mathematical knowledge. The tracking uses what is known in the literature as the “Kalman Filter“, it is an “asymptotic state estimator”, a mathematical tool that allows estimating the position of the tracked object using the cinematic model of the object and its “history”. Wikipedia has a good page about the Kalman filter, the explanation is really well done, even if it is not really easy to understand it if you do not have enough mathematical capabilities. We can simply say that the Kalman filter works in two steps: PREDICTION and UPDATE. The PREDICTION step allows predicting the position of the object knowing its history, the speed of its movements, and knowing the equations that identify its movements. The PREDICTION is corrected every time a measure of the state of the object is available, this correction makes the UPDATE step. Unfortunately, the measure is not perfect, each measure has errors, so PREDICTION and UPDATE are weighted using information about measure and prediction errors. After this attempt to describe the Kalman Filter using simple words, we can move to the description of the code. First of all, let us define our system, which is the information about the ball at each instant “t”.

The vector [x,y,v_x,v_y,w,h] (line45) defines the state:

  • x, y: centroid of the ball
  • v_x, v_y: speed of the centroid (pixel/sec)
  • w, h: size of the bounding box

Now we must define the “measure vector” [z_x,z_y,z_w,z_h] (line 46):

  • z_x, z_y: centroid of the identified ball
  • z_w, z_h: size of the identified ball

A note: the “measure vector” is used during the UPDATE phase only if the ball has been detected in the current frame, otherwise (OCCLUSION) we make only the PREDICTION step.

From line 50 to line 88 we initialize the matrices that realize the two phases of the Kalman Filter. A matrix makes the “linear model” of the movements of the ball. For this example has been made the strong assumption that the ball moves in a linear way, which unfortunately is not true for most of the more complicated dynamic systems. H makes the measure. Q matrix is the matrix related to the “Process covariance“, a difficult name to define the noise of the system, that is the errors about the estimation of the state of the ball at each instant.

Now its time to realize the tracking process in the “while” cycle. The variable “dT” takes the measure of the time elapsed from one phase to the next, the time is essential for the state estimation. If the ball has been detected before (found is TRUE) the tracking is active, from line 132 to line 156 we realize the “PREDICTION” phase, thanks to the OpenCV function “predict”. From line 158 to line 208 the “classical” detection algorithm is applied: blurring, HSV conversion, morphological filtering, thresholding, and dimensional filtering.

From line 231 to line 277 we realize the “UPDATE” of the state of the ball, using the information extracted with the detection, particularly from line 162 to line 266 the initial position and size of the ball are initialized with the first measure (found is FALSE). The variable “found” is used to indicate that the ball has been previously detected and the tracking is active. If we lose the ball for more than 10 consecutive frames “found” is set to FALSE and the tracking process is stopped and reinitialized if we detect the ball again next.

From line 212 to line 229 we show the result of the tracking. The green rectangle identifies the bounding box of the ball detected during the measuring step. The red rectangle shows the “estimated state” of the ball, the result of the prediction step of the Kalman Filter. It is really interesting to note how the estimated state overlaps the measured state meanwhile the ball moves linearly, but overall it is interesting to note that the estimation of the state stays valid even if the ball is behind the bottle.

The tutorial is over.

OpenCV has a good powerful mathematical tool, not really easy to be used, such as the Kalman Filter. I hope that this short guide can help you to use it in your “tracking project”. Please feel free to use my email address (developer@myzhar.com) to contact me if you have any doubt.

The code is available also on Github:

https://github.com/Myzhar/simple-opencv-kalman-tracker

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.