引言
有个项目,需要将osg生成的批量图像转成视频;特点是,图像自带编号,类似于:
Ir_Scene_339.jpg 的格式。
操作中,使用OpenCV自带的video函数完成。
void ImageToVideo( )
{
VideoWriter video("test35.avi", CV_FOURCC('X', 'V', 'I', 'D'), 35.0, Size(1920, 1017));//设置视频尺寸和帧率
{
//输入图像的路径,此处可以优化:判断路径是文件夹还是文件,文件夹直接找内部的图像,文件,在去掉后缀和编号
String img_path0 = "H:\\项目\\图像处理模板\\c++\\CmakeBuildOpenCVPrj\\2021_3_17_18_44_38\\2021_3_17_10_12_6\\*.jpg";
vector<String> img;
glob(img_path0, img, false);
//获得不带后缀且不包含图像编号的去路径,类似于:H:\项目\图像处理模板
string NameOfPathNoPostfix = img[0].substr(0, img[0].rfind("_")+1);\c++\CmakeBuildOpenCVPrj\2021_3_17_18_44_38\2021_3_17_10_12_6\Ir_Scene_
for (size_t i = 0; i < img.size(); i++)
{
String img_path = NameOfPathNoPostfix + to_string(i) + ".jpg";
Mat image = imread(img_path);
resize(image, image, Size(1920, 1017));//修改图像尺寸,此处是标准大小
video << image;
}
cout << "处理完毕!" << endl;
}
}
效果
输入图像文件夹
输出视频文件
升级版
使用下面代码,可以生成一个独立的文件
#include<stdio.h>
#include <cstdio>
#include <string>
#include <iostream>
#include <stdint.h>
#include <math.h>
#include<stdio.h>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/core/core.hpp>
#include <cstdio>
#include <string>
#include <iostream>
#include <stdint.h>
#include "opencv2/core.hpp"
#include <opencv2/opencv.hpp>
#include <math.h>
#include <io.h>
using namespace std;
using namespace cv;
#ifdef _DEBUG
#pragma comment(lib,"opencv_world340d.lib")
#else
#pragma comment(lib,"opencv_world340.lib")
#endif
using namespace std;
using namespace cv;
int main(int argc, char * argv[])
{
cout << "输入文件夹路径:" << endl;
string path = argv[0];
cin >> path;//通过命令行获取文件夹路径
cout << "请输入视频文件名称:" << endl;
string vedeoName;
cin >> vedeoName;
cout << "请输入视频帧率:" << endl;
int fps;
cin >> fps;
cout << "请输入视频宽:" << endl;
int kuan;
cin >> kuan;
cout << "请输入视频高:" << endl;
int gao;
cin >> gao;
String img_path0 = path+"\\*.jpg";
vector<String> img;
glob(img_path0, img, false);
string NameOfPathNoPostfix = img[0].substr(0, img[0].rfind("_") + 1);//获得不带后缀且不包含图像编号的去路径
VideoWriter video(vedeoName+".avi", CV_FOURCC('X', 'V', 'I', 'D'), fps*1.0, Size(kuan, gao));
cout << "视频生成中,请稍等..." << endl;
for (size_t i = 0; i < img.size(); i++)
{
String img_path = NameOfPathNoPostfix + to_string(i) + ".jpg";
Mat image = imread(img_path);
resize(image, image, Size(kuan, gao));
video << image;
}
cout << "处理完毕!生成视频"+ vedeoName + ".avi" << endl;
waitKey(0);
}
在debug目录下回输出一个exe文件:
exe文件
双击可运行。
通过在控制台输入:图像文件夹路径、视频输出的名称、帧率、视频的宽、视频的高。会输出视频。
运行界面
本文介绍如何使用OpenCV将带有编号的图像批量转换为视频的方法。提供了两种实现方式,一种是固定参数的简单示例,另一种是通过命令行输入自定义视频参数的升级版程序。
—— 图像转视频&spm=1001.2101.3001.5002&articleId=120684384&d=1&t=3&u=b8352ac67f2348a99940adb5c481fb61)
2150

被折叠的 条评论
为什么被折叠?



