OpenCV的video module中包含了几种较为常用的背景减除方法,其中混合高斯模型(Gaussian of Mixture Models, GMM)方法效果较好。
常用的目标检测方法:1)帧间差分;2)背景减除;
其中背景减除方法的关键在于建立一个鲁棒的背景模型(背景图像),常用的建立背景模型方法有:
1)均值法;2)中值法;3)滑动平均滤波法;4)单高斯;5)混合高斯模型;6)codebook,等。
混合高斯模型的原理:
每个像素的R、G、B三个通道像素值的变化分别由一个混合高斯模型分布来刻画。这样的好处在于,同一个像素位置处可以呈现多个模态的像素值变化(例如水波纹,晃动的叶子等)。
GMM的出处:Adaptive background mixture models for real-time tracking (1999年由Chris Stau er提出)
OpenCV版本:2.4.2
下面的代码实现了基于GMM的运动目标检测,同时能够消除运动阴影; (基于文献:Improved adaptive Gausian mixture model for background subtraction)
- // 基于混合高斯模型的运动目标检测
- // 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 videoFile = "../test.avi";
- cv::VideoCapture capture;
- capture.open(videoFile);
- if (!capture.isOpened())
- {
- std::cout<<"read video failure"<<std::endl;
- return -1;
- }
- cv::BackgroundSubtractorMOG2 mog;
- cv::Mat foreground;
- cv::Mat background;
- cv::Mat frame;
- long frameNo = 0;
- while (capture.read(frame))
- {
- ++frameNo;
- std::cout<<frameNo<<std::endl;
- // 运动前景检测,并更新背景
- mog(frame, foreground, 0.001);
- // 腐蚀
- cv::erode(foreground, foreground, cv::Mat());
- // 膨胀
- cv::dilate(foreground, foreground, cv::Mat());
- mog.getBackgroundImage(background); // 返回当前背景图像
- cv::imshow("video", foreground);
- cv::imshow("background", background);
- if (cv::waitKey(25) > 0)
- {
- break;
- }
- }
- return 0;
- }