opencv3/C++视频背景建模

来源:互联网 发布:程序员的技术栈 编辑:程序博客网 时间:2024/05/17 06:07

视频背景建模主要使用到:

高斯混合模型(Mixture Of Gauss,MOG)

createBackgroundSubtractorMOG2(int history=500, double varThreshold=16,bool detectShadows=true);

K最近邻(k-NearestNeighbor,kNN)

createBackgroundSubtractorKNN(int history=500, double dist2Threshold=400.0, bool detectShadows=true);

history:history的长度。
varThreshold:像素和模型之间马氏距离的平方的阈值。
detectShadows:默认为true,检测阴影并标记它们(影子会被标记为灰色)。 会降低了部分速度。

实例:

#include<opencv2/opencv.hpp>using namespace cv;int main(){    VideoCapture capture;    capture.open("E:/image/01.avi");    if(!capture.isOpened())    {        printf("can not open video file   \n");        return -1;    }    Mat frame;    namedWindow("input", CV_WINDOW_AUTOSIZE);    namedWindow("MOG2", CV_WINDOW_AUTOSIZE);    namedWindow("KNN", CV_WINDOW_AUTOSIZE);    Mat maskMOG2, maskKNN;    Ptr<BackgroundSubtractor> pMOG2 = createBackgroundSubtractorMOG2(500,25,true);    Ptr<BackgroundSubtractor> pKNN = createBackgroundSubtractorKNN();    Mat kernel = getStructuringElement(MORPH_RECT, Size(5,5));    while (capture.read(frame))    {        imshow("input", frame);        pMOG2->apply(frame, maskMOG2);        pKNN->apply(frame, maskKNN);        //对处理后的帧进行开操作,减少视频中较小的波动造成的影响        morphologyEx(maskMOG2,maskMOG2, MORPH_OPEN, kernel, Point(-1,-1));        morphologyEx(maskKNN,maskKNN, MORPH_OPEN, kernel, Point(-1,-1));        imshow("MOG2", maskMOG2);        imshow("KNN", maskKNN);        waitKey(3);    }    capture.release();    return 0;}

视频中移动的玻璃球:
这里写图片描述
MOG分离出的小球区域:
这里写图片描述
KNN分离出的小球区域:
这里写图片描述