实时显示摄像头,按空格键保存一张图片,按ESC退出时保存录像。
1 代码
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
using namespace std;
using namespace cv;
void main()
{
string filename = "test.jpg"; //保存的照片名
VideoCapture capture(0);
double rate = 25.0; //帧率
Size videoSize(640, 480); //分辨率
VideoWriter writer("test.mp4", CV_FOURCC('D', 'I', 'V', 'X'), rate, videoSize); //设置为mp4格式存储
Mat frame;
while (capture.isOpened())
{
capture >> frame;
writer << frame;
imshow("video", frame); //实时显示摄像头
if (waitKey(20) == 32) //按空格键拍照
{
imwrite(filename, frame); //照片保存到工程目录
}
if (waitKey(20) == 27) //按ESC退出
{
break;
}
}
}
注:在video窗口按空格键保存,按ESC退出
2 运行结果
