OpenCV_读取文件夹下的图片生成视频文件

来源:互联网 发布:mac word文件丢失 编辑:程序博客网 时间:2024/04/30 13:24


下面这段代码实现了:使用OpenCV读取指定文件夹下的所有图片,然后生成avi视频文件。




[cpp] view plaincopyprint?
  1. //  读取文件夹下的图片生成视频文件  
  2. //  Author:www.icvpr.com  
  3. //  Blog:  http://blog.csdn.net/icvpr    
  4.   
  5. #include <iostream>  
  6. #include <string>  
  7. #include <io.h>  
  8.   
  9. #include <opencv2/opencv.hpp>  
  10.   
  11. using namespace std;  
  12. using namespace cv;  
  13.   
  14. int main(int argc, char** argv)  
  15. {  
  16.     // 图片集  
  17.     string fileFolderPath = "..\\images";  
  18.     string fileExtension = "jpg";  
  19.     string fileFolder = fileFolderPath + "\\*." + fileExtension;  
  20.   
  21.     // 输出视频  
  22.     string outputVideoName = "output.avi";  
  23.       
  24.     // openCV video writer  
  25.     VideoWriter writer;  
  26.       
  27.     int codec = 0;  
  28.     int frameRate = 25;  
  29.     Size frameSize;  
  30.   
  31.   
  32.     // 遍历文件夹  
  33.     char fileName[1000];  
  34.   
  35.     struct _finddata_t fileInfo;    // 文件信息结构体  
  36.   
  37.     // 1. 第一次查找  
  38.     long findResult = _findfirst(fileFolder.c_str(), &fileInfo);            
  39.     if (findResult == -1)  
  40.     {  
  41.         _findclose(findResult);   
  42.         return -1;  
  43.     }  
  44.       
  45.     // 2. 循环查找  
  46.     do   
  47.     {  
  48.         sprintf(fileName, "%s\\%s", fileFolderPath.c_str(), fileInfo.name);  
  49.   
  50.         if ( fileInfo.attrib == _A_ARCH)  // 是存档类型文件  
  51.         {         
  52.             Mat frame;  
  53.             frame = imread(fileName);    // 读入图片  
  54.             if (!writer.isOpened())  
  55.             {  
  56.                 frameSize.width  = frame.cols;  
  57.                 frameSize.height = frame.rows;  
  58.       
  59.                 if (!writer.open(outputVideoName, CV_FOURCC('D','I','V','X') , frameRate, frameSize, true))  
  60.                 {  
  61.                     cout << "open writer error..." << endl;  
  62.                     return -1;  
  63.                 }  
  64.             }  
  65.   
  66.             // 将图片数据写入  
  67.             writer.write(frame);  
  68.   
  69.             // 显示  
  70.             imshow("video", frame);  
  71.             waitKey(frameRate);  
  72.         }  
  73.   
  74.     } while (!_findnext(findResult, &fileInfo));    
  75.   
  76.   
  77.     _findclose(findResult);   
  78.   
  79.   
  80.     return 0;  
  81. }  


注意:

如果生成的avi视频的文件大小为0KB的话, 说明视频生成失败,可能的原因是编码器没有。下载安装Xvid编解码器后,再运行试一下,一般没有问题。

下载地址: http://www.xvidmovies.com/codec/



0 0
原创粉丝点击