bgfg_gmg.cpp 17.4 KB
Newer Older
1 2 3 4 5 6 7 8 9
/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  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.
//
//
10
//                          License Agreement
11
//                For Open Source Computer Vision Library
12 13
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
14
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
15 16 17 18 19 20 21 22 23 24 25 26
// 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:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's 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.
//
27
//   * The name of the copyright holders may not be used to endorse or promote products
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
//     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 the Intel Corporation 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.
//
//M*/

/*
 * This class implements an algorithm described in "Visual Tracking of Human Visitors under
 * Variable-Lighting Conditions for a Responsive Audio Art Installation," A. Godbehere,
 * A. Matsukawa, K. Goldberg, American Control Conference, Montreal, June 2012.
 *
 * Prepared and integrated by Andrew B. Godbehere.
 */

#include "precomp.hpp"

53 54 55 56 57 58 59 60 61 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 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
namespace cv
{

class CV_EXPORTS BackgroundSubtractorGMGImpl : public BackgroundSubtractorGMG
{
public:
    BackgroundSubtractorGMGImpl();
    ~BackgroundSubtractorGMGImpl();
    virtual AlgorithmInfo* info() const { return 0; }

    /**
     * Validate parameters and set up data structures for appropriate image size.
     * Must call before running on data.
     * @param frameSize input frame size
     * @param min       minimum value taken on by pixels in image sequence. Usually 0
     * @param max       maximum value taken on by pixels in image sequence. e.g. 1.0 or 255
     */
    void initialize(Size frameSize, double minVal, double maxVal);

    /**
     * Performs single-frame background subtraction and builds up a statistical background image
     * model.
     * @param image Input image
     * @param fgmask Output mask image representing foreground and background pixels
     */
    virtual void apply(InputArray image, OutputArray fgmask, double learningRate=-1.0);

    /**
     * Releases all inner buffers.
     */
    void release();

    virtual int getMaxFeatures() const { return maxFeatures; }
    virtual void setMaxFeatures(int _maxFeatures) { maxFeatures = _maxFeatures; }

    virtual double getDefaultLearningRate() const { return learningRate; }
    virtual void setDefaultLearningRate(double lr) { learningRate = lr; }

    virtual int getNumFrames() const { return numInitializationFrames; }
    virtual void setNumFrames(int nframes) { numInitializationFrames = nframes; }

    virtual int getQuantizationLevels() const { return quantizationLevels; }
    virtual void setQuantizationLevels(int nlevels) { quantizationLevels = nlevels; }

    virtual double getBackgroundPrior() const { return backgroundPrior; }
    virtual void setBackgroundPrior(double bgprior) { backgroundPrior = bgprior; }

    virtual int getSmoothingRadius() const { return smoothingRadius; }
    virtual void setSmoothingRadius(int radius) { smoothingRadius = radius; }

    virtual double getDecisionThreshold() const { return decisionThreshold; }
    virtual void setDecisionThreshold(double thresh) { decisionThreshold = thresh; }

    virtual bool getUpdateBackgroundModel() const { return updateBackgroundModel; }
    virtual void setUpdateBackgroundModel(bool update) { updateBackgroundModel = update; }

    virtual double getMinVal() const { return minVal_; }
    virtual void setMinVal(double val) { minVal_ = val; }

    virtual double getMaxVal() const  { return maxVal_; }
    virtual void setMaxVal(double val)  { maxVal_ = val; }

    virtual void getBackgroundImage(OutputArray) const
    {
        CV_Error( CV_StsNotImplemented, "" );
    }

    //! Total number of distinct colors to maintain in histogram.
    int     maxFeatures;
    //! Set between 0.0 and 1.0, determines how quickly features are "forgotten" from histograms.
    double  learningRate;
    //! Number of frames of video to use to initialize histograms.
    int     numInitializationFrames;
    //! Number of discrete levels in each channel to be used in histograms.
    int     quantizationLevels;
    //! Prior probability that any given pixel is a background pixel. A sensitivity parameter.
    double  backgroundPrior;
    //! Value above which pixel is determined to be FG.
    double  decisionThreshold;
    //! Smoothing radius, in pixels, for cleaning up FG image.
    int     smoothingRadius;
    //! Perform background model update
    bool updateBackgroundModel;

private:
    double maxVal_;
    double minVal_;

    Size frameSize_;
    int frameNum_;

    Mat_<int> nfeatures_;
    Mat_<unsigned int> colors_;
    Mat_<float> weights_;

