waldboost.cpp 11.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
/*

By downloading, copying, installing or using the software you agree to this
license. If you do not agree to this license, do not download, install,
copy or use the software.


                          License Agreement
               For Open Source Computer Vision Library
                       (3-clause BSD License)

Copyright (C) 2013, OpenCV Foundation, all rights reserved.
Third party copyrights are property of their respective owners.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

  * Redistributions of source code must retain the above copyright notice,
    this list of conditions and the following disclaimer.

  * Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

  * Neither the names of the copyright holders nor the names of the contributors
    may be used to endorse or promote products derived from this software
    without specific prior written permission.

This software is provided by the copyright holders and contributors "as is" and
any express or implied warranties, including, but not limited to, the implied
warranties of merchantability and fitness for a particular purpose are
disclaimed. In no event shall copyright holders or contributors be liable for
any direct, indirect, incidental, special, exemplary, or consequential damages
(including, but not limited to, procurement of substitute goods or services;
loss of use, data, or profits; or business interruption) however caused
and on any theory of liability, whether in contract, strict liability,
or tort (including negligence or otherwise) arising in any way out of
the use of this software, even if advised of the possibility of such damage.

*/

#include "precomp.hpp"

Vlad Shakhuro's avatar
Vlad Shakhuro committed
44 45
using std::swap;

46
using std::vector;
47

Vlad Shakhuro's avatar
Vlad Shakhuro committed
48 49 50 51 52
#include <iostream>
using std::cout;
using std::endl;


manuele's avatar
manuele committed
53 54 55 56




