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