#include "StdAfx.h"
#include <cv.h>
#include <opencv2/opencv.hpp>
#include <cstdio>
#include <cstdlib>
#include <Windows.h>
#include "highgui.h"
#include "math.h"
using namespace std;
using namespace cv;
int W=600;
int H=400;
int main (int argc, char** argv)
{
VideoCapture capture("tree.avi");
Mat frame;
Mat frame_resize;
//Mat frame_r_Gray;
Mat average;
Mat background,foreground,foreground_BW;
//---------------------------------------------------------------------
//获取视频的宽度、高度、帧率、总的帧数
CvCapture* pCapture = NULL;
pCapture = cvCaptureFromAVI("tree.avi");
int frameH = (int) cvGetCaptureProperty(pCapture, CV_CAP_PROP_FRAME_HEIGHT);
int frameW = (int) cvGetCaptureProperty(pCapture, CV_CAP_PROP_FRAME_WIDTH);
int fps = (int) cvGetCaptureProperty(pCapture, CV_CAP_PROP_FPS);
int numFrames = (int) cvGetCaptureProperty(pCapture, CV_CAP_PROP_FRAME_COUNT);
int num=numFrames;
printf("vedio's \nwidth = %d\t height = %d\n video's fps = %d\t nums = %d", frameW, frameH, fps, numFrames);
//---------------------------------------------------------------------
Mat frame_r_Gray;
Mat frame_0,frame_1;//Mat m(3, 5, CV_32FC1, 1);
//---------------------------------------------------------------------
while(num)
{
capture>>frame;
if(!capture.read(frame)) break;
resize(frame, frame_resize, Size(W,H));
imshow("frame_resize",frame_resize);
cvtColor( frame_resize,frame_r_Gray, CV_RGB2GRAY );
//imshow("frame_resize_Gray",frame_r_Gray);
//-----------------------------------------------------------------------------------
//选择前一帧作为背景(读入第一帧时,第一帧作为背景)
if(num==numFrames)
{
background=frame_r_Gray.clone();
frame_0=background;
}
else
{
background=frame_0;
}
//------------------------------------------------------------------------------------
absdiff(frame_r_Gray,background,foreground);//用帧差法求前景
imshow("foreground",foreground);
threshold( foreground, foreground_BW, 50, 255 , 0 );//二值化
imshow("foreground_BW",foreground_BW);
frame_0=frame_r_Gray.clone();
num--;
char c = waitKey(33);
if( c ==27 ) break;
}
}