使用 VideoWriter
写视频文件
用代码说明如何写视频:
#include <opencv2/opencv.h>
voide videoWrite()
{
std::string inputFile = "test.mp4";
cv::VideoCapture cap(inputFile);
std::string filePath; // 写如文件路径
int fps=25;
int width=100;
int height=100;
cv::Mat frame;
cv::VideoWriter videoWriter(filePath, cv::FOURCC(‘X', 'I', 'V', 'D'),fps ,cv::Size(height, width));
while(cap.read(frame))
{
videoWriter.write(frame);
}
cap.release();
videoWriter.release();
}
以上代码手写,作为示例,没有验证,如有错误请自行改正。
容易出现的错误分析:
- 写入的帧的大小要和上面videoWriter 中指定的大小统一,否则会写入错误;
- 注意fourcc要与保存的格式进行对应;
- 当写入的尺寸过大时,可能会写入错误。我在写入视频的帧大小为 3850*1080 时,写入不成功;将尺寸缩小一半,写入成功。具体原因未找到。