图像与视频的相互转换

            在做跟踪算法的测试的时候,我们往往需要用找视频,而标准库的大多数是图像,这时候我们得将图像转换为视频格式;有时候我们获得一个视频中的每一帧图像,那么则得将视频转换为图像。

     (1)视频转换为图像:
#include <opencv2/opencv.hpp>

using namespace cv;
using namespace std;
int CropImageCount=0;
int main(int argc, char * argv[])
{
	
	char saveName[256];
	VideoCapture capture;
	//capture.open(0);
	capture.open("fingers.avi");
	Mat frame;
	cvNamedWindow("frame", CV_WINDOW_AUTOSIZE);
	if (!capture.isOpened())
	{
		cout << "capture device failed to open!" << endl;
		return -1;
	}
	
	while(1)
	{
	  capture>>frame;
	  if (frame.empty())
			return -1;

	  imshow("frame",frame);
	  sprintf(saveName,"fingers/%05d.jpg",++CropImageCount);
	  imwrite(saveName, frame);
	  if ( cvWaitKey(1) == 27 )
			break;
	}
	return 0;
}

      (2)图像转换为视频:

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

int fps=30;
int start_img=1,end_img=413;
char fileName[255];
string saveName="F:\\dataset\\50个测试视频序列\\Walking\\Walking\\img\\Walking.avi";
VideoWriter video;


int main(int argc, char * argv[])
{
 sprintf(fileName,"F:\\dataset\\50个测试视频序列\\Walking\\Walking\\img\\%04d.jpg",start_img);
 Mat image=imread(fileName);
 CvSize size=image.size();
 video=VideoWriter(saveName,CV_FOURCC(\'X\',\'V\',\'I\',\'D\'),fps,size);
 cvNamedWindow("frame", CV_WINDOW_AUTOSIZE);
 while(start_img<=end_img)
 {
   sprintf(fileName,"F:\\dataset\\50个测试视频序列\\Walking\\Walking\\img\\%04d.jpg",start_img);
   image=imread(fileName);
   if(image.empty())
   {
	   cout<<"can\'t open the file"<<endl;
	   return -1;
   }
   video.write(image);
   imshow("frame",image);
   if(waitKey(10)==27)
	   break;
   cout<<start_img<<endl;
   start_img++;
 }

 return 0;
}

版权声明:本文为rongbohou-scut原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/rongbohou-scut/p/6071267.html