c++实现摄像头视频保存
时间: 2023-09-18 12:11:14 浏览: 45
你可以使用OpenCV库实现摄像头视频保存。下面是一个简单的C++代码示例:
```c++
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
// 打开摄像头
VideoCapture cap(0);
if(!cap.isOpened())
{
cout << "无法打开摄像头!" << endl;
return -1;
}
// 设置保存视频的路径及名称
string videoPath = "output.avi";
// 获取摄像头的帧率和分辨率
double fps = cap.get(CAP_PROP_FPS);
int width = cap.get(CAP_PROP_FRAME_WIDTH);
int height = cap.get(CAP_PROP_FRAME_HEIGHT);
// 创建视频编码器并打开输出视频文件
VideoWriter videoWriter(videoPath, VideoWriter::fourcc('M', 'J', 'P', 'G'), fps, Size(width, height));
if(!videoWriter.isOpened())
{
cout << "无法保存视频!" << endl;
return -1;
}
// 循环读取摄像头的每一帧,并将其写入输出视频文件
while(true)
{
Mat frame;
cap.read(frame);
if(frame.empty())
{
cout << "摄像头读取失败!" << endl;
break;
}
videoWriter.write(frame);
imshow("Camera", frame);
char c = waitKey(1);
if(c == 27) // 如果按下 ESC 键,退出循环
{
break;
}
}
// 释放摄像头和视频编码器
cap.release();
videoWriter.release();
return 0;
}
```
这个代码将会捕获摄像头的视频流,并将其保存到名为“output.avi”的视频文件中。你可以在代码中修改保存路径和名称。