opencv保存视频
利用opencv提供的方法,从摄像头获取视频,并保存为.avi格式文件。
win8.1,opencv248,vs2013下测试
#include<opencv\cv.h>
#include<highgui.h>
#include<iostream>
using namespace cv;
using namespace std;
int main()
{
CvCapture * capture = cvCaptureFromCAM(0);
IplImage * frame = NULL;
CvVideoWriter* video = NULL;
int i = 0;
// 视频存储 相应参数 设置
int fps = 10; //帧率
int codec = CV_FOURCC('D','I','V','X'); //视频编码 (MPEG-4)
if (!capture) //如果不能打开摄像头给出警告
{
cout << "Can not open the camera." << endl;
return -1;
}
else
{
i = 1;
frame = cvQueryFrame(capture); //首先取得摄像头中的一帧
//创建CvVideoWriter对象并分配空间
//保存的文件名为camera.avi,视频编码为MPEG-4,大小就是摄像头视频的大小,帧频率是fps=10
video = cvCreateVideoWriter("camera.avi", codec, fps, cvSize(frame->width, frame->height), 1);
if (video) //如果能创建CvVideoWriter对象则表明成功
{
cout << "VideoWriter has created." << endl;
cvNamedWindow("Camera Video", 1); //新建一个窗口
while (frame = cvQueryFrame(capture))//从CvCapture中获得一帧
{
if (!frame)
{
cout << "Can not get frame from the capture." << endl;
break;
}
if (cvWriteFrame(video, frame))//判断是否写入成功,如果返回的是1,表示写入成功
{
if (i%fps == 0)
cout << i / fps << "s" << endl;
cout << 1 << " ";
}
++i;
cvShowImage("Camera Video", frame); //显示视频内容的图片
if (cvWaitKey(1000 / fps)>0) break; //有其他键盘响应,则退出
if (i >= fps * 60) break;
}
}
else{
cout << "can not create VideoWriter." << endl;
}
cvReleaseVideoWriter(&video);
cvReleaseCapture(&capture);
cvDestroyWindow("Camera Video");
}
return 0;
}