「眼睛成長記」(五)—映入眼帘
- 2020 年 4 月 10 日
- 筆記
我們前幾講描述了OpenCV使用VideoCapture打開視頻,關閉視頻並獲取視頻屬性。今天來看一下打開視頻之後,我們如何寫入視頻,本質是也就是如何對視頻進行編碼。同樣地,OpenCV為這個過程也提供了一個叫做VideoWriter的類。
打開寫入視頻的上下文:
open方法:
原型:
CV_WRAP virtual bool open(const String& filename, int fourcc, double fps, Size frameSize, bool isColor = true);
說明:
filename: 輸出的視頻文件名
fourcc: 由4個字符組成的編碼格式,如{『X』, '2', '6', '4'}
fps: 視頻的幀率
frameSize: 幀的大小
isColor: 是否為彩色視頻
寫入視頻數據:
write方法:
原型:
CV_WRAP virtual void write(const Mat& image);
說明 : 寫入前的原始圖片

判斷打開成功

isOpened()方法:
VideoWriter與VideoCapture類似,都有isOpened方法,用來判斷,上下文是否打開成功。成功返回true,失敗返回false。

這裡是代碼:
#include <opencv2/core.hpp> #include <opencv2/imgcodecs.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <iostream> using namespace cv; using namespace std; int main(int argc, char *argv[]) { VideoCapture cam(0); if (!cam.isOpened()) { cout << " cam open failed " << endl; getchar(); return -1; } cout << " cam open success. " << endl; namedWindow("cam"); Mat img; VideoWriter vw; int fps = cam.get(CAP_PROP_FPS); if (fps <= 0) { fps = 25; } vw.open("out.avi", VideoWriter::fourcc('X','2', '6', '4'), fps, Size(cam.get(CAP_PROP_FRAME_WIDTH), cam.get(CAP_PROP_FRAME_HEIGHT)), true); if (!vw.isOpened()) { cout << " video open failed " << endl; getchar(); return -1; } cout << " video open success " << endl; for (;;) { cam.read(img); if (img.empty()) break; imshow("cam", img); vw.write(img); if (waitKey(5) == 'q') break; } waitKey(); return 0;

代碼說明
1. 例子中使用VideoCapture打開本地攝像頭;
2. 使用VideoWriter指定x264編碼;
3.按q鍵退出程序。
4.用OpenCV的窗口顯示每一幀圖片。