Set stricter warning rules for gcc
[profile/ivi/opencv.git] / modules / ts / include / opencv2 / ts / ts.hpp
1 #ifndef __OPENCV_GTESTCV_HPP__
2 #define __OPENCV_GTESTCV_HPP__
3
4 #if HAVE_CVCONFIG_H
5 #include "cvconfig.h"
6 #endif
7 #ifndef GTEST_CREATE_SHARED_LIBRARY
8 #ifdef BUILD_SHARED_LIBS
9 #define GTEST_LINKED_AS_SHARED_LIBRARY 1
10 #endif
11 #endif
12
13 #ifdef ANDROID
14 # include <android/api-level.h>
15 # define GTEST_HAS_CLONE (__ANDROID_API__ > 7 && __arm__)
16 # define GTEST_HAS_POSIX_RE (__ANDROID_API__ > 7)
17 # define GTEST_HAS_STD_WSTRING _GLIBCXX_USE_WCHAR_T
18 #endif
19
20 #include <stdarg.h> // for va_list
21
22 #if defined _MSC_VER && _MSC_VER >= 1200
23 #pragma warning( disable: 4251 4275 4355 4127 )
24 #endif
25
26 #define GTEST_DONT_DEFINE_FAIL      0
27 #define GTEST_DONT_DEFINE_SUCCEED   0
28 #define GTEST_DONT_DEFINE_ASSERT_EQ 0
29 #define GTEST_DONT_DEFINE_ASSERT_NE 0
30 #define GTEST_DONT_DEFINE_ASSERT_LE 0
31 #define GTEST_DONT_DEFINE_ASSERT_LT 0
32 #define GTEST_DONT_DEFINE_ASSERT_GE 0
33 #define GTEST_DONT_DEFINE_ASSERT_GT 0
34 #define GTEST_DONT_DEFINE_TEST      0
35
36 #include "opencv2/ts/ts_gtest.h"
37
38 #ifndef GTEST_USES_SIMPLE_RE
39 #  define GTEST_USES_SIMPLE_RE 0
40 #endif
41 #ifdef __GNUC__
42 #  pragma GCC diagnostic ignored "-Wmissing-declarations"
43 #endif
44
45 #include "opencv2/core/core.hpp"
46
47 namespace cvtest
48 {
49
50 using std::vector;
51 using std::string;
52 using cv::RNG;
53 using cv::Mat;
54 using cv::Scalar;
55 using cv::Size;
56 using cv::Point;
57 using cv::Rect;
58
59 class CV_EXPORTS TS;
60
61 CV_EXPORTS int64 readSeed(const char* str);
62
63 CV_EXPORTS void randUni( RNG& rng, Mat& a, const Scalar& param1, const Scalar& param2 );
64
65 inline unsigned randInt( RNG& rng )
66 {
67     return (unsigned)rng;
68 }
69
70 inline  double randReal( RNG& rng )
71 {
72     return (double)rng;
73 }
74
75
76 CV_EXPORTS const char* getTypeName( int type );
77 CV_EXPORTS int typeByName( const char* type_name );
78
79 CV_EXPORTS string vec2str(const string& sep, const int* v, size_t nelems);
80
81 inline int clipInt( int val, int min_val, int max_val )
82 {
83     if( val < min_val )
84         val = min_val;
85     if( val > max_val )
86         val = max_val;
87     return val;
88 }
89
90 CV_EXPORTS double getMinVal(int depth);
91 CV_EXPORTS double getMaxVal(int depth);
92
93 CV_EXPORTS Size randomSize(RNG& rng, double maxSizeLog);
94 CV_EXPORTS void randomSize(RNG& rng, int minDims, int maxDims, double maxSizeLog, vector<int>& sz);
95 CV_EXPORTS int randomType(RNG& rng, int typeMask, int minChannels, int maxChannels);
96 CV_EXPORTS Mat randomMat(RNG& rng, Size size, int type, double minVal, double maxVal, bool useRoi);
97 CV_EXPORTS Mat randomMat(RNG& rng, const vector<int>& size, int type, double minVal, double maxVal, bool useRoi);
98 CV_EXPORTS void add(const Mat& a, double alpha, const Mat& b, double beta,
99                       Scalar gamma, Mat& c, int ctype, bool calcAbs=false);
100 CV_EXPORTS void multiply(const Mat& a, const Mat& b, Mat& c, double alpha=1);
101 CV_EXPORTS void divide(const Mat& a, const Mat& b, Mat& c, double alpha=1);
102
103 CV_EXPORTS void convert(const Mat& src, Mat& dst, int dtype, double alpha=1, double beta=0);
104 CV_EXPORTS void copy(const Mat& src, Mat& dst, const Mat& mask=Mat(), bool invertMask=false);
105 CV_EXPORTS void set(Mat& dst, const Scalar& gamma, const Mat& mask=Mat());
106
107 // working with multi-channel arrays
108 CV_EXPORTS void extract( const Mat& a, Mat& plane, int coi );
109 CV_EXPORTS void insert( const Mat& plane, Mat& a, int coi );
110
111 // checks that the array does not have NaNs and/or Infs and all the elements are
112 // within [min_val,max_val). idx is the index of the first "bad" element.
113 CV_EXPORTS int check( const Mat& data, double min_val, double max_val, vector<int>* idx );
114
115 // modifies values that are close to zero
116 CV_EXPORTS void  patchZeros( Mat& mat, double level );
117
118 CV_EXPORTS void transpose(const Mat& src, Mat& dst);
119 CV_EXPORTS void erode(const Mat& src, Mat& dst, const Mat& _kernel, Point anchor=Point(-1,-1),
120                       int borderType=IPL_BORDER_CONSTANT, const Scalar& borderValue=Scalar());
121 CV_EXPORTS void dilate(const Mat& src, Mat& dst, const Mat& _kernel, Point anchor=Point(-1,-1),
122                        int borderType=IPL_BORDER_CONSTANT, const Scalar& borderValue=Scalar());
123 CV_EXPORTS void filter2D(const Mat& src, Mat& dst, int ddepth, const Mat& kernel,
124                          Point anchor, double delta, int borderType,
125                          const Scalar& borderValue=Scalar());
126 CV_EXPORTS void copyMakeBorder(const Mat& src, Mat& dst, int top, int bottom, int left, int right,
127                                int borderType, const Scalar& borderValue=Scalar());
128 CV_EXPORTS Mat calcSobelKernel2D( int dx, int dy, int apertureSize, int origin=0 );
129 CV_EXPORTS Mat calcLaplaceKernel2D( int aperture_size );
130
131 CV_EXPORTS void initUndistortMap( const Mat& a, const Mat& k, Size sz, Mat& mapx, Mat& mapy );
132
133 CV_EXPORTS void minMaxLoc(const Mat& src, double* minval, double* maxval,
134                           vector<int>* minloc, vector<int>* maxloc, const Mat& mask=Mat());
135 CV_EXPORTS double norm(const Mat& src, int normType, const Mat& mask=Mat());
136 CV_EXPORTS double norm(const Mat& src1, const Mat& src2, int normType, const Mat& mask=Mat());
137 CV_EXPORTS Scalar mean(const Mat& src, const Mat& mask=Mat());
138
139 CV_EXPORTS bool cmpUlps(const Mat& data, const Mat& refdata, int expMaxDiff, double* realMaxDiff, vector<int>* idx);
140
141 // compares two arrays. max_diff is the maximum actual difference,
142 // success_err_level is maximum allowed difference, idx is the index of the first
143 // element for which difference is >success_err_level
144 // (or index of element with the maximum difference)
145 CV_EXPORTS int cmpEps( const Mat& data, const Mat& refdata, double* max_diff,
146                        double success_err_level, vector<int>* idx,
147                        bool element_wise_relative_error );
148
149 // a wrapper for the previous function. in case of error prints the message to log file.
150 CV_EXPORTS int cmpEps2( TS* ts, const Mat& data, const Mat& refdata, double success_err_level,
151                         bool element_wise_relative_error, const char* desc );
152
153 CV_EXPORTS int cmpEps2_64f( TS* ts, const double* val, const double* refval, int len,
154                         double eps, const char* param_name );
155
156 CV_EXPORTS void logicOp(const Mat& src1, const Mat& src2, Mat& dst, char c);
157 CV_EXPORTS void logicOp(const Mat& src, const Scalar& s, Mat& dst, char c);
158 CV_EXPORTS void min(const Mat& src1, const Mat& src2, Mat& dst);
159 CV_EXPORTS void min(const Mat& src, double s, Mat& dst);
160 CV_EXPORTS void max(const Mat& src1, const Mat& src2, Mat& dst);
161 CV_EXPORTS void max(const Mat& src, double s, Mat& dst);
162
163 CV_EXPORTS void compare(const Mat& src1, const Mat& src2, Mat& dst, int cmpop);
164 CV_EXPORTS void compare(const Mat& src, double s, Mat& dst, int cmpop);
165 CV_EXPORTS void gemm(const Mat& src1, const Mat& src2, double alpha,
166                      const Mat& src3, double beta, Mat& dst, int flags);
167     CV_EXPORTS void transform( const Mat& src, Mat& dst, const Mat& transmat, const Mat& shift );
168 CV_EXPORTS double crossCorr(const Mat& src1, const Mat& src2);
169
170 struct CV_EXPORTS MatInfo
171 {
172     MatInfo(const Mat& _m) : m(&_m) {}
173     const Mat* m;
174 };
175
176 CV_EXPORTS std::ostream& operator << (std::ostream& out, const MatInfo& m);
177
178 struct CV_EXPORTS MatComparator
179 {
180 public:
181     MatComparator(double maxdiff, int context);
182
183     ::testing::AssertionResult operator()(const char* expr1, const char* expr2,
184                                           const Mat& m1, const Mat& m2);
185
186     double maxdiff;
187     double realmaxdiff;
188     vector<int> loc0;
189     int context;
190 };
191
192
193
194 class BaseTest;
195 class TS;
196
197 class CV_EXPORTS BaseTest
198 {
199 public:
200     // constructor(s) and destructor
201     BaseTest();
202     virtual ~BaseTest();
203
204     // the main procedure of the test
205     virtual void run( int start_from );
206
207     // the wrapper for run that cares of exceptions
208     virtual void safe_run( int start_from=0 );
209
210     const string& get_name() const { return name; }
211
212     // returns true if and only if the different test cases do not depend on each other
213     // (so that test system could get right to a problematic test case)
214     virtual bool can_do_fast_forward();
215
216     // deallocates all the memory.
217     // called by init() (before initialization) and by the destructor
218     virtual void clear();
219
220 protected:
221     int test_case_count; // the total number of test cases
222
223     // read test params
224     virtual int read_params( CvFileStorage* fs );
225
226     // returns the number of tests or -1 if it is unknown a-priori
227     virtual int get_test_case_count();
228
229     // prepares data for the next test case. rng seed is updated by the function
230     virtual int prepare_test_case( int test_case_idx );
231
232     // checks if the test output is valid and accurate
233     virtual int validate_test_results( int test_case_idx );
234
235     // calls the tested function. the method is called from run_test_case()
236     virtual void run_func(); // runs tested func(s)
237
238     // updates progress bar
239     virtual int update_progress( int progress, int test_case_idx, int count, double dt );
240
241     // finds test parameter
242     const CvFileNode* find_param( CvFileStorage* fs, const char* param_name );
243
244     // name of the test (it is possible to locate a test by its name)
245     string name;
246
247     // pointer to the system that includes the test
248     TS* ts;
249 };
250
251
252 /*****************************************************************************************\
253 *                               Information about a failed test                           *
254 \*****************************************************************************************/
255
256 struct TestInfo
257 {
258     TestInfo();
259
260     // pointer to the test
261     BaseTest* test;
262
263     // failure code (CV_FAIL*)
264     int code;
265
266     // seed value right before the data for the failed test case is prepared.
267     uint64 rng_seed;
268
269     // seed value right before running the test
270     uint64 rng_seed0;
271
272     // index of test case, can be then passed to BaseTest::proceed_to_test_case()
273     int test_case_idx;
274 };
275
276 /*****************************************************************************************\
277 *                                 Base Class for test system                              *
278 \*****************************************************************************************/
279
280 // common parameters:
281 struct CV_EXPORTS TSParams
282 {
283     TSParams();
284
285     // RNG seed, passed to and updated by every test executed.
286     uint64 rng_seed;
287
288     // whether to use IPP, MKL etc. or not
289     bool use_optimized;
290
291     // extensivity of the tests, scale factor for test_case_count
292     double test_case_count_scale;
293 };
294
295
296 class CV_EXPORTS TS
297 {
298 public:
299     // constructor(s) and destructor
300     TS();
301     virtual ~TS();
302
303     enum
304     {
305         NUL=0,
306         SUMMARY_IDX=0,
307         SUMMARY=1 << SUMMARY_IDX,
308         LOG_IDX=1,
309         LOG=1 << LOG_IDX,
310         CSV_IDX=2,
311         CSV=1 << CSV_IDX,
312         CONSOLE_IDX=3,
313         CONSOLE=1 << CONSOLE_IDX,
314         MAX_IDX=4
315     };
316
317     static TS* ptr();
318
319     // initialize test system before running the first test
320     virtual void init( const string& modulename );
321
322     // low-level printing functions that are used by individual tests and by the system itself
323     virtual void printf( int streams, const char* fmt, ... );
324     virtual void vprintf( int streams, const char* fmt, va_list arglist );
325
326     // updates the context: current test, test case, rng state
327     virtual void update_context( BaseTest* test, int test_case_idx, bool update_ts_context );
328
329     const TestInfo* get_current_test_info() { return &current_test_info; }
330
331     // sets information about a failed test
332     virtual void set_failed_test_info( int fail_code );
333
334     virtual void set_gtest_status();
335
336     // test error codes
337     enum
338     {
339         // everything is Ok
340         OK=0,
341
342         // generic error: stub value to be used
343         // temporarily if the error's cause is unknown
344         FAIL_GENERIC=-1,
345
346         // the test is missing some essential data to proceed further
347         FAIL_MISSING_TEST_DATA=-2,
348
349         // the tested function raised an error via cxcore error handler
350         FAIL_ERROR_IN_CALLED_FUNC=-3,
351
352         // an exception has been raised;
353         // for memory and arithmetic exception
354         // there are two specialized codes (see below...)
355         FAIL_EXCEPTION=-4,
356
357         // a memory exception
358         // (access violation, access to missed page, stack overflow etc.)
359         FAIL_MEMORY_EXCEPTION=-5,
360
361         // arithmetic exception (overflow, division by zero etc.)
362         FAIL_ARITHM_EXCEPTION=-6,
363
364         // the tested function corrupted memory (no exception have been raised)
365         FAIL_MEMORY_CORRUPTION_BEGIN=-7,
366         FAIL_MEMORY_CORRUPTION_END=-8,
367
368         // the tested function (or test ifself) do not deallocate some memory
369         FAIL_MEMORY_LEAK=-9,
370
371         // the tested function returned invalid object, e.g. matrix, containing NaNs,
372         // structure with NULL or out-of-range fields (while it should not)
373         FAIL_INVALID_OUTPUT=-10,
374
375         // the tested function returned valid object, but it does not match to
376         // the original (or produced by the test) object
377         FAIL_MISMATCH=-11,
378
379         // the tested function returned valid object (a single number or numerical array),
380         // but it differs too much from the original (or produced by the test) object
381         FAIL_BAD_ACCURACY=-12,
382
383         // the tested function hung. Sometimes, can be determined by unexpectedly long
384         // processing time (in this case there should be possibility to interrupt such a function
385         FAIL_HANG=-13,
386
387         // unexpected responce on passing bad arguments to the tested function
388         // (the function crashed, proceed succesfully (while it should not), or returned
389         // error code that is different from what is expected)
390         FAIL_BAD_ARG_CHECK=-14,
391
392         // the test data (in whole or for the particular test case) is invalid
393         FAIL_INVALID_TEST_DATA=-15,
394
395         // the test has been skipped because it is not in the selected subset of the tests to run,
396         // because it has been run already within the same run with the same parameters, or because
397         // of some other reason and this is not considered as an error.
398         // Normally TS::run() (or overrided method in the derived class) takes care of what
399         // needs to be run, so this code should not occur.
400         SKIPPED=1
401     };
402
403     // get file storage
404     CvFileStorage* get_file_storage();
405
406     // get RNG to generate random input data for a test
407     RNG& get_rng() { return rng; }
408
409     // returns the current error code
410     int get_err_code() { return current_test_info.code; }
411
412     // returns the test extensivity scale
413     double get_test_case_count_scale() { return params.test_case_count_scale; }
414
415     const string& get_data_path() const { return data_path; }
416
417     // returns textual description of failure code
418     static string str_from_code( int code );
419
420 protected:
421
422     // these are allocated within a test to try keep them valid in case of stack corruption
423     RNG rng;
424
425     // information about the current test
426     TestInfo current_test_info;
427
428     // the path to data files used by tests
429     string data_path;
430
431     TSParams params;
432     std::string output_buf[MAX_IDX];
433 };
434
435
436 /*****************************************************************************************\
437 *            Subclass of BaseTest for testing functions that process dense arrays           *
438 \*****************************************************************************************/
439
440 class CV_EXPORTS ArrayTest : public BaseTest
441 {
442 public:
443     // constructor(s) and destructor
444     ArrayTest();
445     virtual ~ArrayTest();
446
447     virtual void clear();
448
449 protected:
450
451     virtual int read_params( CvFileStorage* fs );
452     virtual int prepare_test_case( int test_case_idx );
453     virtual int validate_test_results( int test_case_idx );
454
455     virtual void prepare_to_validation( int test_case_idx );
456     virtual void get_test_array_types_and_sizes( int test_case_idx, vector<vector<Size> >& sizes, vector<vector<int> >& types );
457     virtual void fill_array( int test_case_idx, int i, int j, Mat& arr );
458     virtual void get_minmax_bounds( int i, int j, int type, Scalar& low, Scalar& high );
459     virtual double get_success_error_level( int test_case_idx, int i, int j );
460
461     bool cvmat_allowed;
462     bool iplimage_allowed;
463     bool optional_mask;
464     bool element_wise_relative_error;
465
466     int min_log_array_size;
467     int max_log_array_size;
468
469     enum { INPUT, INPUT_OUTPUT, OUTPUT, REF_INPUT_OUTPUT, REF_OUTPUT, TEMP, MASK, MAX_ARR };
470
471     vector<vector<void*> > test_array;
472     vector<vector<Mat> > test_mat;
473     float buf[4];
474 };
475
476
477 class CV_EXPORTS BadArgTest : public BaseTest
478 {
479 public:
480     // constructor(s) and destructor
481     BadArgTest();
482     virtual ~BadArgTest();
483
484 protected:
485     virtual int run_test_case( int expected_code, const string& descr );
486     virtual void run_func(void) = 0;
487     int test_case_idx;
488     int progress;
489     double t, freq;
490
491     template<class F>
492     int run_test_case( int expected_code, const string& _descr, F f)
493     {
494         double new_t = (double)cv::getTickCount(), dt;
495         if( test_case_idx < 0 )
496         {
497             test_case_idx = 0;
498             progress = 0;
499             dt = 0;
500         }
501         else
502         {
503             dt = (new_t - t)/(freq*1000);
504             t = new_t;
505         }
506         progress = update_progress(progress, test_case_idx, 0, dt);
507
508         int errcount = 0;
509         bool thrown = false;
510         const char* descr = _descr.c_str() ? _descr.c_str() : "";
511
512         try
513         {
514             f();
515         }
516         catch(const cv::Exception& e)
517         {
518             thrown = true;
519             if( e.code != expected_code )
520             {
521                 ts->printf(TS::LOG, "%s (test case #%d): the error code %d is different from the expected %d\n",
522                     descr, test_case_idx, e.code, expected_code);
523                 errcount = 1;
524             }
525         }
526         catch(...)
527         {
528             thrown = true;
529             ts->printf(TS::LOG, "%s  (test case #%d): unknown exception was thrown (the function has likely crashed)\n",
530                        descr, test_case_idx);
531             errcount = 1;
532         }
533         if(!thrown)
534         {
535             ts->printf(TS::LOG, "%s  (test case #%d): no expected exception was thrown\n",
536                        descr, test_case_idx);
537             errcount = 1;
538         }
539         test_case_idx++;
540
541         return errcount;
542     }
543 };
544
545 struct CV_EXPORTS DefaultRngAuto
546 {
547     const uint64 old_state;
548
549     DefaultRngAuto() : old_state(cv::theRNG().state) { cv::theRNG().state = (uint64)-1; }
550     ~DefaultRngAuto() { cv::theRNG().state = old_state; }
551
552     DefaultRngAuto& operator=(const DefaultRngAuto&);
553 };
554
555 }
556
557 // fills c with zeros
558 CV_EXPORTS void cvTsZero( CvMat* c, const CvMat* mask=0 );
559
560 // copies a to b (whole matrix or only the selected region)
561 CV_EXPORTS void cvTsCopy( const CvMat* a, CvMat* b, const CvMat* mask=0 );
562
563 // converts one array to another
564 CV_EXPORTS void  cvTsConvert( const CvMat* src, CvMat* dst );
565
566 CV_EXPORTS void cvTsGEMM( const CvMat* a, const CvMat* b, double alpha,
567                          const CvMat* c, double beta, CvMat* d, int flags );
568
569 #define CV_TEST_MAIN(resourcesubdir) \
570 int main(int argc, char **argv) \
571 { \
572     cvtest::TS::ptr()->init(resourcesubdir); \
573     ::testing::InitGoogleTest(&argc, argv); \
574     return RUN_ALL_TESTS(); \
575 }
576
577 #endif
578
579 #include "ts_perf.hpp"