    Mat buf_;
};

BackgroundSubtractorGMGImpl::BackgroundSubtractorGMGImpl()
152 153 154 155 156 157 158 159 160 161 162
{
    /*
     * Default Parameter Values. Override with algorithm "set" method.
     */
    maxFeatures = 64;
    learningRate = 0.025;
    numInitializationFrames = 120;
    quantizationLevels = 16;
    backgroundPrior = 0.8;
    decisionThreshold = 0.8;
    smoothingRadius = 7;
163
    updateBackgroundModel = true;
164
    minVal_ = maxVal_ = 0;
165
}
166

167
BackgroundSubtractorGMGImpl::~BackgroundSubtractorGMGImpl()
168
{
169
}
170

171
void BackgroundSubtractorGMGImpl::initialize(Size frameSize, double minVal, double maxVal)
172
{
173
    CV_Assert(minVal < maxVal);
174 175 176 177 178
    CV_Assert(maxFeatures > 0);
    CV_Assert(learningRate >= 0.0 && learningRate <= 1.0);
    CV_Assert(numInitializationFrames >= 1);
    CV_Assert(quantizationLevels >= 1 && quantizationLevels <= 255);
    CV_Assert(backgroundPrior >= 0.0 && backgroundPrior <= 1.0);
179

180 181
    minVal_ = minVal;
    maxVal_ = maxVal;
182

183 184
    frameSize_ = frameSize;
    frameNum_ = 0;
185

186 187 188
    nfeatures_.create(frameSize_);
    colors_.create(frameSize_.area(), maxFeatures);
    weights_.create(frameSize_.area(), maxFeatures);
189

190
    nfeatures_.setTo(Scalar::all(0));
191 192
}

193
namespace
194
{
195
    float findFeature(unsigned int color, const unsigned int* colors, const float* weights, int nfeatures)
196
    {
197
        for (int i = 0; i < nfeatures; ++i)
198
        {
199 200
            if (color == colors[i])
                return weights[i];
201 202
        }

203 204 205
        // not in histogram, so return 0.
        return 0.0f;
    }
206

207
    void normalizeHistogram(float* weights, int nfeatures)
208
    {
209 210 211
        float total = 0.0f;
        for (int i = 0; i < nfeatures; ++i)
            total += weights[i];
212

213
        if (total != 0.0f)
214
        {
215 216
            for (int i = 0; i < nfeatures; ++i)
                weights[i] /= total;
217 218 219
        }
    }

220
    bool insertFeature(unsigned int color, float weight, unsigned int* colors, float* weights, int& nfeatures, int maxFeatures)
221
    {
222 223
        int idx = -1;
        for (int i = 0; i < nfeatures; ++i)
224
        {
225
            if (color == colors[i])
226
            {
227 228 229 230
                // feature in histogram
                weight += weights[i];
                idx = i;
                break;
231 232
            }
        }
233

234 235 236
        if (idx >= 0)
        {
            // move feature to beginning of list
237

238
            ::memmove(colors + 1, colors, idx * sizeof(unsigned int));
239
            ::memmove(weights + 1, weights, idx * sizeof(float));
240

241 242 243 244 245 246
            colors[0] = color;
            weights[0] = weight;
        }
        else if (nfeatures == maxFeatures)
        {
            // discard oldest feature
247

248
            ::memmove(colors + 1, colors, (nfeatures - 1) * sizeof(unsigned int));
249
            ::memmove(weights + 1, weights, (nfeatures - 1) * sizeof(float));
250

251 252 253 254 255 256 257
            colors[0] = color;
            weights[0] = weight;
        }
        else
        {
            colors[nfeatures] = color;
            weights[nfeatures] = weight;
258

259
            ++nfeatures;
260

261
            return true;
262 263
        }

264 265
        return false;
    }
266 267
}

268
namespace
269
{
270 271
    template <typename T> struct Quantization
    {
272
        static unsigned int apply(const void* src_, int x, int cn, double minVal, double maxVal, int quantizationLevels)
273
        {
274
            const T* src = static_cast<const T*>(src_);
275 276
            src += x * cn;

277
            unsigned int res = 0;
278 279 280 281
            for (int i = 0, shift = 0; i < cn; ++i, ++src, shift += 8)
                res |= static_cast<int>((*src - minVal) * quantizationLevels / (maxVal - minVal)) << shift;

            return res;
282
        }
283 284
    };

285
    class GMG_LoopBody : public ParallelLoopBody
286
    {
287
    public:
288
        GMG_LoopBody(const Mat& frame, const Mat& fgmask, const Mat_<int>& nfeatures, const Mat_<unsigned int>& colors, const Mat_<float>& weights,
289
                     int maxFeatures, double learningRate, int numInitializationFrames, int quantizationLevels, double backgroundPrior, double decisionThreshold,
290
                     double maxVal, double minVal, int frameNum, bool updateBackgroundModel) :
291
            frame_(frame), fgmask_(fgmask), nfeatures_(nfeatures), colors_(colors), weights_(weights),
292 293 294
            maxFeatures_(maxFeatures), learningRate_(learningRate), numInitializationFrames_(numInitializationFrames), quantizationLevels_(quantizationLevels),
            backgroundPrior_(backgroundPrior), decisionThreshold_(decisionThreshold), updateBackgroundModel_(updateBackgroundModel),
            maxVal_(maxVal), minVal_(minVal), frameNum_(frameNum)
295 296
        {
        }
297

298
        void operator() (const Range& range) const;
299 300

    private:
301
        Mat frame_;
302

303
        mutable Mat_<uchar> fgmask_;
304

305 306 307
        mutable Mat_<int> nfeatures_;
        mutable Mat_<unsigned int> colors_;
        mutable Mat_<float> weights_;
308 309 310 311 312 313 314

        int     maxFeatures_;
        double  learningRate_;
        int     numInitializationFrames_;
        int     quantizationLevels_;
        double  backgroundPrior_;
        double  decisionThreshold_;
315
        bool updateBackgroundModel_;
316 317 318

        double maxVal_;
        double minVal_;
319
        int frameNum_;
320 321
    };

322
    void GMG_LoopBody::operator() (const Range& range) const
323
    {
324
        typedef unsigned int (*func_t)(const void* src_, int x, int cn, double minVal, double maxVal, int quantizationLevels);
325
        static const func_t funcs[] =
326
        {
327 328 329 330 331 332 333
            Quantization<uchar>::apply,
            Quantization<schar>::apply,
            Quantization<ushort>::apply,
            Quantization<short>::apply,
            Quantization<int>::apply,
            Quantization<float>::apply,
            Quantization<double>::apply
334 335
        };

336
        const func_t func = funcs[frame_.depth()];
337 338
        CV_Assert(func != 0);

339 340
        const int cn = frame_.channels();

341
        for (int y = range.start, featureIdx = y * frame_.cols; y < range.end; ++y)
342
        {
343 344 345 346 347 348 349
            const uchar* frame_row = frame_.ptr(y);
            int* nfeatures_row = nfeatures_[y];
            uchar* fgmask_row = fgmask_[y];

            for (int x = 0; x < frame_.cols; ++x, ++featureIdx)
            {
                int nfeatures = nfeatures_row[x];
350
                unsigned int* colors = colors_[featureIdx];
351 352
                float* weights = weights_[featureIdx];

353
                unsigned int newFeatureColor = func(frame_row, x, cn, minVal_, maxVal_, quantizationLevels_);
354 355 356

                bool isForeground = false;

357
                if (frameNum_ >= numInitializationFrames_)
358 359 360 361 362 363 364 365 366 367
                {
                    // typical operation

                    const double weight = findFeature(newFeatureColor, colors, weights, nfeatures);

                    // see Godbehere, Matsukawa, Goldberg (2012) for reasoning behind this implementation of Bayes rule
                    const double posterior = (weight * backgroundPrior_) / (weight * backgroundPrior_ + (1.0 - weight) * (1.0 - backgroundPrior_));

                    isForeground = ((1.0 - posterior) > decisionThreshold_);

368
                    // update histogram.
369

370 371 372
                    if (updateBackgroundModel_)
                    {
                        for (int i = 0; i < nfeatures; ++i)
373
                            weights[i] *= (float)(1.0f - learningRate_);
374

375
                        bool inserted = insertFeature(newFeatureColor, (float)learningRate_, colors, weights, nfeatures, maxFeatures_);
376

377 378 379 380 381
                        if (inserted)
                        {
                            normalizeHistogram(weights, nfeatures);
                            nfeatures_row[x] = nfeatures;
                        }
382
                    }
383
                }
384
                else if (updateBackgroundModel_)
385
                {
386
                    // training-mode update
387

388
                    insertFeature(newFeatureColor, 1.0f, colors, weights, nfeatures, maxFeatures_);
389

390
                    if (frameNum_ == numInitializationFrames_ - 1)
391 392 393
                        normalizeHistogram(weights, nfeatures);
                }

A
Andrey Kamaev 已提交
394
                fgmask_row[x] = (uchar)(-(schar)isForeground);
395
            }
396 397
        }
    }
398 399
}

400
void BackgroundSubtractorGMGImpl::apply(InputArray _frame, OutputArray _fgmask, double newLearningRate)
401
{
402
    Mat frame = _frame.getMat();
403

404 405
    CV_Assert(frame.depth() == CV_8U || frame.depth() == CV_16U || frame.depth() == CV_32F);
    CV_Assert(frame.channels() == 1 || frame.channels() == 3 || frame.channels() == 4);
406

407
    if (newLearningRate != -1.0)
408
    {
409 410
        CV_Assert(newLearningRate >= 0.0 && newLearningRate <= 1.0);
        learningRate = newLearningRate;
411
    }
412

413
    if (frame.size() != frameSize_)
414 415 416 417 418 419 420 421 422 423
    {
        double minval = minVal_;
        double maxval = maxVal_;
        if( minVal_ == 0 && maxVal_ == 0 )
        {
            minval = 0;
            maxval = frame.depth() == CV_8U ? 255.0 : frame.depth() == CV_16U ? std::numeric_limits<ushort>::max() : 1.0;
        }
        initialize(frame.size(), minval, maxval);
    }
424

425
    _fgmask.create(frameSize_, CV_8UC1);
426
    Mat fgmask = _fgmask.getMat();
427

428 429
    GMG_LoopBody body(frame, fgmask, nfeatures_, colors_, weights_,
                      maxFeatures, learningRate, numInitializationFrames, quantizationLevels, backgroundPrior, decisionThreshold,
430
                      maxVal_, minVal_, frameNum_, updateBackgroundModel);
431
    parallel_for_(Range(0, frame.rows), body, frame.total()/(double)(1<<16));
432

433 434
    if (smoothingRadius > 0)
    {
435
        medianBlur(fgmask, buf_, smoothingRadius);
436
        swap(fgmask, buf_);
437
    }
438

439 440 441
    // keep track of how many frames we have processed
    ++frameNum_;
}
442

443
void BackgroundSubtractorGMGImpl::release()
444
{
445
    frameSize_ = Size();
446 447 448 449 450 451

    nfeatures_.release();
    colors_.release();
    weights_.release();
    buf_.release();
}
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490


Ptr<BackgroundSubtractorGMG> createBackgroundSubtractorGMG(int initializationFrames, double decisionThreshold)
{
    Ptr<BackgroundSubtractorGMG> bgfg = new BackgroundSubtractorGMGImpl;
    bgfg->setNumFrames(initializationFrames);
    bgfg->setDecisionThreshold(decisionThreshold);

    return bgfg;
}

/*
 ///////////////////////////////////////////////////////////////////////////////////////////////////////////

 CV_INIT_ALGORITHM(BackgroundSubtractorGMG, "BackgroundSubtractor.GMG",
 obj.info()->addParam(obj, "maxFeatures", obj.maxFeatures,false,0,0,
 "Maximum number of features to store in histogram. Harsh enforcement of sparsity constraint.");
 obj.info()->addParam(obj, "learningRate", obj.learningRate,false,0,0,
 "Adaptation rate of histogram. Close to 1, slow adaptation. Close to 0, fast adaptation, features forgotten quickly.");
 obj.info()->addParam(obj, "initializationFrames", obj.numInitializationFrames,false,0,0,
 "Number of frames to use to initialize histograms of pixels.");
 obj.info()->addParam(obj, "quantizationLevels", obj.quantizationLevels,false,0,0,
 "Number of discrete colors to be used in histograms. Up-front quantization.");
 obj.info()->addParam(obj, "backgroundPrior", obj.backgroundPrior,false,0,0,
 "Prior probability that each individual pixel is a background pixel.");
 obj.info()->addParam(obj, "smoothingRadius", obj.smoothingRadius,false,0,0,
 "Radius of smoothing kernel to filter noise from FG mask image.");
 obj.info()->addParam(obj, "decisionThreshold", obj.decisionThreshold,false,0,0,
 "Threshold for FG decision rule. Pixel is FG if posterior probability exceeds threshold.");
 obj.info()->addParam(obj, "updateBackgroundModel", obj.updateBackgroundModel,false,0,0,
 "Perform background model update.");
 obj.info()->addParam(obj, "minVal", obj.minVal_,false,0,0,
 "Minimum of the value range (mostly for regression testing)");
 obj.info()->addParam(obj, "maxVal", obj.maxVal_,false,0,0,
 "Maximum of the value range (mostly for regression testing)");
 );
*/

}