A few time 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 potition 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, now it’s the time to write the tutorial.
This is the source code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 |
/****************************************** * 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 such to identify a blue ball. You can modify the color 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 literature as “Kalman Filter“, it is an “asymptotic state estimator”, a mathematical tool that allows to estimate the position of the tracked object using the cinematic model of the object and its “history”. Wikipedia has a good page about Kalman filter, the explaination 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 to predict 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 lets define our system, that 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 a 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 “PRECITION” 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 measure 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:
Pingback: SORT 多目标跟踪算法笔记 - 算法网