The following code uses opencv to implement the simplest Motion Target Detection Algorithm Based on Adaptive Background update.
That is:
Moving foreground extraction-Background Subtraction
Foreground = | frame-Background |> threshold
Update background model-moving average filtering
Background = background + (frame-background) * alpha = background * (1-alpha) + frame * alpha
// Motion foreground detection-Based on Adaptive Background update // Author: www.icvpr.com//blog: http://blog.csdn.net/icvpr#include <iostream> # include <string> # include <opencv2/opencv. HPP> int main (INT argc, char ** argv) {STD: String videofilename = ".. /test. avi "; int Threshold = 25; // binarization threshold float alpha = 0.01; // update speed [0, 1] CV: videocapture capture; capture. open (videofilename); If (! Capture. isopened () {STD: cout <"cannot open video" <STD: Endl; Return-1;} CV: mat foregroundimg; CV: mat foregroundmat; CV: mat backgroundimg; CV: mat backgroundmat; CV: mat frame; CV: mat grayimg; CV: mat graymat; while (capture. read (FRAME) {CV: cvtcolor (frame, grayimg, cv_bgr2gray); grayimg. convertize (graymat, cv_32fc1); If (backgroundmat. empty () {grayimg. copyto (backgroundimg); grayimg. convertize (backgroundmat, callback);} // Background Subtraction CV: absdiff (graymat, backgroundmat, foregroundmat); // Adaptive Background update CV: addweighted (backgroundmat, Alpha, foregroundmat, 1-Alpha, 0, backgroundmat); // binarization, obtain the foreground pixel CV: threshold (foregroundmat, foregroundmat, threshold, 255, cv_thresh_binary); // For display purpose, convert cv_32fc1 to cv_8ucv: convertscaleabs (foregroundmat, callback); CV: convertscaleabs (backgroundmat, backgroundimg); CV: imshow ("frame", frame); CV :: imshow ("foreground", foregroundimg); CV: imshow ("background", backgroundimg); If (CV: waitkey (25)> 0) {break ;}} return 0 ;}
Related content: www.icvpr.com
--------------------------------------------------------
<Reprint Please note: http://blog.csdn.net/icvpr>