opencv 将视频分解成图片和使用本地图片合成视频
代码如下:
// cvTest.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include<iostream>
#include<opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
using namespace cv;
using namespace std;
char outname[200];
typedef struct __SaveProp__
{
int width;
int height;
int framerate;
struct __SaveProp__(int W, int H, int F)
{
width = W;
height = H;
framerate = F;
}
}SaveProp;
void Video2Img(char* filename, char* outpath, int index, char* postfix);
void Img2Video(char* filepath, unsigned int startIndex, unsigned int EndIndex, char* fOutname, SaveProp* p_prop);
int _tmain(int argc, _TCHAR* argv[])
{
//Video2Img("E:\\3.avi", "E:\\data", 500, "bmp");
SaveProp saveprop(640, 482,15);
Img2Video("E:\\data", 1, 481, "E:\\test", &saveprop);
return 0;
}
//视频拆分成图片
void Video2Img(char* filename, char* outpath, int index, char* postfix)
{
VideoCapture cap(filename);
if (!cap.isOpened())
{
cout << "============================= Video Open Error ============================= " << endl;
return;
}
Mat frame;
int totalname = cap.get(CV_CAP_PROP_FRAME_COUNT);
for (int i = 1; i <= totalname; i++)
{
cap >> frame;
if (frame.empty())
break;
cout << "============================= write " << i << " frame =============================" << endl;
sprintf(outname, "%s\\%04d.%s", outpath, index, postfix);
index++;
imshow("video", frame);
waitKey(10);
imwrite(outname, frame);
}
cap.release();
destroyAllWindows();
cout << "============================= Finish Converting =============================" << endl;
}
// 编码方法
/*
CV_FOURCC('P','I','M','1') = MPEG-1 codec
CV_FOURCC('M','J','P','G') = motion-jpeg codec
CV_FOURCC('M', 'P', '4', '2') = MPEG-4.2 codec
CV_FOURCC('D', 'I', 'V', '3') = MPEG-4.3 codec
CV_FOURCC('D', 'I', 'V', 'X') = MPEG-4 codec
CV_FOURCC('U', '2', '6', '3') = H263 codec
CV_FOURCC('I', '2', '6', '3') = H263I codec
CV_FOURCC('F', 'L', 'V', '1') = FLV1 codec
*/
// 图片合成视频
void Img2Video(char* filepath, unsigned int startIndex, unsigned int EndIndex, char* fOutname, SaveProp* p_prop)
{
sprintf(outname, "%s.avi", fOutname);
VideoWriter writer(outname, VideoWriter::fourcc('M', 'P', '4', '2'), p_prop->framerate,
Size(p_prop->width, p_prop->height));
Mat frame;
char filename[200];
for (unsigned int i = startIndex; i <= EndIndex; i++)
{
sprintf(filename, "%s\\%04d.bmp", filepath, i);
frame = imread(filename);
if (!frame.empty())
{
writer.write(frame);
cout << "============================= write " << i <<" frame =============================" << endl;
}
else
cout << "============================= Image Open Error ============================= " << endl;
}
cout << "============================= Finish Converting =============================" << endl;
}