Merge pull request #2887 from ilya-lavrenov:ipp_morph_fix
[platform/upstream/opencv.git] / modules / legacy / test / test_optflow.cpp
1 /*M///////////////////////////////////////////////////////////////////////////////////////
2 //
3 //  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
4 //
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.
8 //
9 //
10 //                           License Agreement
11 //                For Open Source Computer Vision Library
12 //
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.
16 //
17 // Redistribution and use in source and binary forms, with or without modification,
18 // are permitted provided that the following conditions are met:
19 //
20 //   * Redistribution's of source code must retain the above copyright notice,
21 //     this list of conditions and the following disclaimer.
22 //
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.
26 //
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.
29 //
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.
40 //
41 //M*/
42
43 #include "test_precomp.hpp"
44 #include "opencv2/video/tracking.hpp"
45 #include "opencv2/video/tracking_c.h"
46
47 #include <string>
48 #include <iostream>
49 #include <fstream>
50 #include <iterator>
51 #include <limits>
52
53 using namespace cv;
54 using namespace std;
55
56 class CV_OptFlowTest : public cvtest::BaseTest
57 {
58 public:
59     CV_OptFlowTest();
60     ~CV_OptFlowTest();
61 protected:
62     void run(int);
63
64     bool runDense(const Point& shift = Point(3, 0));
65     bool runSparse();
66 };
67
68 CV_OptFlowTest::CV_OptFlowTest() {}
69 CV_OptFlowTest::~CV_OptFlowTest() {}
70
71
72 Mat copnvert2flow(const Mat& velx, const Mat& vely)
73 {
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));
78     return flow;
79 }
80
81 void calcOpticalFlowLK( const Mat& prev, const Mat& curr, Size winSize, Mat& flow )
82 {
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);
88 }
89
90 void calcOpticalFlowBM( const Mat& prev, const Mat& curr, Size bSize, Size shiftSize, Size maxRange, int usePrevious, Mat& flow )
91 {
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);
94
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);
99 }
100
101 void calcOpticalFlowHS( const Mat& prev, const Mat& curr, int usePrevious, double lambda, TermCriteria criteria, Mat& flow)
102 {
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);
108 }
109
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)
115 {
116     CvMat cvprev = prev;
117     CvMat cvcurr = curr;
118
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);
124
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 );
128 }
129
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)
133 {
134     const int mult = 16;
135
136     if (showImages)
137     {
138         Mat tmp, cflow;
139         resize(gray, tmp, gray.size() * mult, 0, 0, INTER_NEAREST);
140         cvtColor(tmp, cflow, CV_GRAY2BGR);
141
142         const float m2 = 0.3f;
143         const float minVel = 0.1f;
144
145         for(int y = 0; y < flow.rows; ++y)
146             for(int x = 0; x < flow.cols; ++x)
147             {
148                 Point2f f = flow.at<Point2f>(y, x);
149
150                 if (f.x * f.x + f.y * f.y > minVel * minVel)
151                 {
152                     Point p1 = Point(x, y) * mult;
153                     Point p2 = Point(cvRound((x + f.x*m2) * mult), cvRound((y + f.y*m2) * mult));
154
155                     line(cflow, p1, p2, CV_RGB(0, 255, 0));
156                     circle(cflow, Point(x, y) * mult, 2, CV_RGB(255, 0, 0));
157                 }
158             }
159
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);
162     }
163
164     double angle = atan2((float)d.y, (float)d.x);
165     double error = 0;
166
167     bool all = true;
168     Mat inner = flow(where);
169     for(int y = 0; y < inner.rows; ++y)
170         for(int x = 0; x < inner.cols; ++x)
171         {
172             const Point2f f = inner.at<Point2f>(y, x);
173
174             if (f.x == 0 && f.y == 0)
175                 continue;
176
177             all = false;
178
179             double a = atan2(f.y, f.x);
180             error += fabs(angle - a);
181         }
182         double res = all ? numeric_limits<double>::max() : error / (inner.cols * inner.rows);
183
184         if (writeError)
185             cout << "Error " + name << " = " << res << endl;
186
187         return res;
188 }
189
190
191 Mat generateImage(const Size& sz, bool doBlur = true)
192 {
193     RNG rng;
194     Mat mat(sz, CV_8U);
195     mat = Scalar(0);
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;
199     if (doBlur)
200         blur(mat, mat, Size(3, 3));
201     return mat;
202 }
203
204 Mat generateSample(const Size& sz)
205 {
206     Mat smpl(sz, CV_8U);
207     smpl = Scalar(0);
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);
211     return smpl;
212 }
213
214 bool CV_OptFlowTest::runDense(const Point& d)
215 {
216     Size matSize(40, 40);
217     Size movSize(8, 8);
218
219     Mat smpl = generateSample(movSize);
220     Mat prev = generateImage(matSize);
221     Mat curr = prev.clone();
222
223     Rect rect(Point(prev.cols/2, prev.rows/2) - Point(movSize.width/2, movSize.height/2), movSize);
224
225     Mat flowLK, flowBM, flowHS, flowFB, flowFB_G, flowBM_received, m1;
226
227     m1 = prev(rect);                                smpl.copyTo(m1);
228     m1 = curr(Rect(rect.tl() + d, rect.br() + d));  smpl.copyTo(m1);
229
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);
235
236     flowBM.create(prev.size(), CV_32FC2);
237     flowBM = Scalar(0);
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);
241
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;
247     //waitKey();
248
249     const double thres = 0.2;
250     if (errorLK > thres || errorBM > thres || errorFB > thres || errorFBG > thres /*|| errorHS > thres */)
251     {
252         ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH);
253         return false;
254     }
255     return true;
256 }
257
258
259 bool CV_OptFlowTest::runSparse()
260 {
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);
263
264     if (prev.empty() || next.empty())
265     {
266         ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
267         return false;
268     }
269
270     Mat cprev, cnext;
271     cvtColor(prev, cprev, CV_GRAY2BGR);
272     cvtColor(next, cnext, CV_GRAY2BGR);
273
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;
279     vector<float> error;
280     vector<float> matrices;
281
282     Size netSize(10, 10);
283     Point2f center = Point(prev.cols/2, prev.rows/2);
284
285     for(int i = 0 ; i < netSize.width; ++i)
286         for(int j = 0 ; j < netSize.width; ++j)
287         {
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);
290         }
291
292     calcOpticalFlowPyrLK( prev, next, prev_pts, next_ptsOpt, status_Opt, error );
293     calcAffineFlowPyrLK ( prev, next, prev_pts, next_ptsAff, status_Aff, error, matrices);
294
295     const double expected_shift = 25;
296     const double thres = 1;
297     for(size_t i = 0; i < prev_pts.size(); ++i)
298     {
299         circle(cprev, prev_pts[i], 2, CV_RGB(255, 0, 0));
300
301         if (status_Opt[i])
302         {
303             circle(cnext, next_ptsOpt[i], 2, CV_RGB(0, 0, 255));
304             Point2f shift = prev_pts[i] - next_ptsOpt[i];
305
306             double n = sqrt(shift.ddot(shift));
307             if (fabs(n - expected_shift) > thres)
308             {
309                 ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH);
310                 return false;
311             }
312         }
313
314         if (status_Aff[i])
315         {
316             circle(cnext, next_ptsAff[i], 4, CV_RGB(0, 255, 0));
317             Point2f shift = prev_pts[i] - next_ptsAff[i];
318
319             double n = sqrt(shift.ddot(shift));
320             if (fabs(n - expected_shift) > thres)
321             {
322                 ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH);
323                 return false;
324             }
325         }
326
327     }
328
329     /*namedWindow("P");  imshow("P", cprev);
330     namedWindow("N"); imshow("N", cnext);
331     waitKey();*/
332
333     return true;
334 }
335
336
337 void CV_OptFlowTest::run( int /* start_from */)
338 {
339
340     if (!runDense(Point(3, 0)))
341         return;
342
343     if (!runDense(Point(0, 3)))
344         return;
345
346     //if (!runDense(Point(3, 3))) return;  //probably LK works incorrectly in this case.
347
348     if (!runSparse())
349         return;
350
351     ts->set_failed_test_info(cvtest::TS::OK);
352 }
353
354
355 TEST(Legacy_OpticalFlow, accuracy) { CV_OptFlowTest test; test.safe_run(); }