2016年12月15日 星期四

opencv c++ 錄製Video

OpenCV用VideoWriter類別來製作影像檔,一般的影像檔除了影像壓縮與編碼規格之外,還有聲音與字幕,但OpenCV開發時為求簡化,所以並沒有納入音軌與字幕,只單純處理影像,現在所有影像編碼都有獨一的短名,像XVID、CIVX和H264等,在使用VideoWriter時,我們可指定編碼方式。
VideoWriter建構式

VideoWriter::VideoWriter()


VideoWriter::VideoWriter(const string& filename, int fourcc, double fps, Size frameSize, bool isColor=true)


  • filename:輸出影像檔的檔名。
  • fourcc:編碼方式,舉例來說CV_FOURCC(‘P’,’I’,’M’,’1′)是MPEG-1,CV_FOURCC(‘M’,’J’,’P’,’G’)是motion-jpeg。
  • fps:更新頻率。
  • frameSize:影像檔的影像尺寸。
  • isColor:是否為彩色影像。

VideoWriter初始化


bool:VideoWriter::open(const string& filename, int fourcc, double fps, Size frameSize, bool isColor=true)

初始化參數和建構式相同,功用也一樣,我們可以建構式就指定影像檔各設定,也可以先用VideoWriter()這個建構式,接著用open()設定影像檔。
bool VideoWriter::isOpened()

檢查是否初始化成功,如果成功返回true,否則返回false。
VideoWriter寫入影像

VideoWriter& VideoWriter::operator<<(const Mat& image)

void VideoWriter::write(const Mat& image)

透過這個函式,將image寫入要輸出的影片檔。

以下程式碼開啟攝影機鏡頭讀取影像,並將這些及時影像存成avi檔:

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace cv;
int main()
{
VideoCapture capture(0);
VideoWriter writer("VideoTest.avi", CV_FOURCC('M', 'J', 'P', 'G'), 25.0, Size(640, 480));
Mat frame;

while (capture.isOpened())
{
capture >> frame;
writer << frame;
imshow("video", frame);
if (cvWaitKey(20) == 27){
break;
}
}

}

Reference:

沒有留言:

張貼留言