读取摄像头
VideoCapture类 创建一个视频数据流 对象
如果使用相机,则加上括号(0),表示第一个摄像头;
如果读取视频,不需要加
判断是否打开,使用.isOpened()方法
将画面数据流入临时变量,直接用>>
显示.imshow()
/**
* @brief 读取摄像头
*
*/
void QuickDemo::DemoReadVideo()
{
VideoCapture video(0); //创建视频流,摄像头
double fps; //读取视频的fps帧率
int waitms; //每一帧的时间间隔
if (video.isOpened())
{
cout << "Video Open OK" << endl;
cout << "width" << video.get(CAP_PROP_FRAME_WIDTH) << endl;
cout << "height" << video.get(CAP_PROP_FRAME_HEIGHT) << endl;
fps = video.get(CAP_PROP_FPS); //获取帧率
waitms = 1000 / fps;
cout << "fps" << fps << endl;
}
else
{
cout << "Video Open Error" << endl;
return;
}
Mat frame; //帧,临时当前画面
while (1)
{
video >> frame; //数据流传入
if (frame.empty())
{
cout << "frame is empty" << endl;
}
else
{
imshow("frame", frame); //显示
waitKey(waitms);
}
}
}
保存视频
配置输入流
VideoCapture创建,输入视频流对象,相机填序号0
判断是否打开正常
配置输出流
VideoWriter创建,输出流对象,
编码格式用fourcc()方法
打开输出流,open()
注意
最后一个参数要填true,不然视频播放器不支持
使用tmpframe.size()前,必须先给tmpframe赋值,不然报错
判断是否打开isOpened()
数据流传输,<<,>>或read(img),write(img)都可以
/**
* @brief 保存视频文件
*
*/
void QuickDemo::demo_WriteVideo()
{
VideoCapture InputVideo(0); //创建输入数据流,使用 0 摄像头
double ifps,ofps;
int waitms;
if (InputVideo.isOpened())
{
cout << "open ok" << endl;
ifps = InputVideo.get(CAP_PROP_FPS);
cout << "ifps\t" << ifps << endl;
waitms = 1000 / ifps;
cout << "waitms\t" << waitms << endl;
}
else
{
return;
}
Mat tmpframe; //缓存帧
InputVideo.read(tmpframe); //先读一个,不然tmpframe是空的size会报错
string filename = "testVideo.avi";
VideoWriter OutputVideo; //创建输出数据流
int codec = OutputVideo.fourcc('M', 'J', 'P', 'G'); //设置编码格式
ofps = 20.0;
OutputVideo.open(filename, codec, ofps, tmpframe.size(), true); //打开输出流
//一定要选true,不然视频播放器不支持多工流
if (OutputVideo.isOpened())
{
cout << "open OK!" << endl;
}
else
{
return;
}
while (1)
{
InputVideo >> tmpframe; //获取到图片帧
// InputVideo.read(tmpframe);
imshow("Video", tmpframe);
// OutputVideo.write(tmpframe); //输出流
OutputVideo << tmpframe;
// waitKey(waitms);
char c;
c = waitKey(50);
if (c == 27) //ESC建退出
{
exit(0);
}
}
}