1. 程式人生 > >視訊檔案按幀抓取影象並儲存

視訊檔案按幀抓取影象並儲存

一.原材料

       win10,opencv3.0,vs2013,test.MP4。只需要配置好opencv的環境就好,3.0可以直接用MP4型別的視訊資料。

二.實現功能:

      1.顯示視訊的具體資訊,幀數,幀率,解析度等;

      2.對視訊進行逐幀抓取影象;

      3.對影象尺寸進行變換--縮放,我電腦是AMD顯示卡無gpu加速,只能縮小影象,減少以後的訓練時間;

      4.將影象儲存到特定的資料夾下。便於以後製作資料集。

三.程式碼實現:

<span style="font-size:14px;color:#000000;background-color: rgb(255, 255, 255);"></span><pre class="html" name="code">#include<cstring>    <span style="color:#ff0000;">////實現對視訊進行按幀抓取影象並儲存////</span>
#include "cv.h"
#include "highgui.h"
#include"stdlib.h"

using namespace std;

int main()
{
     CvCapture *capture;
     capture = cvCreateFileCapture("6515_10.124.6.230_2010-12-08_12-19-23(1).mp4");
     assert(capture!=NULL);        <span style="color:#ff0000;"> //使用斷言對函式引數進行確認,“假設”不成立則中斷。
	                            //顯示視訊資訊--我的視訊h576*w704,fps25,frame number15036
</span>	 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 : %d\n\tvideo width : %d\n\tfps : %d\n\tframe numbers : %d\n", frameH, frameW, fps,          numFrames);
	
     IplImage *frame=0;            //初始化定義                      
     int n = 0;                    //初始化
     char image_name[256];         //image_name的名字、型別、存放路徑的字串長度,小了可能會記憶體溢位中斷

     while(1)                      
     {
        frame = cvQueryFrame(capture);     //獲取一幀影象
		
	sprintf(image_name,"%s%d%s","D:\\OPenCV\\images\\",++n,".jpg");
                                           //儲存的檔案地址、型別、名稱,中文路徑儲存不了。
	IplImage*out = cvCreateImage(CvSize(frame->width / 2, frame->height / 2), frame->depth,frame->nChannels);
	cvPyrDown(frame,out,CV_GAUSSIAN_5x5); //下采樣縮小影象
        cvSaveImage(image_name,out);     //儲存一幀影象
	cvReleaseImage(&out);
          
        if(n==15011)break;               //共15011幀
    }
	  
        cvReleaseCapture(&capture);
	frame = NULL;  //cvReleaseImage()和cvCreateImage()相對應的。在程式中如果沒有使用cvCreateImage()“建立”就不能“釋放”。
	system("pause");                 //是為了讓輸出結果在cmd停留,前提是有#include"stdlib.h"
        return 0;
}

四.常見問題:

     報錯:sprintf不安全請替換巴拉巴拉。。。 解決方法:檢視>>其他視窗>>屬性管理器>>Debug Win32  or Relesae Win32>>右鍵MicrosftCppWin32.user>>屬性頁>>C/C++>>前處理器>>前處理器定義>>編輯裡面新增    _CRT_SECURE_NO_WARNINGS 儲存即可 。

    其他記憶體溢位,無圖片產生等問題程式碼註釋的很仔細了。

五.待解決問題:

   指定區域的逐幀抓取,下一篇研究用這篇抓取到的影象製作caffe需要的leveldb型資料集。