OpenCVのコマンドラインパーサ

OpenCVのコマンドラインパーサを使って,オプションを設定します.
基本的な表記ルールに従う必要がありますが,慣れればベタに書くよりもずっと楽です.

#include "opencv2/opencv.hpp"

#include <iostream>
#include <string>

using std::string;
using std::cout;
using std::endl;

void help()
{
  cout << endl
       << "OpenCV command-line parser test." << endl
       << "Call:" << endl
       << "./parser -b -i=2 -f=5.3 str1str in3val" << endl
       << endl;
}

const char* keys = 
{
  //  keys  //
  //  "{short tag|long tag|default value|notification}"  //
  "{1|||sample string without option tag}"
  "{2||-100|sample int without option tag}"
  "{b|bool|false|sample boolean}"
  "{i|int|0|sample int}"
  "{f|float|0.0|sample float}"
};

int main( int argc, const char** argv )
{
  //help();

  //  parser  //
  cv::CommandLineParser parser(argc, argv, keys);

  //  without 
  string str_1 = parser.get<string>("1");
  int   in_2 = parser.get<int>("2");
  //  value as corresponding type  //
  bool  bo_b = parser.get<bool>("b");
  int   in_i = parser.get<int>("i");
  float fl_f = parser.get<float>("f");
  //  value as string  //
  string str_b = parser.get<string>("b");
  //string str_i = parser.get<string>("i");
  //string str_f = parser.get<string>("f");

  cout << "str_1 = " << str_1 << endl;
  cout << "in_2 = " << in_2 << endl;

  cout << "bo_b = " << bo_b << endl;
  cout << "in_i = " << in_i << endl;
  cout << "fl_f = " << fl_f << endl;

  cout << "str_b = " << str_b << endl;
  //cout << "str_i = " << str_i << endl;
  //cout << "str_f = " << str_f << endl;

  return 0;
}

オプションなし実行結果(デフォルト値が使われます)

./parser

str_1 = 
in_2 = -100
bo_b = 0
in_i = 0
fl_f = 0
str_b = false

オプションあり実行結果

  • 値が必要なタグについては,=で結んでも良いし,スペースで区切っても良いようです.
./parser string_001 333 -b=true -i=28 -f=7.5

str_1 = string_001
in_2 = 333
bo_b = 1
in_i = 28
fl_f = 7.5
str_b = true

./parser string_001 333 -b true -i 28 -f 7.5

str_1 = string_001
in_2 = 333
bo_b = 1
in_i = 28
fl_f = 7.5
str_b = true

無効な書き方

  • タグなし引数がintでパースできないときは,0が返ってきました.
  • 値が必要なタグに値をつけないと,次のタグを誤って値としてパースしまいました.
  • boolでのパースについては,値をつけなくとも正しく動作しました.
./parser string_001 not_int -b -i -f

str_1 = string_001
in_2 = 0
bo_b = 1
in_i = 149075172
fl_f = 0
str_b = true
<追加dump出力>
str_i = -f
str_f = 0.0

このパーサだけでも,かなり便利です.