图片视频相互转换

时间:2021-08-05 17:50:54

配置opencv3.0+VS2013(其他版本更改include文件即可)
一、图片转换为视频

#include "stdAfx.h"
#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
using namespace cv;
using namespace std;
int main()
{
// 定义相关参数
const int num = 220;//图片总数
char fileName[50];
char windowName[50];
cv::Mat srcImage;

char* outfile = "E:\\View1.avi";//输出视频路径
double fps = 15;
CvSize size = cvSize(768,576);
//创建输出视频文件
CvVideoWriter* Save_result = NULL;
Save_result = cvCreateVideoWriter(outfile, CV_FOURCC('X', 'V', 'I', 'D'), fps, size, 1);
IplImage* dstImg = cvCreateImage(size, IPL_DEPTH_8U, 3);//创建要保存的图像
for (int i = 1; i <= num; i++)
{
// sprintf读入指定路径下图片序列
sprintf_s(fileName, "F:\\毕业相关的程序\\测试数据集\\View_001\\1 (%d).jpg", i);//文件名格式为1(11).jpg格式,如需更改,直接做替换
sprintf_s(windowName, "video");
// 按照图像文件名读取
srcImage = cv::imread(fileName);
if (!srcImage.data)
{
std::cout << "No data!" << std::endl;
return -1;
}
dstImg = &IplImage(srcImage);
cvWriteFrame(Save_result, dstImg);
cv::namedWindow(windowName);
cv::imshow(windowName, srcImage);
waitKey(10);
std::cout << "NO: " << i << std::endl;
/* 该处可以添加处理步骤 */
}
cvReleaseVideoWriter(&Save_result);
cvDestroyWindow(windowName);//必须释放VideoWriter、销毁窗口,否则视频无法播放
cv::waitKey(0);
return 0;
}

二、视频转换成图片

CvCapture* capture = cvCaptureFromAVI("F:\\毕业论文相关\\机场视频\\安检区外北侧.ts");
int i = 0;
IplImage* img = 0;
char image_name[50];
cvNamedWindow("实时视频");
//读取和显示
while (1)
{
img = cvQueryFrame(capture); //获取一帧图片
if (img == NULL)
break;

cvShowImage("实时视频", img); //将其显示
char key = cvWaitKey(20);
sprintf_s(image_name, "%s%d%s","F:\\毕业论文相关\\机场视频\\density_img_", ++i, ".jpg");//保存的图片名
if (i%5==0)
{
cvSaveImage(image_name, img); //保存一帧图片
}

}

cvReleaseCapture(&capture);
cvDestroyWindow("实时视频");