C++视频分解和图片合成视频代码

附上两个常用的代码,一个是视频分解,一个是图片集合成video。

1、视频分解代码

//将视频分解成一张张图片并保存
#include"opencv2/opencv.hpp"
using namespace cv;//如果不定义命名空间则图像采集这个功能是无效的
void main()
{
	VideoCapture cap("D:\\Photo and Video\\depth\\depthCorrect.mp4");
	Mat frame;
	char outfile[50];
	if(!cap.isOpened())//打开失败便退回
		return;
	int totallFrame=cap.get(CV_CAP_PROP_FRAME_COUNT);//获取视频总帧数
	for(int i=1;i<=totallFrame;i++)
	{
	   cap>>frame;//取帧
		if(frame.empty())
			break;
		sprintf(outfile,"D:\\Photo and Video\\depth1\\%d.png",i);//这行代码的作用就是提供一个标准化的名字
		imwrite(outfile,frame);//outfile之所以不加引号是因为outfile是一个已经被定义的字符串
		imshow("video",frame);
		waitKey(100);//每隔两秒显示1帧,数值越小播放越快,有种快进的感觉,后退也一样
	}
	  cap.release();
	  destroyAllWindows();
}

2、图片合成video,该代码没有优化,需要手动调节图片大小以及帧率

#include <iostream>
#include <opencv2\opencv.hpp>


using namespace std;
using namespace cv;
void Image_To_Video();

int main()
{
	Image_To_Video();
	waitKey(0);
	return 0;
}

void Image_To_Video()
{
	char image_name[80];
	VideoWriter writer;
	int frame_fps=20;
	int frame_width = 640;
	int frame_height = 480;

	writer = VideoWriter("D:\\Photo and Video\\lsd_slam_dataset.avi", CV_FOURCC('X', 'V', 'I', 'D'),
		frame_fps, Size(frame_width, frame_height),true);
	cout << "frame_width is " << frame_width << endl;
	cout << "frame_height is " << frame_height << endl;
	cout << "frame_fps is " << frame_fps << endl;
	//namedWindow("image to vedio", CV_WINDOW_AUTOSIZE);
	int num = 2702;// the number of picture
	int i = 1;
	Mat img;

	for (i = 1; i < num;i++)
	{
		//cout << "1\n";
		sprintf_s(image_name, "D:\\images\\%05d.png",i);
		cout << image_name << endl;
		img = imread(image_name);// imread picture
		if (img.empty())
		{
			cout << "can not load image file...\n";
			break;
		}
		//imshow("image to vedio", img);
		writer << img;
		if (waitKey(30) == 27 || i == num)
		{
			cout << "please press the  ESC key " << endl;
			break;
		}
		cout << "write end!!\n";

	}
}

猜你喜欢

转载自blog.csdn.net/huoguangyao/article/details/89328986