假设我们在E盘下的images文件夹下有图像名称为frame_0000到图像名称为frame_0199共200张图像,如何将这些图像生成视频文件呢?下面是源码:
// createVideo.cpp : 定义控制台应用程序的入口点。
#include "stdafx.h"
#include <cv.h>
#include <cxcore.h>
#include <highgui.h>
#include <iostream>
#include <string>
using namespace std;
#define USE_OPENCV20 0
#if USE_OPENCV20
#pragma comment(lib,"cv200.lib")
#pragma comment(lib,"highgui200d.lib")
#pragma comment(lib,"cxcore200.lib")
#pragma comment(lib,"cxcore200d.lib")
#pragma comment(lib,"cv200d.lib")
#pragma comment(lib,"highgui200d.lib")
#else
#pragma comment( lib, "cv.lib" )
#pragma comment( lib, "cxcore.lib" )
#pragma comment( lib, "highgui.lib" )
#endif
int main()
{
IplImage *srcImage = NULL;
CvVideoWriter *pWriter = NULL;
int frameNum = 200;
//载入样例图像
srcImage = cvLoadImage("E:\\images\\frame_0000.jpg",CV_LOAD_IMAGE_COLOR);
if (!srcImage)
{
printf("can't load srcImage!\n");
return -1;
}
//缩放图像,用于存储srcImage扩大或是缩小的图像,这里我们选择不缩放,缩放函数为cvResize,后面我们会看到
IplImage *smallImage = cvCreateImage(cvSize(srcImage->width, srcImage->height), srcImage->depth, srcImage->nChannels);
//创建CvVideoWriter
if(USE_OPENCV20)
{
pWriter=cvCreateVideoWriter("E:\\video.avi",CV_FOURCC('M', 'J', 'P', 'G'),20.0,cvSize(smallImage->width,smallImage->height),1);
}
else
{
pWriter=cvCreateVideoWriter("E:\\video.avi",-1 ,15.0,cvSize(smallImage->width,smallImage->height),1);
}
if(!pWriter)
{
printf("can't create vedioWriter!\n");
}
char filename[500];
for (int i = 0; i < frameNum; i++)
{
printf("%d\n", i);
//构造文件名
char num[4];
sprintf(num, "%d", i);
if (i>=0 && i<10)
{
strcpy(filename, "E:\\images\\frame_000");
}
else if (i >= 10 && i < 100)
{
strcpy(filename, "E:\\images\\frame_00");
}
else
{
strcpy(filename, "E:\\images\\frame_0");
}
strcat(filename, num);
strcat(filename, ".jpg");
//载入图像
srcImage=cvLoadImage(filename,1);
if (!srcImage)
{
printf("can't load image!\n");
}
//缩放图像
cvResize(srcImage,smallImage);
//将图像写入视频
int ret = cvWriteFrame(pWriter,smallImage);
if (ret!=1)
{
printf("can't write to the video!\n");
return -1;
}
cvReleaseImage(&srcImage);
cvReleaseImage(&smallImage);
}
cvWaitKey(0);
//释放资源
cvReleaseImage(&srcImage);
cvReleaseImage(&smallImage);
cvReleaseVideoWriter(&pWriter);
return 0;
}
注意配置好opencv环境。。。