opencv提取视频帧,将多张图片组合成视频(C++)

OpenCV-视频处理-视频处理5191 2

opencv提取视频帧,将多张图片组合成视频(C++)

作者:bit452

参考:http://blog.sina.com.cn/s/blog_5f5931540100rt4n.html

opencv结合c++实现了,提取视频的每一帧并保存。将多幅图片合成一个视频

第一个函数

 

void Video_To_Image(string filename)

作用是 生成并保存一个视频的每一帧

 

#include 
#include 
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/core/core.hpp"

using namespace std;
void  Video_To_Image(string filename);
void  Image_To_Video();
int main()
{
	string video_name = "test.avi";//注意,使用string时,若不用using namespace std,需要使用std::string
	Video_To_Image(video_name);
	Image_To_Video();
	return 0;
}
void Video_To_Image(string filename)
{
	cout << "---------------Video_To_Image-----------------" << endl;
	cv::VideoCapture capture(filename);
	if (!capture.isOpened())
	{
		cout << "open video error";
	}
		/*CV_CAP_PROP_POS_MSEC – 视频的当前位置(毫秒)
		CV_CAP_PROP_POS_FRAMES – 视频的当前位置(帧)
		CV_CAP_PROP_FRAME_WIDTH – 视频流的宽度
		CV_CAP_PROP_FRAME_HEIGHT – 视频流的高度
		CV_CAP_PROP_FPS – 帧速率(帧 / 秒)*/
	int frame_width = (int)capture.get(CV_CAP_PROP_FRAME_WIDTH);
	int frame_height = (int)capture.get(CV_CAP_PROP_FRAME_HEIGHT);
	float frame_fps = capture.get(CV_CAP_PROP_FPS);
	int frame_number = capture.get(CV_CAP_PROP_FRAME_COUNT);//总帧数
	cout << "frame_width is " << frame_width<(img_name.data()), "%s%d%s", "image", ++num, ".jpg");//保存的图片名
		sprintf(image_name, "%s%d%s", "image", ++num, ".jpg");//保存的图片名
		img_name = image_name;
		imwrite(img_name, frame);//保存保存一帧图片
		if (cv::waitKey(30) == 27||num==frame_number)
		{
			cout << "按下ESC键" << endl;
			break;
		}
	}
	capture.release();//这句话貌似不需要
}


 

 

 
void  Image_To_Video();

作用是将多张图片合成视频

定义如下

 

void Image_To_Video()
{
	cout << "---------------Video_To_Image-----------------" << endl;
	char image_name[20];
	string s_image_name;
	cv::VideoWriter writer;
	int isColor = 1;//不知道是干啥用的
	int frame_fps = 30;
	int frame_width = 640;
	int frame_height = 480;
	using namespace cv;
	string video_name = "out.avi";
	writer = VideoWriter(video_name, CV_FOURCC('X', 'V', 'I', 'D'),frame_fps,Size(frame_width,frame_height),isColor);
	cout << "frame_width is " << frame_width << endl;
	cout << "frame_height is " << frame_height << endl;
	cout << "frame_fps is " << frame_fps << endl;
	cv::namedWindow("image to video", CV_WINDOW_AUTOSIZE);
	int num = 160;//输入的图片总张数
	int i = 0;
	Mat img;
	while (i<=num)
	{
		sprintf(image_name, "%s%d%s", "image", ++i, ".jpg");
		s_image_name = image_name;
		img = imread(s_image_name);//读入图片
		if (!img.data)//判断图片调入是否成功
		{
			cout << "Could not load image file...\n" << endl;
		}
		imshow("image to video",img);
		//写入
		writer.write(img);
		if (cv::waitKey(30) == 27 || i == 160)
		{
			cout << "按下ESC键" << endl;
			break;
		}		
	}
}


 

 

 

 

你可能感兴趣的:(opencv提取视频帧,将多张图片组合成视频(C++))