videowriter保存mp4 C++
时间: 2023-10-21 22:04:46 浏览: 95
在 C++ 中,可以使用 OpenCV 库中的 VideoWriter 类来保存 MP4 视频。以下是一个简单的示例代码:
```c++
#include <opencv2/opencv.hpp>
using namespace cv;
int main() {
// 打开视频文件
VideoCapture cap("input.avi");
// 检查视频是否打开成功
if (!cap.isOpened()) {
std::cerr << "Failed to open input video file" << std::endl;
return -1;
}
// 获取视频帧率和分辨率
double fps = cap.get(CAP_PROP_FPS);
int width = (int)cap.get(CAP_PROP_FRAME_WIDTH);
int height = (int)cap.get(CAP_PROP_FRAME_HEIGHT);
// 创建 VideoWriter 对象
VideoWriter writer("output.mp4", VideoWriter::fourcc('M', 'P', '4', 'V'), fps, Size(width, height));
// 检查 VideoWriter 是否创建成功
if (!writer.isOpened()) {
std::cerr << "Failed to create output video file" << std::endl;
return -1;
}
// 逐帧读取并保存视频
Mat frame;
while (cap.read(frame)) {
writer.write(frame);
}
// 释放资源
cap.release();
writer.release();
return 0;
}
```
需要注意的是,要保存成 MP4 格式,需要指定 fourcc 参数为 "MP4V"。如果系统中没有支持 MP4 编码的视频编解码器,可能会导致保存失败。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)