opencv实现从视频读取每一帧图像保存并合成avi格式视频

  • Post author:
  • Post category:其他


我的方法是用两个mat生成的对象,frame,src,frame是读取了视频的每一帧图像,并实现了保存,src是单纯用于合成视频。目前有出现两个bug,一个是生成的avi格式视频过大,一个是获取的图像可能是颠倒的。

#include<opencv2/opencv.hpp>
#include<iostream>
using namespace cv;
using namespace std;

int main()
{
	VideoCapture capture("input.avi");
	long totalFrameNumber = capture.get(CAP_PROP_FRAME_COUNT);
	cout << "整个视频共" << totalFrameNumber << "帧" << endl;
	capture.set(CAP_PROP_POS_FRAMES, 0);
	double rate = capture.get(CAP_PROP_FPS);
	cout << "帧率:" << rate << endl;
	int delay = 1000 / rate;
	Mat frame;
	if (!capture.read(frame))
	{
		cout << "读取视频失败" << endl;
		return -1;
	}
	int isColor = 1;
	int fps = rate;
	
	
	//char savefile[200];
	int frameWidth = frame.cols;
	int frameHeight = frame.rows;
	VideoWriter writer;
	writer.open("out.avi", VideoWriter::fourcc('M', 'J', 'P', 'G'), 30, Size(frameWidth, frameHeight), 1);
	char savefile[200];
	Mat src;
	for (int i=0;i< totalFrameNumber; i++)
	{
		
		frame = frame.clone();
	/*	waitKey(delay);*/
		if (!capture.read(frame))
		{
			cout << "读取视频结束" << endl;
			break;
		}
		
		
		cout << "现在处理第" << i <<"帧" << endl;
		sprintf(savefile, "./img/img%d.jpg", i);
		imwrite(savefile, frame);
		/*frame = imread(savefile,1);*/
		src = imread(savefile, 1);
		if (src.empty())
		{
			cout << "图片读取完了" << endl;
			break;
		}

		imshow("Output Video", src);
		waitKey(1000 / rate);
		writer.write(src);

	}

	

	writer.release();
	capture.release();
	waitKey(0);
	return 0;

	
}



版权声明:本文为kll741原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。