图像视频互相转化
(1)图像转视频
// VideoWriter.cpp : 定义控制台应用程序的入口点。
//
//#include "stdafx.h"
#include "cv.h"
#include "highgui.h"
#include "iostream"
using namespace std;
int main(int argc, char* argv[])
{
double fps = 9;//视频压缩帧率
CvSize size = cvSize(128, 64);//图片序列中每张图片的宽高
CvVideoWriter* writer = cvCreateVideoWriter("E:\\20160923\\a2.avi", -1, fps, size);
int n;
char str[200];
memset(str, '\0', 200 * sizeof(char));
for (int i = 1; i<80; i++)
{
n = i / 10;
//memset(str, '\0', 200 * sizeof(char));
//sprintf(str, "c:/result/%d.jpg", i);
//sprintf(str, "c:/result/%d.jpg", i);
sprintf(str, "E:\\20160923\\a images_dif_size\\%d.png", i);
IplImage* colorIn = cvLoadImage(str);
int flag = cvWriteFrame(writer, colorIn);
cout << flag << endl;
cvReleaseImage(&colorIn);
}
cvReleaseVideoWriter(&writer);
system("pause");
return 0;
}
(2)视频转图像
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/objdetect/objdetect.hpp>
#include <opencv2/ml/ml.hpp>
using namespace std;
using namespace cv;
void main()
{
char* vedio = "E:\\20160923\\a.avi";//视频文件路径
CvCapture *cap = cvCaptureFromFile(vedio);
if (cap == NULL)
{
printf("vedio to iamges failed.");
}
char cur_fn[255];//图片文件名
char* ext = ".jpg";//图片格式
char* prefix = "E:\\20160923\\a images\\";//保存图片的文件夹路径 一定要有,因为OpenCV不会自动创建文件夹
IplImage* pImg = NULL;
int frame = 0;
while ((pImg = cvQueryFrame(cap)) != NULL)
{
frame++;
strcpy(cur_fn, "");
sprintf(cur_fn, "%s%d%s", prefix, frame, ext);//这里的设置适合形如 123.jpg 124.jpg的图片序列
cvSaveImage(cur_fn, pImg, NULL);
}
cvReleaseImage(&pImg);
cvReleaseCapture(&cap);
}
////////////////////////////////////////////////////////////////////