opencv中C++写视频的函数如下:
C++:
VideoWriter::
VideoWriter
(const string& filename, int fourcc, double fps, Size frameSize, bool isColor=true)
参数:
filename - 输出视频文件的名称。
fourcc - 用于压缩帧的4字符编解码器代码。 例如,CV_FOURCC('P','I','M','1')是MPEG-1编解码器,CV_FOURCC('M','J','P','G')是一个动作 - jpeg编解码器等。代码列表可以通过FOURCC页面在视频编解码器中获得。
fps - 创建的视频流的帧率。
frameSize - 视频帧的大小。
isColor - 如果它不为零,编码器将对彩色帧进行预期和编码,否则它将与灰度帧一起使用(该标志目前仅在Windows上受支持)。
构造函数/函数初始化视频编写器。 在Linux上,FFMPEG用于编写视频; 在Windows FFMPEG或VFW上使用; 在MacOSX上使用QTKit。
上代码:
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main()
{
// 视频读入与输出路径设置
string sourceVideoPath = "C:\\Users\\Administrator\\Desktop\\飞机.avi";
string outputVideoPath = "F:\\a1\\xinjian\\P.avi";
// 视频输入
VideoCapture inputVideo(sourceVideoPath);
// 检测视频输入的有效性
if (!inputVideo.isOpened())
{
cout << "fail to open!" << endl;
return -1;
}
VideoWriter outputVideo;
// 获取视频分辨率
cv::Size videoResolution = cv::Size((int)inputVideo.get(
CV_CAP_PROP_FRAME_WIDTH), (int)inputVideo.get(
CV_CAP_PROP_FRAME_HEIGHT));
double fps = inputVideo.get(CV_CAP_PROP_FPS);
// 获取视频帧率
cout << "totalFrame:" << inputVideo.get(
CV_CAP_PROP_FRAME_COUNT) << endl;
// 获取视频总帧数
cout << "fps:" << inputVideo.get(CV_CAP_PROP_FPS) << endl;
// 获取视频图像宽高
cout << "videoResolution:" << videoResolution.width <<
" " << videoResolution.height << endl;
VideoWriter outputVideo("V.avi", CV_FOURCC('M','J','P','G'), 25.0,
videoResolution, true);
if (!outputVideo.isOpened())
{
cout << "fail to open!" << endl;
return -1;
}
cv::Mat frameImg;
int count = 0;
cv::Mat resultImg1;
while (true)
{
inputVideo >> frameImg;
// 视频帧结束判断
if (!frameImg.empty())
{
count++;
applyColorMap(frameImg,resultImg1,COLORMAP_HOT);
imshow("Canny Video",resultImg1);
outputVideo<< resultImg1;
}
else
{
break;
}
// 按下键盘上q键退出
if (char(waitKey(1)) == 'q')
{
inputVideo.release();
outputVideo.release();
break;
}
}
std::cout << "writeTotalFrame:" << count << std::endl;
inputVideo.release();
outputVideo.release();
return 0;
}