Opencv中将视频保存为连续的图片和连续的图片保存为视频

一直觉得Opencv是个很实用的很伟大的东西,很多功能总是能够在不经意间实现,下面就将AVI视频每一帧保存为图片(.jpg,.bmp),和连续图片保存为视频来演示一下:
   直接贴代码,只要学了Opencv一个星期的,绝对看的懂了:
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <cv.h>
#include <highgui.h>
#define NUM_FRAME 300 //只处理前300帧,根据视频帧数可修改


void Video_to_image(char* filename)
{
    printf("------------- video to image ... ----------------n");
    //初始化一个视频文件捕捉器
    CvCapture* capture = cvCaptureFromAVI(filename);   
   //获取视频信息
    cvQueryFrame(capture);
   int frameH    = (int) cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);
   int frameW    = (int) cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
   int fps       = (int) cvGetCaptureProperty(capture, CV_CAP_PROP_FPS);
   int numFrames = (int) cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_COUNT);
   printf("tvideo height : %dntvideo width : %dntfps : %dntframe numbers : %dn", frameH, frameW, fps, numFrames);
   //定义和初始化变量
   int i = 0;
   IplImage* img = 0;
   char image_name[13];
   cvNamedWindow( "mainWin", CV_WINDOW_AUTOSIZE );
   //读取和显示
   while(1)
  {
    img = cvQueryFrame(capture); //获取一帧图片
    cvShowImage( "mainWin", img ); //将其显示
    char key = cvWaitKey(20);
    sprintf(image_name, "%s%d%s", "image", ++i, ".jpg");//保存的图片名
    cvSaveImage( image_name, img);   //保存一帧图片
    if(i == NUM_FRAME) break;
  }
   cvReleaseCapture(&capture);
   cvDestroyWindow("mainWin");
}


void Image_to_video()
{
     int i = 0;
     IplImage* img = 0;
     char image_name[13];
     printf("------------- image to video ... ----------------n");

     //初始化视频编写器,参数根据实际视频文件修改
     CvVideoWriter *writer = 0;
    int isColor = 1;
    int fps     = 30; // or 25
    int frameW = 400; // 744 for firewire cameras
    int frameH = 240; // 480 for firewire cameras
    writer=cvCreateVideoWriter("out.avi",CV_FOURCC('X','V','I','D'),fps,cvSize(frameW,frameH),isColor);
    printf("tvideo height : %dntvideo width : %dntfps : %dn", frameH, frameW, fps);

    //创建窗口
    cvNamedWindow( "mainWin", CV_WINDOW_AUTOSIZE );
    while(i<NUM_FRAME)
   {
      sprintf(image_name, "%s%d%s", "image", ++i, ".jpg");
      img = cvLoadImage(image_name);
      if(!img)
     {
        printf("Could not load image file...n");
        exit(0);
     }
     cvShowImage("mainWin", img);
     char key = cvWaitKey(20);
     cvWriteFrame(writer, img);
   }
     cvReleaseVideoWriter(&writer);
     cvDestroyWindow("mainWin");
}


   int main(int argc, char *argv[])
  {
      char filename[13] = "1.avi";
      Video_to_image(filename); //视频转图片
       return 0;
  }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值