首页
学习
活动
专区
圈层
工具
发布

“眼睛成长记”(五)---映入眼帘

写入视频

我们前几讲描述了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。

这里是代码:

代码语言:javascript
复制
#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的窗口显示每一帧图片。

举报
领券