Most of the OpenCV programs that I have written so far require explicitly taking some input from the user as a command-line argument. For example, it is highly likely that a OpenCV program would require an image (or video) to operate upon and hence requires a path to that multimedia file as an input. Instead of having the user type in the path in response to a program-generated prompt after the code has begun it’s execution, it is much more orderly, compact and convenient to supply those parameters as command-line arguments and have the logic to parse the input parameters embedded in our code.
For this exact purpose, I wrote a small, minimalist command-line parser in C++ that works out-of-the box with OpenCV programs.
The functionality of the parser is bestowed upon by three functions which are described in detail:
void setCommandOptions(vector<string>& args, int argc, char** argv)
argvthe variables through which the command-line arguments are actually passed down into the
argcis the number of strings (arguments) pointed to by
argv. This function does the simple task of copying all the command-line arguments from
argvinto the vector of strings named
args. The for loop starts from 1 nbecause, by default the first argument in
argv(corresponding to the index 0 i.e.
argv) is the name of your executable. For example, if I run a C++ program by executing
./myprogram arg1from the terminal,
argvwould point to
string getCommandOptions(const vector<string>& args, const string& opt)
The primary aim of this function is to retrieve the arguments corresponding to the command-line option opt (the 2nd argument to the function). So, if the program was invoked using the command
./sample-code -image ~/Pictures/picture.jpg, then the function call
getCommandOptions(args, “-image”)would return the string
“~/Pictures/picture.jpg”. Note that
“-image”is the option and
“~/Pictures/picture.jpg”is the argument here. The implementation uses the
find()function from the
<algorithm>header to accomplish the task along with certain sanity checks as to whether the option opt exists or not and ensuring that there is a argument corresponding to the sought after option. That is, in cases like
./sample-code -image, a function invocation of the form
getCommandOptions(args, “-image”)would return an empty string because of the absence of a argument with the
bool doesCmdOptionExist(const vector<string>& args, const string& opt)
A predicate to check whether the command line option opt exists in
The complete code can be viewed here.