opencv implements reading video and saving video

  • 2020-06-01 10:44:58
  • OfStack

Have to say opencv is a powerful thing, before doing a project to a module is used for image processing, this time want to slow the broadcast of a video, see opencv have Internet before this functionality, accidentally try one today, not much, mainly to do a small record have 1 point to pay attention to the little problem say 1, the code is not much, basically also is copy online


#include <iostream> 
#include <assert.h> 
#include <opencv/cv.h> 
#include <opencv/highgui.h> 
#include <math.h> 
 
using namespace std; 
#ifdef NDEBUG 
#pragma comment(lib, "highgui210.lib") 
#pragma comment(lib, "cxcore210.lib") 
#pragma comment(lib, "ml210.lib") 
#pragma comment(lib, "cv210.lib") 
#else 
#pragma comment(lib, "highgui210d.lib") 
#pragma comment(lib, "cxcore210d.lib") 
#pragma comment(lib, "ml210d.lib") 
#pragma comment(lib, "cv210d.lib") 
#endif 
 
char g_fileName[] = "C:\\Users\\Desktop\\test.avi"; 
char g_winodwName[] = "Cv Test"; 
int main() 
{ 
 ::cvNamedWindow("g_winodwName", CV_WINDOW_AUTOSIZE); 
 CvCapture *pCvCapture = NULL; 
 pCvCapture = cvCreateFileCapture(g_fileName); 
 assert(NULL != pCvCapture); 
 IplImage *pIplFrame = NULL; 
 
 char out1[] = "C:\\Users\\Desktop\\out1.avi"; 
 double fps1 = cvGetCaptureProperty(pCvCapture, 
     CV_CAP_PROP_FPS); 
 
 CvSize size1 = cvSize((int)cvGetCaptureProperty(pCvCapture, 
       CV_CAP_PROP_FRAME_WIDTH), 
    (int)cvGetCaptureProperty(pCvCapture, 
       CV_CAP_PROP_FRAME_HEIGHT)); 
 
 
 CvVideoWriter *wrVideo1 = cvCreateVideoWriter(out1, 
       CV_FOURCC('X','V','I','D'), 
       10, 
       size1); 
 IplImage *gray1 = cvCreateImage(size1,8,1); 
 
 while (true) 
 { 
 pIplFrame = cvQueryFrame(pCvCapture); 
 if (NULL == pIplFrame) 
 { 
  break; 
 } 
 else 
 { 
  ::cvShowImage(g_winodwName, pIplFrame); 
  // Save the video  
  cvCvtColor(pIplFrame,gray1,CV_RGB2GRAY); 
  cvWriteFrame(wrVideo1,gray1); 
 
  if (27 == ::cvWaitKey(120)) 
  { 
  break; 
  } 
 } 
 } 
 
 
 ::cvReleaseImage(&pIplFrame); 
 ::cvDestroyWindow(g_winodwName); 
 ::cvReleaseImage(&gray1); 
 ::cvReleaseVideoWriter(&wrVideo1); 
 
 return cin.get(); 
} 

There are several small place need to pay attention to, the first is cvCreateFileCapture () this function if the path right or return NULL, 1 kind is because no decoder installed, 1 has two decoders k_lite and xvid, specific which one can do it I'm not sure, because when I tried both installed and then run correctly, and one is cvCreateVideoWriter () this function parameters in it, and the third parameter is set the video frame, the smaller the number, the slower, should the number of frames per second, The principle of saving video is also to save image frames to video files. That is to say, the video is playing 1 picture frame flash.


Related articles: