OpenCV3读取视频或摄像头

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

 1 // This is a demo introduces you to reading a video and camera 
 2 #include <iostream>
 3 #include <string>
 4 #include <sstream>
 5 using namespace std;
 6 
 7 // OpenCV includes
 8 #include <opencv2/core.hpp>
 9 #include <opencv2/highgui.hpp>
10 #include <opencv2/videoio.hpp> // for camera
11 using namespace cv;
12 
13 // OpenCV command line parser functions
14 // Keys accepted by command line parser
15 const char* keys = 
16 {
17     "{help h usage ? | | print this message}"
18     "{@video | | Video file, if not defined try to use webcamera}"
19 };
20 
21 int main(int argc, const char** argv)
22 {
23     CommandLineParser parser(argc, argv, keys);
24     parser.about("Reading a video and camera v1.0.0");
25 
26     // If requires help show
27     if (parser.has("help"))
28     {
29         parser.printMessage();
30         return 0;
31     }
32     String videoFile = parser.get<String>(0);
33 
34     // Check if params are correctly parsed in his variables
35     if (!parser.check())
36     {
37         parser.printErrors();
38         return 0;
39     }
40 
41     VideoCapture cap; 
42     if (videoFile != "")
43     {
44         cap.open(videoFile);// read a video file
45     }else {
46         cap.open(0);// read the default caera
47     }
48     if (!cap.isOpened())// check if we succeeded
49     {
50         return -1;
51     }
52 
53     namedWindow("Video", 1);
54     while (1)
55     {
56         Mat frame;
57         cap >> frame; // get a new frame from camera
58         imshow("Video", frame);
59         if (waitKey(30) >= 0) break;
60     }
61 
62     // Release the camera or video file
63     cap.release();
64     return 0;
65 }

  在我们解释如何读取视频文件或者摄像头输入之前,我们需要首先介绍一个非常有用的新类,它可以用于帮助我们管理输入的命令行参数,这个类在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;
}

 

posted @ 2016-05-19 20:18  XiaoManon  阅读(15635)  评论(0编辑  收藏  举报