1. 程式人生 > >Opencv讀取和儲存視訊

Opencv讀取和儲存視訊

   在Opencv中我們經常會需要讀取視訊,對視訊進行操作,最後儲存視訊,這裡我們寫了一個示例程式實現讀取視訊,將視訊幀灰度化,最後儲存視訊的一個流程。

//實現對視訊的讀入,灰度化,儲存視訊的功能
#include <cv.h>
#include<highgui.h>
#include <iostream>
using namespace std;
int main()
{
	char *video="test.avi";//視訊檔案,名字可以修改
	CvCapture *cap=cvCaptureFromAVI(video);//從視訊檔案中讀取
	/*CvCapture *cap=cvCaptureFromCAM(0);*///從攝像頭捕捉
	IplImage *img=cvQueryFrame(cap);//讀取一幀
	if (!img)
	{
		cout<<"讀取視訊出錯"<<endl;
		exit(0);
	}


	//獲取視訊檔案的引數
	int frameHeight  =(int) cvGetCaptureProperty(cap,CV_CAP_PROP_FRAME_HEIGHT);//幀高度
	int frameWidth   =(int) cvGetCaptureProperty(cap,CV_CAP_PROP_FRAME_WIDTH);//幀寬度
	int fps          =(int) cvGetCaptureProperty(cap,CV_CAP_PROP_FPS);//幀率
	int numFrames    =(int) cvGetCaptureProperty(cap,CV_CAP_PROP_FRAME_COUNT);//幀數

	cout<<"視訊影象的高度是"<<frameHeight<<"  寬度是"<<frameWidth<<endl;
	cout<<"視訊的幀率是"<<fps<<"    幀數是"<<numFrames<<endl;

	//CvVideoWriter *writer=cvCreateVideoWriter("out.avi",CV_FOURCC('x','v','i','d'),fps,cvSize(frameWidth,frameHeight));//對於彩色視訊檔案
	CvVideoWriter *writer=cvCreateVideoWriter("out.avi",-1,fps,cvSize(frameWidth,frameHeight),0);//對於灰度視訊檔案
	IplImage *grayimg=cvCreateImage(cvSize(frameWidth,frameHeight),8,1);
	while (img)
	{
		cvCvtColor(img,grayimg,CV_BGR2GRAY);
		cvNamedWindow("灰度圖",0);
		cvShowImage("灰度圖",grayimg);
		cvWriteFrame(writer,grayimg);
		if(cvWaitKey(20)==27)//等待20毫秒,按下Esc退出
			break;;
		img=cvQueryFrame(cap);
	}
	//注意不用釋放img
	cvReleaseImage(&grayimg);
	cvReleaseCapture(&cap);
	cvReleaseVideoWriter(&writer);
}