这篇博客主要参考了《opencv2计算机视觉编程手册》中的chap10中的10.6提取视频中的前景物体的定期更新背景模型。该书在实现这个模型时,编写了一个关于处理视频的类,进行了封装。而下面是我根据书的源代码稍作改写,方便以后写实验性质的代码进行参考:
#include<iostream>
#include<opencv2/core/core.hpp>
#include<opencv2/imgproc/imgproc.hpp>
#include<opencv2/highgui/highgui.hpp>
using namespace std;
using namespace cv;
void process(Mat& frame,Mat &background,Mat &backImage,Mat &foreground,Mat &output,int threshold,double learningRate) {
//当前灰度图像
Mat gray;
//将读取的帧图像转化为灰度图像
cvtColor(frame, gray, CV_BGR2GRAY);
if (background.empty())
//第一帧
gray.convertTo(background, CV_32F);
//背景转为CV_8U格式以便求取和当前帧差的绝对值
background.convertTo(backImage, CV_8U);
//求当前帧与背景的差别
absdiff(backImage, gray, foreground);
//过滤掉前景中与背景差别不大的扰动点
cv::threshold(foreground, output, threshold, 255, THRESH_BINARY_INV);
//更新背景,output