BGSLibrary:A Background Subtraction Library
The BGSLibrary was developed by Andrews Sobral and provides an easy-to-use C++ framework based on OpenCV to perform background subtraction (BGS) in videos.
github介绍及下载地址 : https://github.com/andrewssobral/bgslibrary
现有30+种视频前景提取算法,不一定最优,但可以比较效果,准备研究其中部分。
三帧差法原理,参考opencv知识库
opencv-视频处理-实时前景检测–三帧差法
仅给出算法实现部分代码 ThreeFrameDiffBGS.cpp和ThreeFrameDiffBGS.h
IBGS.h 和main函数可以参考一篇
ThreeFrameDiffBGS.cpp
#include "ThreeFrameDiffBGS.h"
ThreeFrameDiffBGS::ThreeFrameDiffBGS() : firstTime(true), enableThreshold(true), threshold(15), showOutput(true)
{
std::cout << "FrameDifferenceBGS()" << std::endl;
}
ThreeFrameDiffBGS::~ThreeFrameDiffBGS()
{
std::cout << "~FrameDifferenceBGS()" << std::endl;
}
void ThreeFrameDiffBGS::process(const cv::Mat &img_input, cv::Mat &img_output, cv::Mat &img_bgmodel)
{
if (img_input.empty())
return;
enableThreshold = true;
threshold = 15;
showOutput = true;
if (img_input_prev2.empty())
{
img_input.copyTo(img_input_prev2);//前一帧为空时,将当前帧复制给前一帧
return;
}
if (img_input_prev1.empty())
{
img_input.copyTo(img_input_prev1);//前一帧为空时,将当前帧复制给前一帧
return;
}
//进行做差
cv::absdiff(img_input_prev2, img_input_prev1, img_Differ1);
cv::absdiff(img_input_prev1, img_input, img_Differ2);
//先灰度化,然后用阈值提取前景背景
if (img_Differ1.channels() == 3)
cv::cvtColor(img_Differ1, img_Differ1, CV_BGR2GRAY);
if (enableThreshold)
cv::threshold(img_Differ1, img_Differ1, threshold, 255, cv::THRESH_BINARY);
if (img_Differ2.channels() == 3)
cv::cvtColor(img_Differ2, img_Differ2, CV_BGR2GRAY);
if (enableThreshold)
cv::threshold(img_Differ2, img_Differ2, threshold, 255, cv::THRESH_BINARY);
//与运算
cv::bitwise_and(img_Differ1, img_Differ2, img_foreground);
//中值滤波
//cv::medianBlur(img_foreground, img_foreground, 3);
if (showOutput)
{
namedWindow("Frame Difference", cv::WINDOW_NORMAL);
cv::imshow("Frame Difference", img_foreground);
}
img_foreground.copyTo(img_output);
img_input_prev1.copyTo(img_input_prev2);
img_input.copyTo(img_input_prev1);
firstTime = false;
}
ThreeFrameDiffBGS .h
#pragma once
#include <iostream>
#include <opencv2/opencv.hpp>
#include "IBGS.h"
class ThreeFrameDiffBGS : public IBGS
{
private:
bool firstTime;
cv::Mat img_input_prev1;
cv::Mat img_input_prev2; //img_input_prev1的前一帧
cv::Mat img_Differ1; //differ1 = pre2 - pre1
cv::Mat img_Differ2; //differ2 = pre1 - precurrent
cv::Mat img_foreground;
bool enableThreshold;
int threshold;
bool showOutput;
public:
ThreeFrameDiffBGS();
~ThreeFrameDiffBGS();
void process(const cv::Mat &img_input, cv::Mat &img_output, cv::Mat &img_bgmodel);
//private:
// void saveConfig();
// void loadConfig();
};