视频来源:https://www.youtube.com/watch?v=oHFr0R6jQ6I
以下代码用OpenCV实现了视频中背景消除和提取的建模,涉及到KNN(K近邻算法)和GMM(高斯混合模型)。
//
// main.cpp
// opencv-learning
//
// Created by _R on 2019/1/9.
// Copyright © 2019 _R. All rights reserved.
//
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main(int argc, char* argv[])
{
VideoCapture video = VideoCapture("/Users/_R/Desktop/Highway_Test_640x360_30p.mp4");
if (!video.isOpened()) {
cout << "could not load video file ..." << endl;
return -1;
}
Mat frame, bgMask_MOG2, bgMask_KNN, background;
Mat kernel = getStructuringElement(MORPH_RECT, Size(3,3));
namedWindow("highway_test", WINDOW_AUTOSIZE);
namedWindow("background_mask_by_MOG2", WINDOW_AUTOSIZE);
namedWindow("background_by_KNN", WINDOW_AUTOSIZE);
namedWindow("background_mask_by_KNN", WINDOW_AUTOSIZE);
Ptr<BackgroundSubtractor> ptrMOG2 = createBackgroundSubtractorMOG2();
Ptr<BackgroundSubtractor> ptrKNN = createBackgroundSubtractorKNN();
while (video.read(frame)) {
imshow("highway_test", frame);
ptrMOG2->apply(frame, bgMask_MOG2);
morphologyEx(bgMask_MOG2, bgMask_MOG2, MORPH_OPEN, kernel);
ptrKNN->apply(frame, bgMask_KNN);
ptrKNN->getBackgroundImage(background);
imshow("background_by_KNN", background);
imshow("background_mask_by_MOG2", bgMask_MOG2);
imshow("background_mask_by_KNN", bgMask_KNN);
char c = waitKey(50);
if (c == 27) {
break;
}
}
waitKey(0);
video.release();
return 0;
}