win10 / VS2013 / OpenCV3
#include<opencv2/opencv.hpp>
#include<iostream>
using namespace std;
using namespace cv;
//背景差分法
int main()
{
VideoCapture capture("dust.mp4");//获取视频
if (!capture.isOpened())
{
return -1;
}
double rate = capture.get(CV_CAP_PROP_FPS);//获取视频帧率
int delay = 500 / rate;
Mat framepro, frame, dframe;
Mat gray, bi;
bool flag = false;
namedWindow("diff",0);
namedWindow("gray", 0);
namedWindow("bi", 0);
while (capture.read(frame))
{
if (flag == false)
{
framepro = frame.clone(); //第一帧图像
flag = true;
}
else
{
absdiff(frame, framepro, dframe); //帧间差分
//framepro = frame.clone(); //将当前帧拷贝给framepro
//threshold(dframe, dframe, 90, 255, CV_THRESH_TOZERO); //阈值分割
// 将差分图像灰度化/二值化
cvtColor(dframe, gray, CV_BGR2GRAY);
threshold(gray, bi, 50, 255, CV_THRESH_BINARY);
//差分结果实时显示窗口
imshow("diff", dframe);
imshow("gray", gray);
imshow("bi", bi);
waitKey(delay);
}
}
waitKey();
return 0;
}
// 获取视频的 高/宽/帧率/帧数
int frameH = (int)cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);
int frameW = (int)cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
int fps = (int)cvGetCaptureProperty(capture, CV_CAP_PROP_FPS);
int numFrames = (int)cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_COUNT);
double rate = capture.get(CV_CAP_PROP_FPS);
double frameNum = capture.get(CV_CAP_PROP_FRAME_COUNT);
//获取视频总时长(s)
int VideoTime = frameNum / rate;
double t;
int f = 0;
while (capture.read(frame))
{
f++;
t = f / frameNum * VideoTime; //第f帧在视频中所在的时间位置
}