57
namespace cv
58
{
manuele's avatar
manuele committed
59

60
namespace xobjdetect
61
{
manuele's avatar
manuele committed
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
  //sort in-place of columns of the input matrix
  void sort_columns_without_copy(Mat& m, Mat indices)
  {
    
    if(indices.data == 0)
      sortIdx(m, indices, cv::SORT_EVERY_ROW | cv::SORT_ASCENDING);
    
    Mat indices_of_indices;
    sortIdx(indices, indices_of_indices, cv::SORT_EVERY_ROW | cv::SORT_ASCENDING);
      
    std::vector<bool> visited;
    for(int c = 0; c<m.cols; c++)
      visited.push_back(false);
      
    int ind_v = 0;
    Mat temp_column = Mat();
    int next = 0;
    Mat column;
    while(ind_v < m.cols)
    {

      if(temp_column.data == 0)
      {
        (m.col(indices_of_indices.at<int>(0,ind_v))).copyTo(column);
      }
      else
      {
        temp_column.copyTo(column);
      }
      
      
      if(indices_of_indices.at<int>(0,next) != next) //value is in the right place
      {
        //store the next value to change
        (m.col(indices_of_indices.at<int>(0,next))).copyTo(temp_column);
        //insert the value to change at the right place
        column.copyTo(m.col(indices_of_indices.at<int>(0,next)));
        
        //find the index of the next value to change
        next = indices_of_indices.at<int>(0,next);
        //if the idenx is not visited yet
        if(visited[next] == false)
        {
          //then mark it as visited, it will be computed in the next round
          visited[next] = true;
        }
        else
        {
          //find first non visited index
          int i = 0;
manuele's avatar
manuele committed
112
          while(i<(int)visited.size() && visited[i] == true)
manuele's avatar
manuele committed
113 114 115 116 117 118 119 120 121 122 123 124 125
          {
            i++;
          }
          ind_v = i;
          next = i;
          temp_column = Mat();
          
        }
      }
      else // value is already at the right place
      {
        visited[next] = true;
        int i = 0;
manuele's avatar
manuele committed
126
        while(i<(int)visited.size() && visited[i] == true)
manuele's avatar
manuele committed
127 128 129 130 131 132 133 134 135 136 137 138 139
        {
          i++;
        }
        next = i;
        temp_column = Mat();
        ind_v = i;
      }
      
      
    }
    
    
  }
140

141
class WaldBoostImpl : public WaldBoost
142
{
143 144 145 146 147 148
public:
    /* Initialize WaldBoost cascade with default of specified parameters */
    WaldBoostImpl(const WaldBoostParams& params):
        params_(params)
    {}

manuele's avatar
manuele committed
149 150
    virtual std::vector<int> train(Mat& data,
                                   const Mat& labels, bool use_fast_log=false);
151 152

    virtual float predict(
153
        const Ptr<FeatureEvaluator>& feature_evaluator) const;
154

Vlad Shakhuro's avatar
Vlad Shakhuro committed
155 156 157 158
    virtual void write(FileStorage& fs) const;

    virtual void read(const FileNode& node);

159 160 161 162 163 164 165 166 167
private:
    /* Parameters for cascade training */
    WaldBoostParams params_;
    /* Stumps in cascade */
    std::vector<Stump> stumps_;
    /* Rejection thresholds for linear combination at every stump evaluation */
    std::vector<float> thresholds_;
};

Vlad Shakhuro's avatar
Vlad Shakhuro committed
168 169 170 171 172 173 174 175 176 177 178
static int count(const Mat_<int> &m, int elem)
{
    int res = 0;
    for( int row = 0; row < m.rows; ++row )
        for( int col = 0; col < m.cols; ++col )
            if( m(row, col) == elem)
                res += 1;
    return res;
}

void WaldBoostImpl::read(const FileNode& node)
179
{
Vlad Shakhuro's avatar
Vlad Shakhuro committed
180 181 182
    FileNode params = node["waldboost_params"];
    params_.weak_count = (int)(params["weak_count"]);
    params_.alpha = (float)(params["alpha"]);
183

Vlad Shakhuro's avatar
Vlad Shakhuro committed
184 185 186
    FileNode stumps = node["waldboost_stumps"];
    stumps_.clear();
    for( FileNodeIterator n = stumps.begin(); n != stumps.end(); ++n )
187
    {
Vlad Shakhuro's avatar
Vlad Shakhuro committed
188 189 190
        Stump s;
        *n >> s;
        stumps_.push_back(s);
191 192
    }

Vlad Shakhuro's avatar
Vlad Shakhuro committed
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
    FileNode thresholds = node["waldboost_thresholds"];
    thresholds_.clear();
    for( FileNodeIterator n = thresholds.begin(); n != thresholds.end(); ++n )
    {
        float t;
        *n >> t;
        thresholds_.push_back(t);
    }
}

void WaldBoostImpl::write(FileStorage& fs) const
{
    fs << "{";
    fs << "waldboost_params" << "{"
        << "weak_count" << params_.weak_count
        << "alpha" << params_.alpha
        << "}";

    fs << "waldboost_stumps" << "[";
    for( size_t i = 0; i < stumps_.size(); ++i )
        fs << stumps_[i];
    fs << "]";

    fs << "waldboost_thresholds" << "[";
    for( size_t i = 0; i < thresholds_.size(); ++i )
        fs << thresholds_[i];
    fs << "]";
    fs << "}";

}

manuele's avatar
manuele committed
224
vector<int> WaldBoostImpl::train(Mat& data, const Mat& labels_, bool use_fast_log)
Vlad Shakhuro's avatar
Vlad Shakhuro committed
225
{
manuele's avatar
manuele committed
226 227
    CV_Assert(labels_.rows == 1 && labels_.cols == data.cols);    
    CV_Assert(data.rows >= params_.weak_count);
Vlad Shakhuro's avatar
Vlad Shakhuro committed
228

manuele's avatar
manuele committed
229
    Mat labels;
Vlad Shakhuro's avatar
Vlad Shakhuro committed
230 231 232 233 234 235 236 237 238 239 240 241 242 243
    labels_.copyTo(labels);

    bool null_data = true;
    for( int row = 0; row < data.rows; ++row )
    {
        for( int col = 0; col < data.cols; ++col )
            if( data.at<int>(row, col) )
                null_data = false;
    }
    CV_Assert(!null_data);

    int pos_count = count(labels, +1);
    int neg_count = count(labels, -1);

244
    Mat_<float> weights(labels.rows, labels.cols);
Vlad Shakhuro's avatar
Vlad Shakhuro committed
245 246
    float pos_weight = 1.0f / (2 * pos_count);
    float neg_weight = 1.0f / (2 * neg_count);
247 248 249 250 251 252 253 254
    for( int col = 0; col < weights.cols; ++col )
    {
        if( labels.at<int>(0, col) == +1 )
            weights.at<float>(0, col) = pos_weight;
        else
            weights.at<float>(0, col) = neg_weight;
    }

Vlad Shakhuro's avatar
Vlad Shakhuro committed
255 256 257
    vector<int> feature_indices_pool;
    for( int ind = 0; ind < data.rows; ++ind )
        feature_indices_pool.push_back(ind);
258 259

    vector<int> feature_indices;
manuele's avatar
manuele committed
260
    vector<int> visited_features;
261 262 263 264
    Mat_<float> trace = Mat_<float>::zeros(labels.rows, labels.cols);
    stumps_.clear();
    thresholds_.clear();
    for( int i = 0; i < params_.weak_count; ++i)
manuele's avatar
manuele committed
265
    {        
266
        Stump s;
manuele's avatar
manuele committed
267
        int feature_ind = s.train(data, labels, weights, visited_features, use_fast_log);
268
        stumps_.push_back(s);
Vlad Shakhuro's avatar
Vlad Shakhuro committed
269
        int ind = feature_indices_pool[feature_ind];
manuele's avatar
manuele committed
270 271
        //we don't need to erase the feature index anymore, because we ignore them if already visited
        //feature_indices_pool.erase(feature_indices_pool.begin() + feature_ind);
Vlad Shakhuro's avatar
Vlad Shakhuro committed
272
        feature_indices.push_back(ind);
273 274 275 276 277 278 279 280 281 282

        // Recompute weights
        for( int col = 0; col < weights.cols; ++col )
        {
            float h = s.predict(data.at<int>(feature_ind, col));
            trace(0, col) += h;
            int label = labels.at<int>(0, col);
            weights.at<float>(0, col) *= exp(-label * h);
        }

manuele's avatar
manuele committed
283 284 285 286 287 288
        // set to zero row for feature in data
        for(int jc = 0; jc<data.cols; jc++)
        {
          data.at<int>(feature_ind, jc) = 0;
        }
        visited_features.push_back(feature_ind);
Vlad Shakhuro's avatar
Vlad Shakhuro committed
289 290 291



292
        // Normalize weights
Vlad Shakhuro's avatar
Vlad Shakhuro committed
293
        float z = (float)sum(weights)[0];
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
        for( int col = 0; col < weights.cols; ++col)
        {
            weights.at<float>(0, col) /= z;
        }

        // Sort trace
        Mat indices;
        sortIdx(trace, indices, cv::SORT_EVERY_ROW | cv::SORT_ASCENDING);
        Mat new_weights = Mat_<float>::zeros(weights.rows, weights.cols);
        Mat new_labels = Mat_<int>::zeros(labels.rows, labels.cols);
        Mat new_trace;
        for( int col = 0; col < new_weights.cols; ++col )
        {
            new_weights.at<float>(0, col) =
                weights.at<float>(0, indices.at<int>(0, col));
            new_labels.at<int>(0, col) =
                labels.at<int>(0, indices.at<int>(0, col));
        }
manuele's avatar
manuele committed
312 313 314
        
        //sort in-place to save memory
        sort_columns_without_copy(data, indices);
315 316 317
        sort(trace, new_trace, cv::SORT_EVERY_ROW | cv::SORT_ASCENDING);

        // Compute threshold for trace
Vlad Shakhuro's avatar
Vlad Shakhuro committed
318
        /*
319 320
        int col = 0;
        for( int pos_i = 0;
Vlad Shakhuro's avatar
Vlad Shakhuro committed
321
             pos_i < pos_count * params_.alpha && col < new_labels.cols;
322 323
             ++col )
        {
Vlad Shakhuro's avatar
Vlad Shakhuro committed
324
            if( new_labels.at<int>(0, col) == +1 )
325 326
                ++pos_i;
        }
Vlad Shakhuro's avatar
Vlad Shakhuro committed
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
        */

        int cur_pos = 0, cur_neg = 0;
        int max_col = 0;
        for( int col = 0; col < new_labels.cols - 1; ++col ) {
            if (new_labels.at<int>(0, col) == +1 )
                ++cur_pos;
            else
                ++cur_neg;

            float p_neg = cur_neg / (float)neg_count;
            float p_pos = cur_pos / (float)pos_count;
            if( params_.alpha * p_neg > p_pos )
                max_col = col;
        }
342

Vlad Shakhuro's avatar
Vlad Shakhuro committed
343
        thresholds_.push_back(new_trace.at<float>(0, max_col));
344 345

        // Drop samples below threshold
manuele's avatar
manuele committed
346 347
        //uses Rois instead of copyTo to save memory
        data = data(Rect(max_col, 0, data.cols - max_col, data.rows));
Vlad Shakhuro's avatar
Vlad Shakhuro committed
348 349 350 351 352 353 354 355 356 357 358
        new_trace.colRange(max_col, new_trace.cols).copyTo(trace);
        new_weights.colRange(max_col, new_weights.cols).copyTo(weights);
        new_labels.colRange(max_col, new_labels.cols).copyTo(labels);

        pos_count = count(labels, +1);
        neg_count = count(labels, -1);

        if( data.cols < 2 || neg_count == 0)
        {
            break;
        }
359 360 361 362
    }
    return feature_indices;
}

363
float WaldBoostImpl::predict(
364
    const Ptr<FeatureEvaluator>& feature_evaluator) const
365 366
{
    float trace = 0;
Vlad Shakhuro's avatar
Vlad Shakhuro committed
367
    CV_Assert(stumps_.size() == thresholds_.size());
368 369 370 371
    for( size_t i = 0; i < stumps_.size(); ++i )
    {
        int value = feature_evaluator->evaluate(i);
        trace += stumps_[i].predict(value);
manuele's avatar
manuele committed
372
        
373 374 375 376 377
        if( trace < thresholds_[i] )
            return -1;
    }
    return trace;
}
378

379 380 381 382 383 384 385
Ptr<WaldBoost>
createWaldBoost(const WaldBoostParams& params)
{
    return Ptr<WaldBoost>(new WaldBoostImpl(params));
}


386
} /* namespace xobjdetect */
387
} /* namespace cv */