OpenCV高斯模型
int main(int argc, char** argv) { //std::string videoFile = "E:\\C_VC_code\\Text_Photo\\dingdang.avi"; //cv::VideoCapture capture; //capture.open(videoFile); //VideoCapture capture("E:\\C_VC_code\\Text_Photo\\大屏互动+行人检测_标清.flv"); VideoCapture capture(0); if (!capture.isOpened()) { std::cout<<"read video failure"<<std::endl; return -1; } cv::BackgroundSubtractorMOG2 mog; cv::Mat foreground; cv::Mat background; cv::Mat frame; Mat frame1; long frameNo = 0; double scalar = 0.3; while (1) { capture>>frame1; resize(frame1,frame,Size(frame1.cols*scalar,frame1.rows*scalar),1,1,3); // 运动前景检测,并更新背景 mog(frame, foreground, 0.2); // 腐蚀 cv::erode(foreground, foreground, cv::Mat()); // 膨胀 cv::dilate(foreground, foreground, cv::Mat()); mog.getBackgroundImage(background); // 返回当前背景图像 threshold(foreground,foreground,40,250,CV_THRESH_BINARY_INV); cv::imshow("foreground", foreground); cv::imshow("background", background); if (cv::waitKey(40) > 0) { break; } } return 0; }
opencv-3.0.0版本的变化:
int main(int argc, char *argv[]) { cv::Mat frame; cv::Mat back; cv::Mat fore; cv::VideoCapture cap(0); cv::Ptr<BackgroundSubtractorMOG2> bg = createBackgroundSubtractorMOG2(); bg->setNMixtures(30); //bg.bShadowDetection = false; std::vector<std::vector<cv::Point> > contours; cv::namedWindow("Frame"); cv::namedWindow("Background"); for (;;) { cap >> frame; //bg.operator()(frame, fore); bg->apply(frame, fore,0.01); bg->getBackgroundImage(back); cv::erode(fore, fore, cv::Mat()); cv::dilate(fore, fore, cv::Mat()); cv::findContours(fore, contours, CV_RETR_EXTERNAL,CV_CHAIN_APPROX_NONE); cv::drawContours(frame, contours, -1, cv::Scalar(0, 0, 255), 2); threshold(fore, fore, 80, 250, CV_THRESH_BINARY_INV); cv::imshow("Foreground", fore); cv::imshow("Frame", frame); cv::imshow("Background", back); if (cv::waitKey(30) >= 0) break; } return 0; }