96b8c6192492966d99a9487b5b3432ac5a92e57e
[platform/upstream/opencv.git] / modules / softcascade / src / octave.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) 2008-2013, 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 "precomp.hpp"
44 #include "opencv2/ml.hpp"
45 #include <queue>
46
47 using cv::InputArray;
48 using cv::OutputArray;
49 using cv::Mat;
50
51 using cv::softcascade::Octave;
52 using cv::softcascade::FeaturePool;
53 using cv::softcascade::Dataset;
54 using cv::softcascade::ChannelFeatureBuilder;
55
56 FeaturePool::~FeaturePool(){}
57 Dataset::~Dataset(){}
58
59 namespace {
60
61 class BoostedSoftCascadeOctave : public cv::Boost, public Octave
62 {
63 public:
64
65     BoostedSoftCascadeOctave(cv::Rect boundingBox = cv::Rect(), int npositives = 0, int nnegatives = 0, int logScale = 0,
66         int shrinkage = 1, cv::Ptr<ChannelFeatureBuilder> builder = ChannelFeatureBuilder::create("HOG6MagLuv"));
67     virtual ~BoostedSoftCascadeOctave();
68     virtual cv::AlgorithmInfo* info() const;
69     virtual bool train(const Dataset* dataset, const FeaturePool* pool, int weaks, int treeDepth);
70     virtual void setRejectThresholds(OutputArray thresholds);
71     virtual void write( cv::FileStorage &fs, const FeaturePool* pool, InputArray thresholds) const;
72     virtual void write( CvFileStorage* fs, cv::String name) const;
73 protected:
74     virtual float predict( InputArray _sample, InputArray _votes, bool raw_mode, bool return_sum ) const;
75     virtual bool train( const cv::Mat& trainData, const cv::Mat& responses, const cv::Mat& varIdx=cv::Mat(),
76        const cv::Mat& sampleIdx=cv::Mat(), const cv::Mat& varType=cv::Mat(), const cv::Mat& missingDataMask=cv::Mat());
77
78     void processPositives(const Dataset* dataset);
79     void generateNegatives(const Dataset* dataset);
80
81     float predict( const Mat& _sample, const cv::Range range) const;
82 private:
83     void traverse(const CvBoostTree* tree, cv::FileStorage& fs, int& nfeatures, int* used, const double* th) const;
84     virtual void initialize_weights(double (&p)[2]);
85
86     int logScale;
87     cv::Rect boundingBox;
88
89     int npositives;
90     int nnegatives;
91
92     int shrinkage;
93
94     Mat integrals;
95     Mat responses;
96
97     CvBoostParams params;
98
99     Mat trainData;
100
101     cv::Ptr<ChannelFeatureBuilder> builder;
102 };
103
104 BoostedSoftCascadeOctave::BoostedSoftCascadeOctave(cv::Rect bb, int np, int nn, int ls, int shr,
105     cv::Ptr<ChannelFeatureBuilder> _builder)
106 : logScale(ls), boundingBox(bb), npositives(np), nnegatives(nn), shrinkage(shr)
107 {
108     int maxSample = npositives + nnegatives;
109     responses.create(maxSample, 1, CV_32FC1);
110
111     CvBoostParams _params;
112     {
113         // tree params
114         _params.max_categories       = 10;
115         _params.max_depth            = 2;
116         _params.cv_folds             = 0;
117         _params.truncate_pruned_tree = false;
118         _params.use_surrogates       = false;
119         _params.use_1se_rule         = false;
120         _params.regression_accuracy  = 0;
121
122         // boost params
123         _params.boost_type           = CvBoost::GENTLE;
124         _params.split_criteria       = CvBoost::SQERR;
125         _params.weight_trim_rate     = 0.95;
126
127         // simple defaults
128         _params.min_sample_count     = 0;
129         _params.weak_count           = 1;
130     }
131
132     params = _params;
133
134     builder = _builder;
135
136     int w = boundingBox.width;
137     int h = boundingBox.height;
138
139     integrals.create(npositives + nnegatives, (w / shrinkage + 1) * (h / shrinkage * builder->totalChannels() + 1), CV_32SC1);
140 }
141
142 BoostedSoftCascadeOctave::~BoostedSoftCascadeOctave(){}
143
144 bool BoostedSoftCascadeOctave::train( const cv::Mat& _trainData, const cv::Mat& _responses, const cv::Mat& varIdx,
145        const cv::Mat& sampleIdx, const cv::Mat& varType, const cv::Mat& missingDataMask)
146 {
147     bool update = false;
148     return cv::Boost::train(_trainData, CV_COL_SAMPLE, _responses, varIdx, sampleIdx, varType, missingDataMask, params,
149     update);
150 }
151
152 void BoostedSoftCascadeOctave::setRejectThresholds(cv::OutputArray _thresholds)
153 {
154     // labels decided by classifier
155     cv::Mat desisions(responses.cols, responses.rows, responses.type());
156     float* dptr = desisions.ptr<float>(0);
157
158     // mask of samples satisfying the condition
159     cv::Mat ppmask(responses.cols, responses.rows, CV_8UC1);
160     uchar* mptr = ppmask.ptr<uchar>(0);
161
162     int nsamples = npositives + nnegatives;
163
164     cv::Mat stab;
165
166     for (int si = 0; si < nsamples; ++si)
167     {
168         float decision = dptr[si] = predict(trainData.col(si), stab, false, false);
169         mptr[si] = cv::saturate_cast<uchar>((unsigned int)( (responses.ptr<float>(si)[0] == 1.f) && (decision == 1.f)));
170     }
171
172     int weaks = weak->total;
173     _thresholds.create(1, weaks, CV_64FC1);
174     cv::Mat& thresholds = _thresholds.getMatRef();
175     double* thptr = thresholds.ptr<double>(0);
176
177     cv::Mat traces(weaks, nsamples, CV_64FC1, cv::Scalar::all(FLT_MAX));
178
179     for (int w = 0; w < weaks; ++w)
180     {
181         double* rptr = traces.ptr<double>(w);
182         for (int si = 0; si < nsamples; ++si)
183         {
184             cv::Range curr(0, w + 1);
185             if (mptr[si])
186             {
187                 float trace = predict(trainData.col(si), curr);
188                 rptr[si] = trace;
189             }
190         }
191         double mintrace = 0.;
192         cv::minMaxLoc(traces.row(w), &mintrace);
193         thptr[w] = mintrace;
194     }
195 }
196
197 void BoostedSoftCascadeOctave::processPositives(const Dataset* dataset)
198 {
199     int h = boundingBox.height;
200
201     ChannelFeatureBuilder& _builder = *builder;
202
203     int total = 0;
204     for (int curr = 0; curr < dataset->available( Dataset::POSITIVE); ++curr)
205     {
206         cv::Mat sample = dataset->get( Dataset::POSITIVE, curr);
207
208         cv::Mat channels = integrals.row(total).reshape(0, h / shrinkage * builder->totalChannels() + 1);
209         sample = sample(boundingBox);
210
211         _builder(sample, channels);
212         responses.ptr<float>(total)[0] = 1.f;
213
214         if (++total >= npositives) break;
215     }
216     npositives  = total;
217     nnegatives = cvRound(nnegatives * total / (double)npositives);
218 }
219
220 void BoostedSoftCascadeOctave::generateNegatives(const Dataset* dataset)
221 {
222     using namespace cv::softcascade::internal;
223     // ToDo: set seed, use offsets
224     Random::engine eng(DX_DY_SEED);
225     Random::engine idxEng((Random::seed_type)INDEX_ENGINE_SEED);
226
227     int h = boundingBox.height;
228
229     int nimages = dataset->available(Dataset::NEGATIVE);
230     Random::uniform iRand(0, nimages - 1);
231
232     int total = 0;
233     Mat sum;
234
235     ChannelFeatureBuilder& _builder = *builder;
236     for (int i = npositives; i < nnegatives + npositives; ++total)
237     {
238         int curr = iRand(idxEng);
239
240         Mat frame = dataset->get(Dataset::NEGATIVE, curr);
241
242         int maxW = frame.cols - 2 * boundingBox.x - boundingBox.width;
243         int maxH = frame.rows - 2 * boundingBox.y - boundingBox.height;
244
245         Random::uniform wRand(0, maxW -1);
246         Random::uniform hRand(0, maxH -1);
247
248         int dx = wRand(eng);
249         int dy = hRand(eng);
250
251         frame = frame(cv::Rect(dx, dy, boundingBox.width, boundingBox.height));
252
253         cv::Mat channels = integrals.row(i).reshape(0, h / shrinkage * builder->totalChannels() + 1);
254         _builder(frame, channels);
255
256         // // if (predict(sum))
257         {
258             responses.ptr<float>(i)[0] = 0.f;
259             ++i;
260         }
261     }
262 }
263
264
265 template <typename T> int sgn(T val) {
266     return (T(0) < val) - (val < T(0));
267 }
268
269 void BoostedSoftCascadeOctave::traverse(const CvBoostTree* tree, cv::FileStorage& fs, int& nfeatures, int* used, const double* th) const
270 {
271     std::queue<const CvDTreeNode*> nodes;
272     nodes.push( tree->get_root());
273     const CvDTreeNode* tempNode;
274     int leafValIdx = 0;
275     int internalNodeIdx = 1;
276     float* leafs = new float[(int)pow(2.f, get_params().max_depth)];
277
278     fs << "{";
279     fs << "treeThreshold" << *th;
280     fs << "internalNodes" << "[";
281     while (!nodes.empty())
282     {
283         tempNode = nodes.front();
284         CV_Assert( tempNode->left );
285         if ( !tempNode->left->left && !tempNode->left->right)
286         {
287             leafs[-leafValIdx] = (float)tempNode->left->value;
288             fs << leafValIdx-- ;
289         }
290         else
291         {
292             nodes.push( tempNode->left );
293             fs << internalNodeIdx++;
294         }
295         CV_Assert( tempNode->right );
296         if ( !tempNode->right->left && !tempNode->right->right)
297         {
298             leafs[-leafValIdx] = (float)tempNode->right->value;
299             fs << leafValIdx--;
300         }
301         else
302         {
303             nodes.push( tempNode->right );
304             fs << internalNodeIdx++;
305         }
306
307         int fidx = tempNode->split->var_idx;
308         fs << nfeatures;
309         used[nfeatures++] = fidx;
310
311         fs << tempNode->split->ord.c;
312
313         nodes.pop();
314     }
315     fs << "]";
316
317     fs << "leafValues" << "[";
318     for (int ni = 0; ni < -leafValIdx; ni++)
319         fs << leafs[ni];
320     fs << "]";
321
322
323     fs << "}";
324
325     delete [] leafs;
326 }
327
328 void BoostedSoftCascadeOctave::write( cv::FileStorage &fso, const FeaturePool* pool, InputArray _thresholds) const
329 {
330     CV_Assert(!_thresholds.empty());
331     cv::Mat used( 1, weak->total * ( (int)pow(2.f, params.max_depth) - 1), CV_32SC1);
332     int* usedPtr = used.ptr<int>(0);
333     int nfeatures = 0;
334     cv::Mat thresholds = _thresholds.getMat();
335     fso << "{"
336         << "scale" << logScale
337         << "weaks" << weak->total
338         << "trees" << "[";
339         // should be replaced with the H.L. one
340         CvSeqReader reader;
341         cvStartReadSeq( weak, &reader);
342
343         for(int i = 0; i < weak->total; i++ )
344         {
345             CvBoostTree* tree;
346             CV_READ_SEQ_ELEM( tree, reader );
347
348             traverse(tree, fso, nfeatures, usedPtr, thresholds.ptr<double>(0) + i);
349         }
350     fso << "]";
351     // features
352
353     fso << "features" << "[";
354     for (int i = 0; i < nfeatures; ++i)
355         pool->write(fso, usedPtr[i]);
356     fso << "]"
357         << "}";
358 }
359
360 void BoostedSoftCascadeOctave::initialize_weights(double (&p)[2])
361 {
362     double n = data->sample_count;
363     p[0] =  n / (2. * (double)(nnegatives));
364     p[1] =  n / (2. * (double)(npositives));
365 }
366
367 bool BoostedSoftCascadeOctave::train(const Dataset* dataset, const FeaturePool* pool, int weaks, int treeDepth)
368 {
369     CV_Assert(treeDepth == 2);
370     CV_Assert(weaks > 0);
371
372     params.max_depth  = treeDepth;
373     params.weak_count = weaks;
374
375     // 1. fill integrals and classes
376     processPositives(dataset);
377     generateNegatives(dataset);
378
379     // 2. only simple case (all features used)
380     int nfeatures = pool->size();
381     cv::Mat varIdx(1, nfeatures, CV_32SC1);
382     int* ptr = varIdx.ptr<int>(0);
383
384     for (int x = 0; x < nfeatures; ++x)
385         ptr[x] = x;
386
387     // 3. only simple case (all samples used)
388     int nsamples = npositives + nnegatives;
389     cv::Mat sampleIdx(1, nsamples, CV_32SC1);
390     ptr = sampleIdx.ptr<int>(0);
391
392     for (int x = 0; x < nsamples; ++x)
393         ptr[x] = x;
394
395     // 4. ICF has an ordered response.
396     cv::Mat varType(1, nfeatures + 1, CV_8UC1);
397     uchar* uptr = varType.ptr<uchar>(0);
398     for (int x = 0; x < nfeatures; ++x)
399         uptr[x] = CV_VAR_ORDERED;
400     uptr[nfeatures] = CV_VAR_CATEGORICAL;
401
402     trainData.create(nfeatures, nsamples, CV_32FC1);
403     for (int fi = 0; fi < nfeatures; ++fi)
404     {
405         float* dptr = trainData.ptr<float>(fi);
406         for (int si = 0; si < nsamples; ++si)
407         {
408             dptr[si] = pool->apply(fi, si, integrals);
409         }
410     }
411
412     cv::Mat missingMask;
413
414     bool ok = train(trainData, responses, varIdx, sampleIdx, varType, missingMask);
415     if (!ok)
416         CV_Error(CV_StsInternal, "ERROR: tree can not be trained");
417     return ok;
418
419 }
420
421 float BoostedSoftCascadeOctave::predict( cv::InputArray _sample, cv::InputArray _votes, bool raw_mode, bool return_sum ) const
422 {
423     cv::Mat sample = _sample.getMat();
424     CvMat csample = sample;
425     if (_votes.empty())
426         return CvBoost::predict(&csample, 0, 0, CV_WHOLE_SEQ, raw_mode, return_sum);
427     else
428     {
429         cv::Mat votes = _votes.getMat();
430         CvMat cvotes = votes;
431         return CvBoost::predict(&csample, 0, &cvotes, CV_WHOLE_SEQ, raw_mode, return_sum);
432     }
433 }
434
435 float BoostedSoftCascadeOctave::predict( const Mat& _sample, const cv::Range range) const
436 {
437     CvMat sample = _sample;
438     return CvBoost::predict(&sample, 0, 0, range, false, true);
439 }
440
441 void BoostedSoftCascadeOctave::write( CvFileStorage* fs, cv::String _name) const
442 {
443     CvBoost::write(fs, _name.c_str());
444 }
445
446 }
447
448 CV_INIT_ALGORITHM(BoostedSoftCascadeOctave, "Octave.BoostedSoftCascadeOctave", )
449
450 Octave::~Octave(){}
451
452 cv::Ptr<Octave> Octave::create(cv::Rect boundingBox, int npositives, int nnegatives,
453         int logScale, int shrinkage, cv::Ptr<ChannelFeatureBuilder> builder)
454 {
455     cv::Ptr<Octave> octave(
456         new BoostedSoftCascadeOctave(boundingBox, npositives, nnegatives, logScale, shrinkage, builder));
457     return octave;
458 }