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