1 /*M///////////////////////////////////////////////////////////////////////////////////////
3 // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
5 // By downloading, copying, installing or using the software you agree to this license.
6 // If you do not agree to this license, do not download, install,
7 // copy or use the software.
10 // Intel License Agreement
12 // Copyright (C) 2000, Intel Corporation, all rights reserved.
13 // Third party copyrights are property of their respective owners.
15 // Redistribution and use in source and binary forms, with or without modification,
16 // are permitted provided that the following conditions are met:
18 // * Redistribution's of source code must retain the above copyright notice,
19 // this list of conditions and the following disclaimer.
21 // * Redistribution's in binary form must reproduce the above copyright notice,
22 // this list of conditions and the following disclaimer in the documentation
23 // and/or other materials provided with the distribution.
25 // * The name of Intel Corporation may not be used to endorse or promote products
26 // derived from this software without specific prior written permission.
28 // This software is provided by the copyright holders and contributors "as is" and
29 // any express or implied warranties, including, but not limited to, the implied
30 // warranties of merchantability and fitness for a particular purpose are disclaimed.
31 // In no event shall the Intel Corporation or contributors be liable for any direct,
32 // indirect, incidental, special, exemplary, or consequential damages
33 // (including, but not limited to, procurement of substitute goods or services;
34 // loss of use, data, or profits; or business interruption) however caused
35 // and on any theory of liability, whether in contract, strict liability,
36 // or tort (including negligence or otherwise) arising in any way out of
37 // the use of this software, even if advised of the possibility of such damage.
44 // to make sure we can use these short names
49 // This is based on the "An Improved Adaptive Background Mixture Model for
50 // Real-time Tracking with Shadow Detection" by P. KaewTraKulPong and R. Bowden
51 // http://personal.ee.surrey.ac.uk/Personal/R.Bowden/publications/avbs01/avbs01.pdf
53 // The windowing method is used, but not the shadow detection. I make some of my
54 // own modifications which make more sense. There are some errors in some of their
61 BackgroundSubtractor::~BackgroundSubtractor() {}
62 void BackgroundSubtractor::operator()(const Mat&, Mat&, double)
66 static const int defaultNMixtures = CV_BGFG_MOG_NGAUSSIANS;
67 static const int defaultHistory = CV_BGFG_MOG_WINDOW_SIZE;
68 static const double defaultBackgroundRatio = CV_BGFG_MOG_BACKGROUND_THRESHOLD;
69 static const double defaultVarThreshold = CV_BGFG_MOG_STD_THRESHOLD*CV_BGFG_MOG_STD_THRESHOLD;
71 BackgroundSubtractorMOG::BackgroundSubtractorMOG()
73 frameSize = Size(0,0);
77 nmixtures = defaultNMixtures;
78 history = defaultHistory;
79 varThreshold = defaultVarThreshold;
80 backgroundRatio = defaultBackgroundRatio;
83 BackgroundSubtractorMOG::BackgroundSubtractorMOG(int _history, int _nmixtures, double _backgroundRatio)
85 frameSize = Size(0,0);
89 nmixtures = min(_nmixtures > 0 ? _nmixtures : defaultNMixtures, 8);
90 history = _history > 0 ? _history : defaultHistory;
91 varThreshold = defaultVarThreshold;
92 backgroundRatio = min(_backgroundRatio > 0 ? _backgroundRatio : 0.95, 1.);
95 BackgroundSubtractorMOG::~BackgroundSubtractorMOG()
100 void BackgroundSubtractorMOG::initialize(Size _frameSize, int _frameType)
102 frameSize = _frameSize;
103 frameType = _frameType;
106 int nchannels = CV_MAT_CN(frameType);
107 CV_Assert( CV_MAT_DEPTH(frameType) == CV_8U );
109 // for each gaussian mixture of each pixel bg model we store ...
110 // the mixture sort key (w/sum_of_variances), the mixture weight (w),
111 // the mean (nchannels values) and
112 // the diagonal covariance matrix (another nchannels values)
113 bgmodel.create( frameSize.height, frameSize.width*nmixtures*(2 + 2*nchannels), CV_32F );
114 const float w0 = (float)CV_BGFG_MOG_WEIGHT_INIT;
115 const float var0 = (float)(CV_BGFG_MOG_SIGMA_INIT*CV_BGFG_MOG_SIGMA_INIT);
116 const float sk0 = (float)(CV_BGFG_MOG_WEIGHT_INIT/(CV_BGFG_MOG_SIGMA_INIT*sqrt((double)nchannels)));
118 for( int y = 0; y < frameSize.height; y++ )
120 float* mptr = bgmodel.ptr<float>(y);
121 for( int x = 0; x < frameSize.width; x++ )
123 for( int k = 0; k < nmixtures; k++ )
128 for( int c = 0; c < nchannels; c++ )
131 mptr[c + nchannels] = var0;
140 template<typename VT> struct MixData
149 static void process8uC1( BackgroundSubtractorMOG& obj, const Mat& image, Mat& fgmask, double learningRate )
151 int x, y, k, k1, rows = image.rows, cols = image.cols;
152 float alpha = (float)learningRate, T = (float)obj.backgroundRatio, vT = (float)obj.varThreshold;
153 int K = obj.nmixtures;
155 const float w0 = (float)CV_BGFG_MOG_WEIGHT_INIT;
156 const float sk0 = (float)(CV_BGFG_MOG_WEIGHT_INIT/CV_BGFG_MOG_SIGMA_INIT);
157 const float var0 = (float)(CV_BGFG_MOG_SIGMA_INIT*CV_BGFG_MOG_SIGMA_INIT);
159 for( y = 0; y < rows; y++ )
161 const uchar* src = image.ptr<uchar>(y);
162 uchar* dst = fgmask.ptr<uchar>(y);
163 MixData<float>* mptr = (MixData<float>*)obj.bgmodel.ptr(y);
165 for( x = 0; x < cols; x++, mptr += K )
167 float wsum = 0, dw = 0;
169 for( k = 0; k < K; k++ )
171 float w = mptr[k].weight;
172 float mu = mptr[k].mean;
173 float var = mptr[k].var;
174 float diff = pix - mu, d2 = diff*diff;
177 dw = alpha*(1.f - w);
178 mptr[k].weight = w + dw;
179 mptr[k].mean = mu + alpha*diff;
180 mptr[k].var = var = max(var + alpha*(d2 - var), FLT_EPSILON);
181 mptr[k].sortKey = w/sqrt(var);
183 for( k1 = k-1; k1 >= 0; k1-- )
185 if( mptr[k1].sortKey > mptr[k1+1].sortKey )
187 std::swap( mptr[k1], mptr[k1+1] );
194 dst[x] = (uchar)(-(wsum >= T));
197 if( k == K ) // no appropriate gaussian mixture found at all, remove the weakest mixture and create a new one
199 wsum += w0 - mptr[K-1].weight;
200 mptr[K-1].weight = w0;
201 mptr[K-1].mean = pix;
202 mptr[K-1].var = var0;
203 mptr[K-1].sortKey = sk0;
207 wsum += mptr[k].weight;
210 for( k = 0; k < K; k++ )
212 mptr[k].weight *= dw;
213 mptr[k].sortKey *= dw;
219 static void process8uC3( BackgroundSubtractorMOG& obj, const Mat& image, Mat& fgmask, double learningRate )
221 int x, y, k, k1, rows = image.rows, cols = image.cols;
222 float alpha = (float)learningRate, T = (float)obj.backgroundRatio, vT = (float)obj.varThreshold;
223 int K = obj.nmixtures;
225 const float w0 = (float)CV_BGFG_MOG_WEIGHT_INIT;
226 const float sk0 = (float)(CV_BGFG_MOG_WEIGHT_INIT/CV_BGFG_MOG_SIGMA_INIT);
227 const float var0 = (float)(CV_BGFG_MOG_SIGMA_INIT*CV_BGFG_MOG_SIGMA_INIT);
229 for( y = 0; y < rows; y++ )
231 const uchar* src = image.ptr<uchar>(y);
232 uchar* dst = fgmask.ptr<uchar>(y);
233 MixData<Vec3f>* mptr = (MixData<Vec3f>*)obj.bgmodel.ptr(y);
235 for( x = 0; x < cols; x++, mptr += K )
237 float wsum = 0, dw = 0;
238 Vec3f pix(src[x*3], src[x*3+1], src[x*3+2]);
239 for( k = 0; k < K; k++ )
241 float w = mptr[k].weight;
242 Vec3f mu = mptr[k].mean[0];
243 Vec3f var = mptr[k].var[0];
244 Vec3f diff = pix - mu;
245 float d2 = diff.dot(diff);
246 if( d2 < vT*(var[0] + var[1] + var[2]) )
248 dw = alpha*(1.f - w);
249 mptr[k].weight = w + dw;
250 mptr[k].mean = mu + alpha*diff;
251 var = Vec3f(max(var[0] + alpha*(diff[0]*diff[0] - var[0]), FLT_EPSILON),
252 max(var[1] + alpha*(diff[1]*diff[1] - var[1]), FLT_EPSILON),
253 max(var[2] + alpha*(diff[2]*diff[2] - var[2]), FLT_EPSILON));
255 mptr[k].sortKey = w/sqrt(var[0] + var[1] + var[2]);
257 for( k1 = k-1; k1 >= 0; k1-- )
259 if( mptr[k1].sortKey > mptr[k1+1].sortKey )
261 std::swap( mptr[k1], mptr[k1+1] );
268 dst[x] = (uchar)(-(wsum >= T));
271 if( k == K ) // no appropriate gaussian mixture found at all, remove the weakest mixture and create a new one
273 wsum += w0 - mptr[K-1].weight;
274 mptr[K-1].weight = w0;
275 mptr[K-1].mean = pix;
276 mptr[K-1].var = Vec3f(var0, var0, var0);
277 mptr[K-1].sortKey = sk0;
281 wsum += mptr[k].weight;
284 for( k = 0; k < K; k++ )
286 mptr[k].weight *= dw;
287 mptr[k].sortKey *= dw;
293 void BackgroundSubtractorMOG::operator()(const Mat& image, Mat& fgmask, double learningRate)
295 bool needToInitialize = nframes == 0 || learningRate >= 1 || image.size() != frameSize || image.type() != frameType;
297 if( needToInitialize )
298 initialize(frameSize, frameType);
300 CV_Assert( image.depth() == CV_8U );
301 fgmask.create( image.size(), CV_8U );
304 learningRate = learningRate >= 0 && nframes > 1 ? learningRate : 1./min( nframes, history );
306 if( image.type() == CV_8UC1 )
307 process8uC1( *this, image, fgmask, learningRate );
308 else if( image.type() == CV_8UC3 )
309 process8uC3( *this, image, fgmask, learningRate );
311 CV_Error( CV_StsUnsupportedFormat, "Only 1- and 3-channel 8-bit images are supported in BackgroundSubtractorMOG" );
318 icvReleaseGaussianBGModel( CvGaussBGModel** bg_model )
321 CV_Error( CV_StsNullPtr, "" );
325 delete (cv::Mat*)((*bg_model)->g_point);
326 cvReleaseImage( &(*bg_model)->background );
327 cvReleaseImage( &(*bg_model)->foreground );
328 cvReleaseMemStorage(&(*bg_model)->storage);
329 memset( *bg_model, 0, sizeof(**bg_model) );
337 icvUpdateGaussianBGModel( IplImage* curr_frame, CvGaussBGModel* bg_model, double learningRate )
339 int region_count = 0;
340 CvSeq *first_seq = NULL, *prev_seq = NULL, *seq = NULL;
342 cv::Mat image = cv::cvarrToMat(curr_frame), mask = cv::cvarrToMat(bg_model->foreground);
344 cv::BackgroundSubtractorMOG mog;
345 mog.bgmodel = *(cv::Mat*)bg_model->g_point;
346 mog.frameSize = mog.bgmodel.data ? cv::Size(cvGetSize(curr_frame)) : cv::Size();
347 mog.frameType = image.type();
349 mog.nframes = bg_model->countFrames;
350 mog.history = bg_model->params.win_size;
351 mog.nmixtures = bg_model->params.n_gauss;
352 mog.varThreshold = bg_model->params.std_threshold;
353 mog.backgroundRatio = bg_model->params.bg_threshold;
355 mog(image, mask, learningRate);
357 bg_model->countFrames = mog.nframes;
358 if( ((cv::Mat*)bg_model->g_point)->data != mog.bgmodel.data )
359 *((cv::Mat*)bg_model->g_point) = mog.bgmodel;
361 //foreground filtering
363 //filter small regions
364 cvClearMemStorage(bg_model->storage);
366 //cvMorphologyEx( bg_model->foreground, bg_model->foreground, 0, 0, CV_MOP_OPEN, 1 );
367 //cvMorphologyEx( bg_model->foreground, bg_model->foreground, 0, 0, CV_MOP_CLOSE, 1 );
369 cvFindContours( bg_model->foreground, bg_model->storage, &first_seq, sizeof(CvContour), CV_RETR_LIST );
370 for( seq = first_seq; seq; seq = seq->h_next )
372 CvContour* cnt = (CvContour*)seq;
373 if( cnt->rect.width * cnt->rect.height < bg_model->params.minArea )
375 //delete small contour
376 prev_seq = seq->h_prev;
379 prev_seq->h_next = seq->h_next;
380 if( seq->h_next ) seq->h_next->h_prev = prev_seq;
384 first_seq = seq->h_next;
385 if( seq->h_next ) seq->h_next->h_prev = NULL;
393 bg_model->foreground_regions = first_seq;
394 cvZero(bg_model->foreground);
395 cvDrawContours(bg_model->foreground, first_seq, CV_RGB(0, 0, 255), CV_RGB(0, 0, 255), 10, -1);
400 CV_IMPL CvBGStatModel*
401 cvCreateGaussianBGModel( IplImage* first_frame, CvGaussBGStatModelParams* parameters )
403 CvGaussBGStatModelParams params;
405 CV_Assert( CV_IS_IMAGE(first_frame) );
408 if( parameters == NULL )
409 { /* These constants are defined in cvaux/include/cvaux.h: */
410 params.win_size = CV_BGFG_MOG_WINDOW_SIZE;
411 params.bg_threshold = CV_BGFG_MOG_BACKGROUND_THRESHOLD;
413 params.std_threshold = CV_BGFG_MOG_STD_THRESHOLD;
414 params.weight_init = CV_BGFG_MOG_WEIGHT_INIT;
416 params.variance_init = CV_BGFG_MOG_SIGMA_INIT*CV_BGFG_MOG_SIGMA_INIT;
417 params.minArea = CV_BGFG_MOG_MINAREA;
418 params.n_gauss = CV_BGFG_MOG_NGAUSSIANS;
421 params = *parameters;
423 CvGaussBGModel* bg_model = new CvGaussBGModel;
424 memset( bg_model, 0, sizeof(*bg_model) );
425 bg_model->type = CV_BG_MODEL_MOG;
426 bg_model->release = (CvReleaseBGStatModel)icvReleaseGaussianBGModel;
427 bg_model->update = (CvUpdateBGStatModel)icvUpdateGaussianBGModel;
429 bg_model->params = params;
432 bg_model->g_point = (CvGaussBGPoint*)new cv::Mat();
434 bg_model->background = cvCreateImage(cvSize(first_frame->width,
435 first_frame->height), IPL_DEPTH_8U, first_frame->nChannels);
436 bg_model->foreground = cvCreateImage(cvSize(first_frame->width,
437 first_frame->height), IPL_DEPTH_8U, 1);
439 bg_model->storage = cvCreateMemStorage();
441 bg_model->countFrames = 0;
443 icvUpdateGaussianBGModel( first_frame, bg_model, 1 );
445 return (CvBGStatModel*)bg_model;