waldboost.cpp 14.8 KB
Newer Older
1
/*
2 3
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,
4 5 6 7 8 9 10
copy or use the software.


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

11 12 13 14 15 16
Copyright (C) 2000-2015, Intel Corporation, all rights reserved.
Copyright (C) 2009-2011, Willow Garage Inc., all rights reserved.
Copyright (C) 2009-2015, NVIDIA Corporation, all rights reserved.
Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved.
Copyright (C) 2015, OpenCV Foundation, all rights reserved.
Copyright (C) 2015, Itseez Inc., all rights reserved.
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
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
35 36 37
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
38 39 40 41 42 43 44 45 46
(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
47 48
namespace cv {
namespace xobjdetect {
manuele's avatar
manuele committed
49

50 51 52
static void compute_cdf(const Mat1b& data,
                        const Mat1f& weights,
                        Mat1f& cdf)
53
{
54 55 56 57 58 59 60 61 62
    for (int i = 0; i < cdf.cols; ++i)
        cdf(0, i) = 0;

    for (int i = 0; i < weights.cols; ++i) {
        cdf(0, data(0, i)) += weights(0, i);
    }

    for (int i = 1; i < cdf.cols; ++i) {
        cdf(0, i) += cdf(0, i - 1);
manuele's avatar
manuele committed
63
    }
64
}
65

66 67
static void compute_min_step(const Mat &data_pos, const Mat &data_neg, size_t n_bins,
                      Mat &data_min, Mat &data_step)
68
{
69 70
    // Check that quantized data will fit in unsigned char
    assert(n_bins <= 256);
71

72
    assert(data_pos.rows == data_neg.rows);
73

74
    Mat reduced_pos, reduced_neg;
75

76 77 78 79
    reduce(data_pos, reduced_pos, 1, CV_REDUCE_MIN);
    reduce(data_neg, reduced_neg, 1, CV_REDUCE_MIN);
    min(reduced_pos, reduced_neg, data_min);
    data_min -= 0.01;
Vlad Shakhuro's avatar
Vlad Shakhuro committed
80

81 82 83 84 85
    Mat data_max;
    reduce(data_pos, reduced_pos, 1, CV_REDUCE_MAX);
    reduce(data_neg, reduced_neg, 1, CV_REDUCE_MAX);
    max(reduced_pos, reduced_neg, data_max);
    data_max += 0.01;
Vlad Shakhuro's avatar
Vlad Shakhuro committed
86

Vlad Shakhuro's avatar
Vlad Shakhuro committed
87
    data_step = (data_max - data_min) / (double)(n_bins - 1);
88
}
89

90
static void quantize_data(Mat &data, Mat1f &data_min, Mat1f &data_step)
Vlad Shakhuro's avatar
Vlad Shakhuro committed
91
{
92 93 94 95 96 97
//#pragma omp parallel for
    for (int col = 0; col < data.cols; ++col) {
        data.col(col) -= data_min;
        data.col(col) /= data_step;
    }
    data.convertTo(data, CV_8U);
Vlad Shakhuro's avatar
Vlad Shakhuro committed
98 99
}

100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
WaldBoost::WaldBoost(int weak_count):
    weak_count_(weak_count),
    thresholds_(),
    alphas_(),
    feature_indices_(),
    polarities_(),
    cascade_thresholds_() {}

WaldBoost::WaldBoost():
    weak_count_(),
    thresholds_(),
    alphas_(),
    feature_indices_(),
    polarities_(),
    cascade_thresholds_() {}

std::vector<int> WaldBoost::get_feature_indices()
117
{
118 119
    return feature_indices_;
}
120

121 122 123 124 125 126 127 128 129 130 131 132
void WaldBoost::detect(Ptr<CvFeatureEvaluator> eval,
            const Mat& img, const std::vector<float>& scales,
            std::vector<Rect>& bboxes, Mat1f& confidences)
{
    bboxes.clear();
    confidences.release();

    Mat resized_img;
    int step = 4;
    float h;
    for (size_t i = 0; i < scales.size(); ++i) {
        float scale = scales[i];
133
        resize(img, resized_img, Size(), scale, scale, INTER_LINEAR_EXACT);
134
        eval->setImage(resized_img, 0, 0, feature_indices_);
Vlad Shakhuro's avatar
Vlad Shakhuro committed
135 136
        int n_rows = (int)(24 / scale);
        int n_cols = (int)(24 / scale);
137 138 139 140 141
        for (int r = 0; r + 24 < resized_img.rows; r += step) {
            for (int c = 0; c + 24 < resized_img.cols; c += step) {
                //eval->setImage(resized_img(Rect(c, r, 24, 24)), 0, 0);
                eval->setWindow(Point(c, r));
                if (predict(eval, &h) == +1) {
Vlad Shakhuro's avatar
Vlad Shakhuro committed
142 143
                    int row = (int)(r / scale);
                    int col = (int)(c / scale);
144 145 146 147 148
                    bboxes.push_back(Rect(col, row, n_cols, n_rows));
                    confidences.push_back(h);
                }
            }
        }
Vlad Shakhuro's avatar
Vlad Shakhuro committed
149
    }
150
    groupRectangles(bboxes, 3, 0.7);
Vlad Shakhuro's avatar
Vlad Shakhuro committed
151 152
}

153 154 155
void WaldBoost::detect(Ptr<CvFeatureEvaluator> eval,
            const Mat& img, const std::vector<float>& scales,
            std::vector<Rect>& bboxes, std::vector<double>& confidences)
Vlad Shakhuro's avatar
Vlad Shakhuro committed
156
{
157 158 159 160 161 162 163 164
    bboxes.clear();
    confidences.clear();

    Mat resized_img;
    int step = 4;
    float h;
    for (size_t i = 0; i < scales.size(); ++i) {
        float scale = scales[i];
165
        resize(img, resized_img, Size(), scale, scale, INTER_LINEAR_EXACT);
166
        eval->setImage(resized_img, 0, 0, feature_indices_);
Vlad Shakhuro's avatar
Vlad Shakhuro committed
167 168
        int n_rows = (int)(24 / scale);
        int n_cols = (int)(24 / scale);
169 170 171 172
        for (int r = 0; r + 24 < resized_img.rows; r += step) {
            for (int c = 0; c + 24 < resized_img.cols; c += step) {
                eval->setWindow(Point(c, r));
                if (predict(eval, &h) == +1) {
Vlad Shakhuro's avatar
Vlad Shakhuro committed
173 174
                    int row = (int)(r / scale);
                    int col = (int)(c / scale);
175 176 177 178 179 180 181 182
                    bboxes.push_back(Rect(col, row, n_cols, n_rows));
                    confidences.push_back(h);
                }
            }
        }
    }
    std::vector<int> levels(bboxes.size(), 0);
    groupRectangles(bboxes, levels, confidences, 3, 0.7);
Vlad Shakhuro's avatar
Vlad Shakhuro committed
183 184
}

185
void WaldBoost::fit(Mat& data_pos, Mat& data_neg)
Vlad Shakhuro's avatar
Vlad Shakhuro committed
186
{
187 188 189 190 191 192 193 194 195 196
    // data_pos: F x N_pos
    // data_neg: F x N_neg
    // every feature corresponds to row
    // every sample corresponds to column
    assert(data_pos.rows >= weak_count_);
    assert(data_pos.rows == data_neg.rows);

    std::vector<bool> feature_ignore;
    for (int i = 0; i < data_pos.rows; ++i) {
        feature_ignore.push_back(false);
197 198
    }

199 200 201 202
    Mat1f pos_weights(1, data_pos.cols, 1.0f / (2 * data_pos.cols));
    Mat1f neg_weights(1, data_neg.cols, 1.0f / (2 * data_neg.cols));
    Mat1f pos_trace(1, data_pos.cols, 0.0f);
    Mat1f neg_trace(1, data_neg.cols, 0.0f);
203

204 205 206 207 208
    bool quantize = false;
    if (data_pos.type() != CV_8U) {
        std::cerr << "quantize" << std::endl;
        quantize = true;
    }
209

210 211 212 213 214 215 216
    Mat1f data_min, data_step;
    int n_bins = 256;
    if (quantize) {
        compute_min_step(data_pos, data_neg, n_bins, data_min, data_step);
        quantize_data(data_pos, data_min, data_step);
        quantize_data(data_neg, data_min, data_step);
    }
Vlad Shakhuro's avatar
Vlad Shakhuro committed
217

218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
    std::cerr << "pos=" << data_pos.cols << " neg=" << data_neg.cols << std::endl;
    for (int i = 0; i < weak_count_; ++i) {
        // Train weak learner with lowest error using weights
        double min_err = DBL_MAX;
        int min_feature_ind = -1;
        int min_polarity = 0;
        int threshold_q = 0;
        float min_threshold = 0;
//#pragma omp parallel for
        for (int feat_i = 0; feat_i < data_pos.rows; ++feat_i) {
            if (feature_ignore[feat_i])
                continue;

            // Construct cdf
            Mat1f pos_cdf(1, n_bins), neg_cdf(1, n_bins);
            compute_cdf(data_pos.row(feat_i), pos_weights, pos_cdf);
            compute_cdf(data_neg.row(feat_i), neg_weights, neg_cdf);

Vlad Shakhuro's avatar
Vlad Shakhuro committed
236
            float neg_total = (float)sum(neg_weights)[0];
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
            Mat1f err_direct = pos_cdf + neg_total - neg_cdf;
            Mat1f err_backward = 1.0f - err_direct;

            int idx1[2], idx2[2];
            double err1, err2;
            minMaxIdx(err_direct, &err1, NULL, idx1);
            minMaxIdx(err_backward, &err2, NULL, idx2);
//#pragma omp critical
            {
            if (min(err1, err2) < min_err) {
                if (err1 < err2) {
                    min_err = err1;
                    min_polarity = +1;
                    threshold_q = idx1[1];
                } else {
                    min_err = err2;
                    min_polarity = -1;
                    threshold_q = idx2[1];
                }
                min_feature_ind = feat_i;
                if (quantize) {
                    min_threshold = data_min(feat_i, 0) + data_step(feat_i, 0) *
                        (threshold_q + .5f);
                } else {
                    min_threshold = threshold_q + .5f;
                }
            }
            }
        }
Vlad Shakhuro's avatar
Vlad Shakhuro committed
266 267


Vlad Shakhuro's avatar
Vlad Shakhuro committed
268
        float alpha = .5f * (float)log((1 - min_err) / min_err);
269 270 271 272 273 274 275 276 277 278 279 280 281 282
        alphas_.push_back(alpha);
        feature_indices_.push_back(min_feature_ind);
        thresholds_.push_back(min_threshold);
        polarities_.push_back(min_polarity);
        feature_ignore[min_feature_ind] = true;

        double loss = 0;
        // Update positive weights
        for (int j = 0; j < data_pos.cols; ++j) {
            int val = data_pos.at<unsigned char>(min_feature_ind, j);
            int label = min_polarity * (val - threshold_q) >= 0 ? +1 : -1;
            pos_weights(0, j) *= exp(-alpha * label);
            pos_trace(0, j) += alpha * label;
            loss += exp(-pos_trace(0, j)) / (2.0f * data_pos.cols);
283 284
        }

285 286 287 288 289 290 291
        // Update negative weights
        for (int j = 0; j < data_neg.cols; ++j) {
            int val = data_neg.at<unsigned char>(min_feature_ind, j);
            int label = min_polarity * (val - threshold_q) >= 0 ? +1 : -1;
            neg_weights(0, j) *= exp(alpha * label);
            neg_trace(0, j) += alpha * label;
            loss += exp(+neg_trace(0, j)) / (2.0f * data_neg.cols);
292
        }
293 294
        double cascade_threshold = -1;
        minMaxIdx(pos_trace, &cascade_threshold);
Vlad Shakhuro's avatar
Vlad Shakhuro committed
295
        cascade_thresholds_.push_back((float)cascade_threshold);
296

297 298 299
        std::cerr << "i=" << std::setw(4) << i;
        std::cerr << " feat=" << std::setw(5) << min_feature_ind;
        std::cerr << " thr=" << std::setw(3) << threshold_q;
300 301
        std::cerr << " casthr=" << std::fixed << std::setprecision(3)
             << cascade_threshold;
302 303 304 305
        std::cerr <<  " alpha=" << std::fixed << std::setprecision(3)
             << alpha << " err=" << std::fixed << std::setprecision(3) << min_err
             << " loss=" << std::scientific << loss << std::endl;

306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
        //int pos = 0;
        //for (int j = 0; j < data_pos.cols; ++j) {
        //    if (pos_trace(0, j) > cascade_threshold - 0.5) {
        //        pos_trace(0, pos) = pos_trace(0, j);
        //        data_pos.col(j).copyTo(data_pos.col(pos));
        //        pos_weights(0, pos) = pos_weights(0, j);
        //        pos += 1;
        //    }
        //}
        //std::cerr << "pos " << data_pos.cols << "/" << pos << std::endl;
        //pos_trace = pos_trace.colRange(0, pos);
        //data_pos = data_pos.colRange(0, pos);
        //pos_weights = pos_weights.colRange(0, pos);

        int pos = 0;
        for (int j = 0; j < data_neg.cols; ++j) {
            if (neg_trace(0, j) > cascade_threshold - 0.5) {
                neg_trace(0, pos) = neg_trace(0, j);
                data_neg.col(j).copyTo(data_neg.col(pos));
                neg_weights(0, pos) = neg_weights(0, j);
                pos += 1;
            }
        }
        std::cerr << "neg " << data_neg.cols << "/" << pos << std::endl;
        neg_trace = neg_trace.colRange(0, pos);
        data_neg = data_neg.colRange(0, pos);
        neg_weights = neg_weights.colRange(0, pos);


335 336 337 338
        if (loss < 1e-50 || min_err > 0.5) {
            std::cerr << "Stopping early" << std::endl;
            weak_count_ = i + 1;
            break;
Vlad Shakhuro's avatar
Vlad Shakhuro committed
339
        }
340

341 342 343 344 345 346
        // Normalize weights
        double z = (sum(pos_weights) + sum(neg_weights))[0];
        pos_weights /= z;
        neg_weights /= z;
    }
}
Vlad Shakhuro's avatar
Vlad Shakhuro committed
347

348 349 350
int WaldBoost::predict(Ptr<CvFeatureEvaluator> eval, float *h) const
{
    assert(feature_indices_.size() == size_t(weak_count_));
351
    assert(cascade_thresholds_.size() == size_t(weak_count_));
352
    float res = 0;
353 354
    int count = weak_count_;
    for (int i = 0; i < count; ++i) {
Vlad Shakhuro's avatar
Vlad Shakhuro committed
355
        float val = (*eval)(feature_indices_[i]);
356 357
        int label = polarities_[i] * (val - thresholds_[i]) > 0 ? +1: -1;
        res += alphas_[i] * label;
358
        if (res < cascade_thresholds_[i]) {
359
            return -1;
Vlad Shakhuro's avatar
Vlad Shakhuro committed
360
        }
361
    }
362
    *h = res;
363
    return res > cascade_thresholds_[count - 1] ? +1 : -1;
364 365
}

366
void WaldBoost::write(FileStorage &fs) const
367
{
368
    fs << "{";
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
    fs << "waldboost_params"
       << "{" << "weak_count" << weak_count_ << "}";

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

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

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

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

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

    fs << "}";
398
}
399

400
void WaldBoost::read(const FileNode &node)
401
{
402
    weak_count_ = (int)(node["waldboost_params"]["weak_count"]);
403 404 405 406 407 408
    thresholds_.resize(weak_count_);
    alphas_.resize(weak_count_);
    polarities_.resize(weak_count_);
    cascade_thresholds_.resize(weak_count_);
    feature_indices_.resize(weak_count_);

409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
    FileNodeIterator n;

    n = node["thresholds"].begin();
    for (int i = 0; i < weak_count_; ++i, ++n)
        *n >> thresholds_[i];

    n = node["alphas"].begin();
    for (int i = 0; i < weak_count_; ++i, ++n)
        *n >> alphas_[i];

    n = node["polarities"].begin();
    for (int i = 0; i < weak_count_; ++i, ++n)
        *n >> polarities_[i];

    n = node["cascade_thresholds"].begin();
    for (int i = 0; i < weak_count_; ++i, ++n)
        *n >> cascade_thresholds_[i];

    n = node["feature_indices"].begin();
    for (int i = 0; i < weak_count_; ++i, ++n)
        *n >> feature_indices_[i];
430 431
}

432 433 434 435 436 437 438 439 440
void WaldBoost::reset(int weak_count)
{
    weak_count_ = weak_count;
    thresholds_.clear();
    alphas_.clear();
    feature_indices_.clear();
    polarities_.clear();
    cascade_thresholds_.clear();
}
441

442 443 444 445
WaldBoost::~WaldBoost()
{
}

Vlad Shakhuro's avatar
Vlad Shakhuro committed
446 447
}
}