bgfg_gmg.cpp 11.5 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 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
//
// Copyright (C) 2000, Intel Corporation, 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:
//
//   * 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.
//
//   * The name of Intel Corporation may not 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 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"

51
cv::BackgroundSubtractorGMG::BackgroundSubtractorGMG()
52 53 54 55 56 57 58 59 60 61 62
{
    /*
     * 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;
63
    updateBackgroundModel = true;
64
}
65

66
cv::BackgroundSubtractorGMG::~BackgroundSubtractorGMG()
67
{
68
}
69

70 71 72 73 74 75 76 77
void cv::BackgroundSubtractorGMG::initialize(cv::Size frameSize, double min, double max)
{
    CV_Assert(min < max);
    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);
78

79 80
    minVal_ = min;
    maxVal_ = max;
81

82 83
    frameSize_ = frameSize;
    frameNum_ = 0;
84

85 86 87
    nfeatures_.create(frameSize_);
    colors_.create(frameSize_.area(), maxFeatures);
    weights_.create(frameSize_.area(), maxFeatures);
88

89
    nfeatures_.setTo(cv::Scalar::all(0));
90 91
}

92
namespace
93
{
94
    float findFeature(uint color, const uint* colors, const float* weights, int nfeatures)
95
    {
96
        for (int i = 0; i < nfeatures; ++i)
97
        {
98 99
            if (color == colors[i])
                return weights[i];
100 101
        }

102 103 104
        // not in histogram, so return 0.
        return 0.0f;
    }
105

106
    void normalizeHistogram(float* weights, int nfeatures)
107
    {
108 109 110
        float total = 0.0f;
        for (int i = 0; i < nfeatures; ++i)
            total += weights[i];
111

112
        if (total != 0.0f)
113
        {
114 115
            for (int i = 0; i < nfeatures; ++i)
                weights[i] /= total;
116 117 118
        }
    }

119
    bool insertFeature(uint color, float weight, uint* colors, float* weights, int& nfeatures, int maxFeatures)
120
    {
121 122
        int idx = -1;
        for (int i = 0; i < nfeatures; ++i)
123
        {
124
            if (color == colors[i])
125
            {
126 127 128 129
                // feature in histogram
                weight += weights[i];
                idx = i;
                break;
130 131
            }
        }
132

133 134 135
        if (idx >= 0)
        {
            // move feature to beginning of list
136

137
            ::memmove(colors + 1, colors, idx * sizeof(uint));
138
            ::memmove(weights + 1, weights, idx * sizeof(float));
139

140 141 142 143 144 145
            colors[0] = color;
            weights[0] = weight;
        }
        else if (nfeatures == maxFeatures)
        {
            // discard oldest feature
146

147
            ::memmove(colors + 1, colors, (nfeatures - 1) * sizeof(uint));
148
            ::memmove(weights + 1, weights, (nfeatures - 1) * sizeof(float));
149

150 151 152 153 154 155 156
            colors[0] = color;
            weights[0] = weight;
        }
        else
        {
            colors[nfeatures] = color;
            weights[nfeatures] = weight;
157

158
            ++nfeatures;
159

160
            return true;
161 162
        }

163 164
        return false;
    }
165 166
}

167
namespace
168
{
169 170
    template <typename T> struct Quantization
    {
171
        static uint apply(const void* src_, int x, int cn, double minVal, double maxVal, int quantizationLevels)
172
        {
173
            const T* src = static_cast<const T*>(src_);
174 175 176 177 178 179 180
            src += x * cn;

            uint res = 0;
            for (int i = 0, shift = 0; i < cn; ++i, ++src, shift += 8)
                res |= static_cast<int>((*src - minVal) * quantizationLevels / (maxVal - minVal)) << shift;

            return res;
181
        }
182 183 184
    };

    class GMG_LoopBody : public cv::ParallelLoopBody
185
    {
186
    public:
187
        GMG_LoopBody(const cv::Mat& frame, const cv::Mat& fgmask, const cv::Mat_<int>& nfeatures, const cv::Mat_<uint>& colors, const cv::Mat_<float>& weights,
188
                     int maxFeatures, double learningRate, int numInitializationFrames, int quantizationLevels, double backgroundPrior, double decisionThreshold,
189
                     double maxVal, double minVal, int frameNum, bool updateBackgroundModel) :
190
            frame_(frame), fgmask_(fgmask), nfeatures_(nfeatures), colors_(colors), weights_(weights),
191 192 193
            maxFeatures_(maxFeatures), learningRate_(learningRate), numInitializationFrames_(numInitializationFrames), quantizationLevels_(quantizationLevels),
            backgroundPrior_(backgroundPrior), decisionThreshold_(decisionThreshold), updateBackgroundModel_(updateBackgroundModel),
            maxVal_(maxVal), minVal_(minVal), frameNum_(frameNum)
194 195
        {
        }
196 197 198 199 200 201 202 203 204

        void operator() (const cv::Range& range) const;

    private:
        const cv::Mat frame_;

        mutable cv::Mat_<uchar> fgmask_;

        mutable cv::Mat_<int> nfeatures_;
205
        mutable cv::Mat_<uint> colors_;
206 207 208 209 210 211 212 213
        mutable cv::Mat_<float> weights_;

        int     maxFeatures_;
        double  learningRate_;
        int     numInitializationFrames_;
        int     quantizationLevels_;
        double  backgroundPrior_;
        double  decisionThreshold_;
214
        bool updateBackgroundModel_;
215 216 217

        double maxVal_;
        double minVal_;
218
        int frameNum_;
219 220 221 222
    };

    void GMG_LoopBody::operator() (const cv::Range& range) const
    {
223 224
        typedef uint (*func_t)(const void* src_, int x, int cn, double minVal, double maxVal, int quantizationLevels);
        static const func_t funcs[] =
225
        {
226 227 228 229 230 231 232
            Quantization<uchar>::apply,
            Quantization<schar>::apply,
            Quantization<ushort>::apply,
            Quantization<short>::apply,
            Quantization<int>::apply,
            Quantization<float>::apply,
            Quantization<double>::apply
233 234
        };

235
        const func_t func = funcs[frame_.depth()];
236 237
        CV_Assert(func != 0);

238 239
        const int cn = frame_.channels();

240
        for (int y = range.start, featureIdx = y * frame_.cols; y < range.end; ++y)
241
        {
242 243 244 245 246 247 248
            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];
249
                uint* colors = colors_[featureIdx];
250 251
                float* weights = weights_[featureIdx];

252
                uint newFeatureColor = func(frame_row, x, cn, minVal_, maxVal_, quantizationLevels_);
253 254 255

                bool isForeground = false;

256
                if (frameNum_ >= numInitializationFrames_)
257 258 259 260 261 262 263 264 265 266
                {
                    // 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_);

267
                    // update histogram.
268

269 270 271 272
                    if (updateBackgroundModel_)
                    {
                        for (int i = 0; i < nfeatures; ++i)
                            weights[i] *= 1.0f - learningRate_;
273

274
                        bool inserted = insertFeature(newFeatureColor, learningRate_, colors, weights, nfeatures, maxFeatures_);
275

276 277 278 279 280
                        if (inserted)
                        {
                            normalizeHistogram(weights, nfeatures);
                            nfeatures_row[x] = nfeatures;
                        }
281
                    }
282
                }
283
                else if (updateBackgroundModel_)
284
                {
285
                    // training-mode update
286

287
                    insertFeature(newFeatureColor, 1.0f, colors, weights, nfeatures, maxFeatures_);
288

289
                    if (frameNum_ == numInitializationFrames_ - 1)
290 291 292
                        normalizeHistogram(weights, nfeatures);
                }

293
                fgmask_row[x] = (uchar)(-isForeground);
294
            }
295 296
        }
    }
297 298
}

299
void cv::BackgroundSubtractorGMG::operator ()(InputArray _frame, OutputArray _fgmask, double newLearningRate)
300
{
301
    cv::Mat frame = _frame.getMat();
302

303 304
    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);
305

306
    if (newLearningRate != -1.0)
307
    {
308 309
        CV_Assert(newLearningRate >= 0.0 && newLearningRate <= 1.0);
        learningRate = newLearningRate;
310
    }
311

312 313
    if (frame.size() != frameSize_)
        initialize(frame.size(), 0.0, frame.depth() == CV_8U ? 255.0 : frame.depth() == CV_16U ? std::numeric_limits<ushort>::max() : 1.0);
314

315 316
    _fgmask.create(frameSize_, CV_8UC1);
    cv::Mat fgmask = _fgmask.getMat();
317

318 319
    GMG_LoopBody body(frame, fgmask, nfeatures_, colors_, weights_,
                      maxFeatures, learningRate, numInitializationFrames, quantizationLevels, backgroundPrior, decisionThreshold,
320
                      maxVal_, minVal_, frameNum_, updateBackgroundModel);
321
    cv::parallel_for_(cv::Range(0, frame.rows), body);
322

323 324 325 326 327
    if (smoothingRadius > 0)
    {
        cv::medianBlur(fgmask, buf_, smoothingRadius);
        cv::swap(fgmask, buf_);
    }
328

329 330 331
    // keep track of how many frames we have processed
    ++frameNum_;
}
332 333 334 335 336 337 338 339 340 341

void cv::BackgroundSubtractorGMG::release()
{
    frameSize_ = cv::Size();

    nfeatures_.release();
    colors_.release();
    weights_.release();
    buf_.release();
}