您的位置:首页 > 运维架构

OpenCV3读取视频或摄像头

2016-05-19 20:18 330 查看
我们可以利用OpenCV读取视频文件或者摄像头的数据,将其保存为图像,以用于后期处理。下面的实例代码展示了简单的读取和显示操作:

// This is a demo introduces you to reading a video and camera
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

// OpenCV includes
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/videoio.hpp> // for camera
using namespace cv;

// OpenCV command line parser functions
// Keys accepted by command line parser
const char* keys =
{
"{help h usage ? | | print this message}"
"{@video | | Video file, if not defined try to use webcamera}"
};

int main(int argc, const char** argv)
{
CommandLineParser parser(argc, argv, keys);
parser.about("Reading a video and camera v1.0.0");

// If requires help show
if (parser.has("help"))
{
parser.printMessage();
return 0;
}
String videoFile = parser.get<String>(0);

// Check if params are correctly parsed in his variables
if (!parser.check())
{
parser.printErrors();
return 0;
}

VideoCapture cap;
if (videoFile != "")
{
cap.open(videoFile);// read a video file
}else {
cap.open(0);// read the default caera
}
if (!cap.isOpened())// check if we succeeded
{
return -1;
}

namedWindow("Video", 1);
while (1)
{
Mat frame;
cap >> frame; // get a new frame from camera
imshow("Video", frame);
if (waitKey(30) >= 0) break;
}

// Release the camera or video file
cap.release();
return 0;
}


  在我们解释如何读取视频文件或者摄像头输入之前,我们需要首先介绍一个非常有用的新类,它可以用于帮助我们管理输入的命令行参数,这个类在OpenCV 3.0中被引入,被称为CommandLineParser类。

// OpenCV command line parser functions
// Keys accepted by command line parser
const char* keys =
{
"{help h usage ? | | print this message}"
"{@video | | Video file, if not defined try to use webcamera}"
};


  对于一个命令行解析器(command-line parser)而言,我们首先需要做的事情就是在一个常量字符串向量中定义我们需要或者允许出现的参数列表。其中的每一行都有一个固定的模式:

{ name_param | default_value | description }


  其中,name_param(参数名称)参数之前可以添加“@”符号,用于定义将这个参数作为默认输入。我们可以使用不止一个参数。

CommandLineParser parser(argc, argv, keys);


  构造函数将会读取主函数的输入参数和之前定义好的参数作为一个默认输入。

// If requires help show
if (parser.has("help"))
{
parser.printMessage();
return 0;
}


  成员方法has()将会检查指定的参数是否存在。在这个示例程序中,我们将会检查用户是否添加了“-h”、"-?"、“--help”或者"--usage"参数,如果有,然后使用printMessage()成员方法输出所有的参数描述。

String videoFile = parser.get<String>(0);


  使用get<typename>(name_param)函数,我们可以访问和读取输入参数的任何内容。上一行程序代码也可以写成:

String videoFile = parser.get<String>("@video");


  在获取了所有需要的参数之后,我们可以检查是否这些参数都已经被正确处理,如果其中有参数未能成功解析,则显示一条错误信息。

// Check if params are correctly parsed in his variables
if (!parser.check())
{
parser.printErrors();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: