wbdetector.cpp 7.32 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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
/*
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) 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.
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"

using std::cerr;
using std::endl;
using std::vector;
using std::string;

namespace cv {
namespace xobjdetect {

static vector<Mat> sample_patches(
        const string& path,
        int n_rows,
        int n_cols,
Vlad Shakhuro's avatar
Vlad Shakhuro committed
59
        size_t n_patches)
60 61 62 63
{
    vector<String> filenames;
    glob(path, filenames);
    vector<Mat> patches;
Vlad Shakhuro's avatar
Vlad Shakhuro committed
64
    size_t patch_count = 0;
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
    for (size_t i = 0; i < filenames.size(); ++i) {
        Mat img = imread(filenames[i], CV_LOAD_IMAGE_GRAYSCALE);
        for (int row = 0; row + n_rows < img.rows; row += n_rows) {
            for (int col = 0; col + n_cols < img.cols; col += n_cols) {
                patches.push_back(img(Rect(col, row, n_cols, n_rows)).clone());
                patch_count += 1;
                if (patch_count == n_patches) {
                    goto sampling_finished;
                }
            }
        }
    }
sampling_finished:
    return patches;
}

static vector<Mat> read_imgs(const string& path)
{
    vector<String> filenames;
    glob(path, filenames);
    vector<Mat> imgs;
    for (size_t i = 0; i < filenames.size(); ++i) {
        imgs.push_back(imread(filenames[i], CV_LOAD_IMAGE_GRAYSCALE));
    }
    return imgs;
}

92 93 94 95 96 97 98 99 100 101 102 103
void WBDetectorImpl::read(const FileNode& node)
{
    boost_.read(node);
}


void WBDetectorImpl::write(FileStorage &fs) const
{
    boost_.write(fs);
}

void WBDetectorImpl::train(
104 105 106 107 108
    const string& pos_samples_path,
    const string& neg_imgs_path)
{

    vector<Mat> pos_imgs = read_imgs(pos_samples_path);
109
    vector<Mat> neg_imgs = sample_patches(neg_imgs_path, 24, 24, pos_imgs.size() * 10);
110 111 112 113 114 115 116

    assert(pos_imgs.size());
    assert(neg_imgs.size());

    int n_features;
    Mat pos_data, neg_data;

Vlad Shakhuro's avatar
Vlad Shakhuro committed
117 118
    Ptr<CvFeatureEvaluator> eval = CvFeatureEvaluator::create();
    eval->init(CvFeatureParams::create(), 1, Size(24, 24));
119 120
    n_features = eval->getNumFeatures();

121
    const int stages[] = {64, 128, 256, 512, 1024};
122
    const int stage_count = sizeof(stages) / sizeof(*stages);
Vlad Shakhuro's avatar
Vlad Shakhuro committed
123
    const int stage_neg = (int)(pos_imgs.size() * 5);
124
    const int max_per_image = 100;
125

Vlad Shakhuro's avatar
Vlad Shakhuro committed
126
    const float scales_arr[] = {.3f, .4f, .5f, .6f, .7f, .8f, .9f, 1.0f};
127 128 129 130 131 132 133 134 135 136 137
    const vector<float> scales(scales_arr,
            scales_arr + sizeof(scales_arr) / sizeof(*scales_arr));

    vector<String> neg_filenames;
    glob(neg_imgs_path, neg_filenames);


    for (int i = 0; i < stage_count; ++i) {

        cerr << "compute features" << endl;

Vlad Shakhuro's avatar
Vlad Shakhuro committed
138 139
        pos_data = Mat1b(n_features, (int)pos_imgs.size());
        neg_data = Mat1b(n_features, (int)neg_imgs.size());
140 141

        for (size_t k = 0; k < pos_imgs.size(); ++k) {
142
            eval->setImage(pos_imgs[k], +1, 0, boost_.get_feature_indices());
143
            for (int j = 0; j < n_features; ++j) {
Vlad Shakhuro's avatar
Vlad Shakhuro committed
144
                pos_data.at<uchar>(j, (int)k) = (uchar)(*eval)(j);
145 146 147 148
            }
        }

        for (size_t k = 0; k < neg_imgs.size(); ++k) {
149
            eval->setImage(neg_imgs[k], 0, 0, boost_.get_feature_indices());
150
            for (int j = 0; j < n_features; ++j) {
Vlad Shakhuro's avatar
Vlad Shakhuro committed
151
                neg_data.at<uchar>(j, (int)k) = (uchar)(*eval)(j);
152 153 154 155
            }
        }


156 157
        boost_.reset(stages[i]);
        boost_.fit(pos_data, neg_data);
158 159 160 161 162 163 164 165 166 167 168 169 170

        if (i + 1 == stage_count) {
            break;
        }

        int bootstrap_count = 0;
        size_t img_i = 0;
        for (; img_i < neg_filenames.size(); ++img_i) {
            cerr << "win " << bootstrap_count << "/" << stage_neg
                 << " img " << (img_i + 1) << "/" << neg_filenames.size() << "\r";
            Mat img = imread(neg_filenames[img_i], CV_LOAD_IMAGE_GRAYSCALE);
            vector<Rect> bboxes;
            Mat1f confidences;
171
            boost_.detect(eval, img, scales, bboxes, confidences);
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195

            if (confidences.rows > 0) {
                Mat1i indices;
                sortIdx(confidences, indices,
                        CV_SORT_EVERY_COLUMN + CV_SORT_DESCENDING);

                int win_count = min(max_per_image, confidences.rows);
                win_count = min(win_count, stage_neg - bootstrap_count);
                Mat window;
                for (int k = 0; k < win_count; ++k) {
                    resize(img(bboxes[indices(k, 0)]), window, Size(24, 24));
                    neg_imgs.push_back(window.clone());
                    bootstrap_count += 1;
                }
                if (bootstrap_count >= stage_neg) {
                    break;
                }
            }
        }
        cerr << "bootstrapped " << bootstrap_count << " windows from "
             << (img_i + 1) << " images" << endl;
    }
}

196
void WBDetectorImpl::detect(
197 198 199 200 201 202 203 204
    const Mat& img,
    vector<Rect> &bboxes,
    vector<double> &confidences)
{
    Mat test_img = img.clone();
    bboxes.clear();
    confidences.clear();
    vector<float> scales;
Vlad Shakhuro's avatar
Vlad Shakhuro committed
205
    for (float scale = 0.2f; scale < 1.2f; scale *= 1.1f) {
206 207
        scales.push_back(scale);
    }
Vlad Shakhuro's avatar
Vlad Shakhuro committed
208 209
    Ptr<CvFeatureParams> params = CvFeatureParams::create();
    Ptr<CvFeatureEvaluator> eval = CvFeatureEvaluator::create();
210
    eval->init(params, 1, Size(24, 24));
211
    boost_.detect(eval, img, scales, bboxes, confidences);
212 213 214
    assert(confidences.size() == bboxes.size());
}

215 216
Ptr<WBDetector>
WBDetector::create()
217 218 219 220
{
    return Ptr<WBDetector>(new WBDetectorImpl());
}

221 222
}
}