CLAHE Python bindings
[profile/ivi/opencv.git] / modules / objdetect / test / test_latentsvmdetector.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
45 #include <string>
46
47 #ifdef HAVE_CVCONFIG_H
48 #include "cvconfig.h"
49 #endif
50
51 #ifdef HAVE_TBB
52 #include "tbb/task_scheduler_init.h"
53 #endif
54
55 using namespace cv;
56
57 const int num_detections = 3;
58 const float true_scores[3] = {-0.383931f, -0.825876f, -0.959934f};
59 const float score_thr = 0.05f;
60 const CvRect true_bounding_boxes[3] = {cvRect(0, 45, 362, 452), cvRect(304, 0, 64, 80), cvRect(236, 0, 108, 59)};
61
62 class CV_LatentSVMDetectorTest : public cvtest::BaseTest
63 {
64 protected:
65     void run(int);
66     bool isEqual(CvRect r1, CvRect r2, int eps);
67 };
68
69 bool CV_LatentSVMDetectorTest::isEqual(CvRect r1, CvRect r2, int eps)
70 {
71     return (std::abs(r1.x - r2.x) <= eps
72             && std::abs(r1.y - r2.y) <= eps
73             && std::abs(r1.width - r2.width) <= eps
74             && std::abs(r1.height - r2.height) <= eps);
75 }
76
77 void CV_LatentSVMDetectorTest::run( int /* start_from */)
78 {
79     string img_path = string(ts->get_data_path()) + "latentsvmdetector/cat.png";
80     string model_path = string(ts->get_data_path()) + "latentsvmdetector/models_VOC2007/cat.xml";
81     int numThreads = -1;
82
83 #ifdef HAVE_TBB
84     numThreads = 2;
85     tbb::task_scheduler_init init(tbb::task_scheduler_init::deferred);
86     init.initialize(numThreads);
87 #endif
88
89     IplImage* image = cvLoadImage(img_path.c_str());
90     if (!image)
91     {
92         ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
93         return;
94     }
95
96     CvLatentSvmDetector* detector = cvLoadLatentSvmDetector(model_path.c_str());
97     if (!detector)
98     {
99         ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
100         cvReleaseImage(&image);
101         return;
102     }
103
104     CvMemStorage* storage = cvCreateMemStorage(0);
105     CvSeq* detections = 0;
106     detections = cvLatentSvmDetectObjects(image, detector, storage, 0.5f, numThreads);
107     if (detections->total != num_detections)
108     {
109         ts->set_failed_test_info( cvtest::TS::FAIL_MISMATCH );
110     }
111     else
112     {
113         ts->set_failed_test_info(cvtest::TS::OK);
114         for (int i = 0; i < detections->total; i++)
115         {
116             CvObjectDetection detection = *(CvObjectDetection*)cvGetSeqElem( detections, i );
117             CvRect bounding_box = detection.rect;
118             float score = detection.score;
119             if ((!isEqual(bounding_box, true_bounding_boxes[i], 1)) || (fabs(score - true_scores[i]) > score_thr))
120             {
121                 ts->set_failed_test_info( cvtest::TS::FAIL_MISMATCH );
122                 break;
123             }
124         }
125     }
126 #ifdef HAVE_TBB
127     init.terminate();
128 #endif
129     cvReleaseMemStorage( &storage );
130     cvReleaseLatentSvmDetector( &detector );
131     cvReleaseImage( &image );
132 }
133
134 // Test for c++ version of Latent SVM
135
136 class LatentSVMDetectorTest : public cvtest::BaseTest
137 {
138 protected:
139     void run(int);
140 };
141
142 static void writeDetections( FileStorage& fs, const string& nodeName, const vector<LatentSvmDetector::ObjectDetection>& detections )
143 {
144     fs << nodeName << "[";
145     for( size_t i = 0; i < detections.size(); i++ )
146     {
147         const LatentSvmDetector::ObjectDetection& d = detections[i];
148         fs << d.rect.x << d.rect.y << d.rect.width << d.rect.height
149            << d.score << d.classID;
150     }
151     fs << "]";
152 }
153
154 static void readDetections( FileStorage fs, const string& nodeName, vector<LatentSvmDetector::ObjectDetection>& detections )
155 {
156     detections.clear();
157
158     FileNode fn = fs.root()[nodeName];
159     FileNodeIterator fni = fn.begin();
160     while( fni != fn.end() )
161     {
162         LatentSvmDetector::ObjectDetection d;
163         fni >> d.rect.x >> d.rect.y >> d.rect.width >> d.rect.height
164             >> d.score >> d.classID;
165         detections.push_back( d );
166     }
167 }
168
169 static inline bool isEqual( const LatentSvmDetector::ObjectDetection& d1, const LatentSvmDetector::ObjectDetection& d2, int eps, float threshold)
170 {
171     return (
172            std::abs(d1.rect.x - d2.rect.x) <= eps
173            && std::abs(d1.rect.y - d2.rect.y) <= eps
174            && std::abs(d1.rect.width - d2.rect.width) <= eps
175            && std::abs(d1.rect.height - d2.rect.height) <= eps
176            && (d1.classID == d2.classID)
177            && std::abs(d1.score - d2.score) <= threshold
178            );
179 }
180
181 std::ostream& operator << (std::ostream& os, const CvRect& r)
182 {
183     return (os << "[x=" << r.x << ", y=" << r.y << ", w=" << r.width << ", h=" << r.height << "]");
184 }
185
186 bool compareResults( const vector<LatentSvmDetector::ObjectDetection>& calc, const vector<LatentSvmDetector::ObjectDetection>& valid, int eps, float threshold)
187 {
188     if( calc.size() != valid.size() )
189         return false;
190
191     for( size_t i = 0; i < calc.size(); i++ )
192     {
193         const LatentSvmDetector::ObjectDetection& c = calc[i];
194         const LatentSvmDetector::ObjectDetection& v = valid[i];
195         if( !isEqual(c, v, eps, threshold) )
196         {
197             std::cerr << "Expected: " << v.rect << " class=" << v.classID << " score=" << v.score << std::endl;
198             std::cerr << "Actual:   " << c.rect << " class=" << c.classID << " score=" << c.score << std::endl;
199             return false;
200         }
201     }
202     return true;
203 }
204
205 void LatentSVMDetectorTest::run( int /* start_from */)
206 {
207     string img_path_cat = string(ts->get_data_path()) + "latentsvmdetector/cat.png";
208     string img_path_cars = string(ts->get_data_path()) + "latentsvmdetector/cars.png";
209
210     string model_path_cat = string(ts->get_data_path()) + "latentsvmdetector/models_VOC2007/cat.xml";
211     string model_path_car = string(ts->get_data_path()) + "latentsvmdetector/models_VOC2007/car.xml";
212
213     string true_res_path = string(ts->get_data_path()) + "latentsvmdetector/results.xml";
214
215     int numThreads = 1;
216
217 #ifdef HAVE_TBB
218     numThreads = 2;
219 #endif
220
221     Mat image_cat = imread( img_path_cat );
222     Mat image_cars = imread( img_path_cars );
223     if( image_cat.empty() || image_cars.empty() )
224     {
225         ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
226         return;
227     }
228
229     // We will test 2 cases:
230     // detector1 - to test case of one class 'cat'
231     // detector12 - to test case of two (several) classes 'cat' and car
232
233     // Load detectors
234     LatentSvmDetector detector1( vector<string>(1,model_path_cat) );
235
236     vector<string> models_pathes(2);
237     models_pathes[0] = model_path_cat;
238     models_pathes[1] = model_path_car;
239     LatentSvmDetector detector12( models_pathes );
240
241     if( detector1.empty() || detector12.empty() || detector12.getClassCount() != 2 )
242     {
243         ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
244         return;
245     }
246
247     // 1. Test method detect
248     // Run detectors
249     vector<LatentSvmDetector::ObjectDetection> detections1_cat, detections12_cat, detections12_cars;
250     detector1.detect( image_cat, detections1_cat, 0.5, numThreads );
251     detector12.detect( image_cat, detections12_cat, 0.5, numThreads );
252     detector12.detect( image_cars, detections12_cars, 0.5, numThreads );
253
254     // Load true results
255     FileStorage fs( true_res_path, FileStorage::READ );
256     if( fs.isOpened() )
257     {
258         vector<LatentSvmDetector::ObjectDetection> true_detections1_cat, true_detections12_cat, true_detections12_cars;
259         readDetections( fs, "detections1_cat", true_detections1_cat );
260         readDetections( fs, "detections12_cat", true_detections12_cat );
261         readDetections( fs, "detections12_cars", true_detections12_cars );
262
263
264         if( !compareResults(detections1_cat, true_detections1_cat, 1, score_thr) )
265         {
266             std::cerr << "Results of detector1 are invalid on image cat.png" << std::endl;
267             ts->set_failed_test_info( cvtest::TS::FAIL_MISMATCH );
268         }
269         if( !compareResults(detections12_cat, true_detections12_cat, 1, score_thr) )
270         {
271             std::cerr << "Results of detector12 are invalid on image cat.png" << std::endl;
272             ts->set_failed_test_info( cvtest::TS::FAIL_MISMATCH );
273         }
274         if( !compareResults(detections12_cars, true_detections12_cars, 1, score_thr) )
275         {
276             std::cerr << "Results of detector12 are invalid on image cars.png" << std::endl;
277             ts->set_failed_test_info( cvtest::TS::FAIL_MISMATCH );
278         }
279     }
280     else
281     {
282         fs.open( true_res_path, FileStorage::WRITE );
283         if( fs.isOpened() )
284         {
285             writeDetections( fs, "detections1_cat", detections1_cat );
286             writeDetections( fs, "detections12_cat", detections12_cat );
287             writeDetections( fs, "detections12_cars", detections12_cars );
288         }
289         else
290             std::cerr << "File " << true_res_path << " cann't be opened to save test results" << std::endl;
291     }
292
293     // 2. Simple tests of other methods
294     if( detector1.getClassCount() != 1 || detector1.getClassNames()[0] != "cat" )
295     {
296         std::cerr << "Incorrect result of method getClassNames() or getClassCount()" << std::endl;
297         ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT);
298     }
299
300     detector1.clear();
301     if( !detector1.empty() )
302     {
303         std::cerr << "There is a bug in method clear() or empty()" << std::endl;
304         ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT);
305     }
306
307     ts->set_failed_test_info( cvtest::TS::OK);
308 }
309
310 TEST(Objdetect_LatentSVMDetector_c, DISABLED_regression) { CV_LatentSVMDetectorTest test; test.safe_run(); }
311 TEST(Objdetect_LatentSVMDetector_cpp, DISABLED_regression) { LatentSVMDetectorTest test; test.safe_run(); }