1 /*M///////////////////////////////////////////////////////////////////////////////////////
3 // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
5 // By downloading, copying, installing or using the software you agree to this license.
6 // If you do not agree to this license, do not download, install,
7 // copy or use the software.
11 // For Open Source Computer Vision Library
13 // Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
14 // Copyright (C) 2009, Willow Garage Inc., all rights reserved.
15 // Third party copyrights are property of their respective owners.
17 // Redistribution and use in source and binary forms, with or without modification,
18 // are permitted provided that the following conditions are met:
20 // * Redistribution's of source code must retain the above copyright notice,
21 // this list of conditions and the following disclaimer.
23 // * Redistribution's in binary form must reproduce the above copyright notice,
24 // this list of conditions and the following disclaimer in the documentation
25 // and/or other materials provided with the distribution.
27 // * The name of the copyright holders may not be used to endorse or promote products
28 // derived from this software without specific prior written permission.
30 // This software is provided by the copyright holders and contributors "as is" and
31 // any express or implied warranties, including, but not limited to, the implied
32 // warranties of merchantability and fitness for a particular purpose are disclaimed.
33 // In no event shall the Intel Corporation or contributors be liable for any direct,
34 // indirect, incidental, special, exemplary, or consequential damages
35 // (including, but not limited to, procurement of substitute goods or services;
36 // loss of use, data, or profits; or business interruption) however caused
37 // and on any theory of liability, whether in contract, strict liability,
38 // or tort (including negligence or otherwise) arising in any way out of
39 // the use of this software, even if advised of the possibility of such damage.
43 #include "test_precomp.hpp"
44 #include "opencv2/video/tracking.hpp"
45 #include "opencv2/video/tracking_c.h"
56 class CV_OptFlowTest : public cvtest::BaseTest
64 bool runDense(const Point& shift = Point(3, 0));
68 CV_OptFlowTest::CV_OptFlowTest() {}
69 CV_OptFlowTest::~CV_OptFlowTest() {}
72 Mat copnvert2flow(const Mat& velx, const Mat& vely)
74 Mat flow(velx.size(), CV_32FC2);
75 for(int y = 0 ; y < flow.rows; ++y)
76 for(int x = 0 ; x < flow.cols; ++x)
77 flow.at<Point2f>(y, x) = Point2f(velx.at<float>(y, x), vely.at<float>(y, x));
81 void calcOpticalFlowLK( const Mat& prev, const Mat& curr, Size winSize, Mat& flow )
83 Mat velx(prev.size(), CV_32F), vely(prev.size(), CV_32F);
84 CvMat cvvelx = velx; CvMat cvvely = vely;
85 CvMat cvprev = prev; CvMat cvcurr = curr;
86 cvCalcOpticalFlowLK( &cvprev, &cvcurr, winSize, &cvvelx, &cvvely );
87 flow = copnvert2flow(velx, vely);
90 void calcOpticalFlowBM( const Mat& prev, const Mat& curr, Size bSize, Size shiftSize, Size maxRange, int usePrevious, Mat& flow )
92 Size sz((curr.cols - bSize.width + shiftSize.width)/shiftSize.width, (curr.rows - bSize.height + shiftSize.height)/shiftSize.height);
93 Mat velx(sz, CV_32F), vely(sz, CV_32F);
95 CvMat cvvelx = velx; CvMat cvvely = vely;
96 CvMat cvprev = prev; CvMat cvcurr = curr;
97 cvCalcOpticalFlowBM( &cvprev, &cvcurr, bSize, shiftSize, maxRange, usePrevious, &cvvelx, &cvvely);
98 flow = copnvert2flow(velx, vely);
101 void calcOpticalFlowHS( const Mat& prev, const Mat& curr, int usePrevious, double lambda, TermCriteria criteria, Mat& flow)
103 Mat velx(prev.size(), CV_32F), vely(prev.size(), CV_32F);
104 CvMat cvvelx = velx; CvMat cvvely = vely;
105 CvMat cvprev = prev; CvMat cvcurr = curr;
106 cvCalcOpticalFlowHS( &cvprev, &cvcurr, usePrevious, &cvvelx, &cvvely, lambda, criteria );
107 flow = copnvert2flow(velx, vely);
110 void calcAffineFlowPyrLK( const Mat& prev, const Mat& curr,
111 const vector<Point2f>& prev_features, vector<Point2f>& curr_features,
112 vector<uchar>& status, vector<float>& track_error, vector<float>& matrices,
113 TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS,30, 0.01),
114 Size win_size = Size(15, 15), int level = 3, int flags = 0)
119 size_t count = prev_features.size();
120 curr_features.resize(count);
121 status.resize(count);
122 track_error.resize(count);
123 matrices.resize(count * 6);
125 cvCalcAffineFlowPyrLK( &cvprev, &cvcurr, 0, 0,
126 (const CvPoint2D32f*)&prev_features[0], (CvPoint2D32f*)&curr_features[0], &matrices[0],
127 (int)count, win_size, level, (char*)&status[0], &track_error[0], criteria, flags );
130 double showFlowAndCalcError(const string& name, const Mat& gray, const Mat& flow,
131 const Rect& where, const Point& d,
132 bool showImages = false, bool writeError = false)
139 resize(gray, tmp, gray.size() * mult, 0, 0, INTER_NEAREST);
140 cvtColor(tmp, cflow, CV_GRAY2BGR);
142 const float m2 = 0.3f;
143 const float minVel = 0.1f;
145 for(int y = 0; y < flow.rows; ++y)
146 for(int x = 0; x < flow.cols; ++x)
148 Point2f f = flow.at<Point2f>(y, x);
150 if (f.x * f.x + f.y * f.y > minVel * minVel)
152 Point p1 = Point(x, y) * mult;
153 Point p2 = Point(cvRound((x + f.x*m2) * mult), cvRound((y + f.y*m2) * mult));
155 line(cflow, p1, p2, CV_RGB(0, 255, 0));
156 circle(cflow, Point(x, y) * mult, 2, CV_RGB(255, 0, 0));
160 rectangle(cflow, (where.tl() + d) * mult, (where.br() + d - Point(1,1)) * mult, CV_RGB(0, 0, 255));
161 namedWindow(name, 1); imshow(name, cflow);
164 double angle = atan2((float)d.y, (float)d.x);
168 Mat inner = flow(where);
169 for(int y = 0; y < inner.rows; ++y)
170 for(int x = 0; x < inner.cols; ++x)
172 const Point2f f = inner.at<Point2f>(y, x);
174 if (f.x == 0 && f.y == 0)
179 double a = atan2(f.y, f.x);
180 error += fabs(angle - a);
182 double res = all ? numeric_limits<double>::max() : error / (inner.cols * inner.rows);
185 cout << "Error " + name << " = " << res << endl;
191 Mat generateImage(const Size& sz, bool doBlur = true)
196 for(int y = 0; y < mat.rows; ++y)
197 for(int x = 0; x < mat.cols; ++x)
198 mat.at<uchar>(y, x) = (uchar)rng;
200 blur(mat, mat, Size(3, 3));
204 Mat generateSample(const Size& sz)
208 Point sc(smpl.cols/2, smpl.rows/2);
209 rectangle(smpl, Point(0,0), sc - Point(1,1), Scalar(255), CV_FILLED);
210 rectangle(smpl, sc, Point(smpl.cols, smpl.rows), Scalar(255), CV_FILLED);
214 bool CV_OptFlowTest::runDense(const Point& d)
216 Size matSize(40, 40);
219 Mat smpl = generateSample(movSize);
220 Mat prev = generateImage(matSize);
221 Mat curr = prev.clone();
223 Rect rect(Point(prev.cols/2, prev.rows/2) - Point(movSize.width/2, movSize.height/2), movSize);
225 Mat flowLK, flowBM, flowHS, flowFB, flowFB_G, flowBM_received, m1;
227 m1 = prev(rect); smpl.copyTo(m1);
228 m1 = curr(Rect(rect.tl() + d, rect.br() + d)); smpl.copyTo(m1);
230 calcOpticalFlowLK( prev, curr, Size(15, 15), flowLK);
231 calcOpticalFlowBM( prev, curr, Size(15, 15), Size(1, 1), Size(15, 15), 0, flowBM_received);
232 calcOpticalFlowHS( prev, curr, 0, 5, TermCriteria(TermCriteria::MAX_ITER, 400, 0), flowHS);
233 calcOpticalFlowFarneback( prev, curr, flowFB, 0.5, 3, std::max(d.x, d.y) + 10, 100, 6, 2, 0);
234 calcOpticalFlowFarneback( prev, curr, flowFB_G, 0.5, 3, std::max(d.x, d.y) + 10, 100, 6, 2, OPTFLOW_FARNEBACK_GAUSSIAN);
236 flowBM.create(prev.size(), CV_32FC2);
238 Point origin((flowBM.cols - flowBM_received.cols)/2, (flowBM.rows - flowBM_received.rows)/2);
239 Mat wcp = flowBM(Rect(origin, flowBM_received.size()));
240 flowBM_received.copyTo(wcp);
242 double errorLK = showFlowAndCalcError("LK", prev, flowLK, rect, d);
243 double errorBM = showFlowAndCalcError("BM", prev, flowBM, rect, d);
244 double errorFB = showFlowAndCalcError("FB", prev, flowFB, rect, d);
245 double errorFBG = showFlowAndCalcError("FBG", prev, flowFB_G, rect, d);
246 double errorHS = showFlowAndCalcError("HS", prev, flowHS, rect, d); (void)errorHS;
249 const double thres = 0.2;
250 if (errorLK > thres || errorBM > thres || errorFB > thres || errorFBG > thres /*|| errorHS > thres */)
252 ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH);
259 bool CV_OptFlowTest::runSparse()
261 Mat prev = imread(string(ts->get_data_path()) + "optflow/rock_1.bmp", 0);
262 Mat next = imread(string(ts->get_data_path()) + "optflow/rock_2.bmp", 0);
264 if (prev.empty() || next.empty())
266 ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
271 cvtColor(prev, cprev, CV_GRAY2BGR);
272 cvtColor(next, cnext, CV_GRAY2BGR);
274 vector<Point2f> prev_pts;
275 vector<Point2f> next_ptsOpt;
276 vector<Point2f> next_ptsAff;
277 vector<uchar> status_Opt;
278 vector<uchar> status_Aff;
280 vector<float> matrices;
282 Size netSize(10, 10);
283 Point2f center = Point(prev.cols/2, prev.rows/2);
285 for(int i = 0 ; i < netSize.width; ++i)
286 for(int j = 0 ; j < netSize.width; ++j)
288 Point2f p(i * float(prev.cols)/netSize.width, j * float(prev.rows)/netSize.height);
289 prev_pts.push_back((p - center) * 0.5f + center);
292 calcOpticalFlowPyrLK( prev, next, prev_pts, next_ptsOpt, status_Opt, error );
293 calcAffineFlowPyrLK ( prev, next, prev_pts, next_ptsAff, status_Aff, error, matrices);
295 const double expected_shift = 25;
296 const double thres = 1;
297 for(size_t i = 0; i < prev_pts.size(); ++i)
299 circle(cprev, prev_pts[i], 2, CV_RGB(255, 0, 0));
303 circle(cnext, next_ptsOpt[i], 2, CV_RGB(0, 0, 255));
304 Point2f shift = prev_pts[i] - next_ptsOpt[i];
306 double n = sqrt(shift.ddot(shift));
307 if (fabs(n - expected_shift) > thres)
309 ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH);
316 circle(cnext, next_ptsAff[i], 4, CV_RGB(0, 255, 0));
317 Point2f shift = prev_pts[i] - next_ptsAff[i];
319 double n = sqrt(shift.ddot(shift));
320 if (fabs(n - expected_shift) > thres)
322 ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH);
329 /*namedWindow("P"); imshow("P", cprev);
330 namedWindow("N"); imshow("N", cnext);
337 void CV_OptFlowTest::run( int /* start_from */)
340 if (!runDense(Point(3, 0)))
343 if (!runDense(Point(0, 3)))
346 //if (!runDense(Point(3, 3))) return; //probably LK works incorrectly in this case.
351 ts->set_failed_test_info(cvtest::TS::OK);
355 TEST(Legacy_OpticalFlow, accuracy) { CV_OptFlowTest test; test.safe_run(); }