diff --git a/samples/cpp/3calibration.cpp b/samples/cpp/3calibration.cpp index cf37e65006..12f2c81fca 100644 --- a/samples/cpp/3calibration.cpp +++ b/samples/cpp/3calibration.cpp @@ -6,6 +6,7 @@ #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/imgcodecs/imgcodecs.hpp" #include "opencv2/highgui/highgui.hpp" +#include "opencv2/core/utility.hpp" #include #include @@ -20,12 +21,12 @@ static void help() { printf( "\nThis is a camera calibration sample that calibrates 3 horizontally placed cameras together.\n" "Usage: 3calibration\n" - " -w # the number of inner corners per one of board dimension\n" - " -h # the number of inner corners per another board dimension\n" - " [-s ] # square size in some user-defined units (1 by default)\n" - " [-o ] # the output filename for intrinsic [and extrinsic] parameters\n" + " -w= # the number of inner corners per one of board dimension\n" + " -h= # the number of inner corners per another board dimension\n" + " [-s=] # square size in some user-defined units (1 by default)\n" + " [-o=] # the output filename for intrinsic [and extrinsic] parameters\n" " [-zt] # assume zero tangential distortion\n" - " [-a ] # fix aspect ratio (fx/fy)\n" + " [-a=] # fix aspect ratio (fx/fy)\n" " [-p] # fix the principal point at the center\n" " [input_data] # input data - text file with a list of the images of the board\n" "\n" ); @@ -42,7 +43,7 @@ static void calcChessboardCorners(Size boardSize, float squareSize, vector > imagePoints1, +static bool run3Calibration(vector > imagePoints1, vector > imagePoints2, vector > imagePoints3, Size imageSize, Size boardSize, @@ -177,65 +178,48 @@ int main( int argc, char** argv ) int i, k; int flags = 0; Size boardSize, imageSize; - float squareSize = 1.f, aspectRatio = 1.f; - const char* outputFilename = "out_camera_data.yml"; - const char* inputFilename = 0; + float squareSize, aspectRatio; + string outputFilename; + string inputFilename = ""; vector > imgpt[3]; vector imageList; - if(argc < 2) + cv::CommandLineParser parser(argc, argv, + "{help ||}{w||}{h||}{s|1|}{o|out_camera_data.yml|}" + "{zt||}{a|1|}{p||}{@input||}"); + if (parser.has("help")) { help(); - return 1; + return 0; } - - - for( i = 1; i < argc; i++ ) + boardSize.width = parser.get("w"); + boardSize.height = parser.get("h"); + squareSize = parser.get("s"); + aspectRatio = parser.get("a"); + if (parser.has("a")) + flags |= CALIB_FIX_ASPECT_RATIO; + if (parser.has("zt")) + flags |= CALIB_ZERO_TANGENT_DIST; + if (parser.has("p")) + flags |= CALIB_FIX_PRINCIPAL_POINT; + outputFilename = parser.get("o"); + inputFilename = parser.get("@input"); + if (!parser.check()) { - const char* s = argv[i]; - if( strcmp( s, "-w" ) == 0 ) - { - if( sscanf( argv[++i], "%u", &boardSize.width ) != 1 || boardSize.width <= 0 ) - return fprintf( stderr, "Invalid board width\n" ), -1; - } - else if( strcmp( s, "-h" ) == 0 ) - { - if( sscanf( argv[++i], "%u", &boardSize.height ) != 1 || boardSize.height <= 0 ) - return fprintf( stderr, "Invalid board height\n" ), -1; - } - else if( strcmp( s, "-s" ) == 0 ) - { - if( sscanf( argv[++i], "%f", &squareSize ) != 1 || squareSize <= 0 ) - return fprintf( stderr, "Invalid board square width\n" ), -1; - } - else if( strcmp( s, "-a" ) == 0 ) - { - if( sscanf( argv[++i], "%f", &aspectRatio ) != 1 || aspectRatio <= 0 ) - return printf("Invalid aspect ratio\n" ), -1; - flags |= CALIB_FIX_ASPECT_RATIO; - } - else if( strcmp( s, "-zt" ) == 0 ) - { - flags |= CALIB_ZERO_TANGENT_DIST; - } - else if( strcmp( s, "-p" ) == 0 ) - { - flags |= CALIB_FIX_PRINCIPAL_POINT; - } - else if( strcmp( s, "-o" ) == 0 ) - { - outputFilename = argv[++i]; - } - else if( s[0] != '-' ) - { - inputFilename = s; - } - else - return fprintf( stderr, "Unknown option %s", s ), -1; + help(); + parser.printErrors(); + return -1; } - - if( !inputFilename || + if (boardSize.width <= 0) + return fprintf( stderr, "Invalid board width\n" ), -1; + if (boardSize.height <= 0) + return fprintf( stderr, "Invalid board height\n" ), -1; + if (squareSize <= 0) + return fprintf( stderr, "Invalid board square width\n" ), -1; + if (aspectRatio <= 0) + return printf("Invalid aspect ratio\n" ), -1; + if( inputFilename.empty() || !readStringList(inputFilename, imageList) || imageList.size() == 0 || imageList.size() % 3 != 0 ) { diff --git a/samples/cpp/autofocus.cpp b/samples/cpp/autofocus.cpp index f237fb2ddb..cef279d6f2 100644 --- a/samples/cpp/autofocus.cpp +++ b/samples/cpp/autofocus.cpp @@ -43,11 +43,11 @@ const double epsylon = 0.0005; // compression, noice, etc. struct Args_t { - const char * deviceName; - const char * output; - unsigned int fps; - unsigned int minimumFocusStep; - unsigned int breakLimit; + string deviceName; + string output; + int fps; + int minimumFocusStep; + int breakLimit; bool measure; bool verbose; } GlobalArgs; @@ -218,12 +218,12 @@ static void showHelp(const char * pName, bool welcomeMsg) cout << "usage " << pName << ": [OPTIONS] DEVICE_NAME\n\n" "OPTIONS:\n" "\t-h\t\treturns this help message,\n" - "\t-o FILENAME\tsave output video in file (MJPEG only),\n" - "\t-f FPS\t\tframes per second in output video,\n" + "\t-o=\tsave output video in file (MJPEG only),\n" + "\t-f=FPS\t\tframes per second in output video,\n" "\t-m\t\tmeasure exposition\n" "\t\t\t(returns rates from closest focus to INTY\n" "\t\t\tfor every minimum step),\n" - "\t-d INT\t\tset minimum focus step,\n" + "\t-d=\t\tset minimum focus step,\n" "\t-v\t\tverbose mode.\n\n\n" "DEVICE_NAME\t\tis your digital camera model substring.\n\n\n" "On runtime you can use keys to control:\n"; @@ -244,60 +244,36 @@ static void showHelp(const char * pName, bool welcomeMsg) static bool parseArguments(int argc, char ** argv) { - int index; - GlobalArgs.deviceName = "Nikon"; - GlobalArgs.output = NULL; - GlobalArgs.fps = DEFAULT_OUTPUT_FPS; - GlobalArgs.minimumFocusStep = 0; + cv::CommandLineParser parser(argc, argv, "{h help ||}{o||}{f||}{m||}{d|0|}{v||}{@device|Nikon|}"); + if (parser.has("help")) + return false; GlobalArgs.breakLimit = DEFAULT_BREAK_LIMIT; - GlobalArgs.measure = false; - GlobalArgs.verbose = false; - - for (index = 1; index < argc; index++) + if (parser.has("o")) + GlobalArgs.output = parser.get("o"); + else + GlobalArgs.output = ""; + if (parser.has("f")) + GlobalArgs.fps = parser.get("f"); + else + GlobalArgs.fps = DEFAULT_OUTPUT_FPS; + GlobalArgs.measure = parser.has("m"); + GlobalArgs.verbose = parser.has("v"); + GlobalArgs.minimumFocusStep = parser.get("d"); + GlobalArgs.deviceName = parser.get("@device"); + if (!parser.check()) { - const char * arg = argv[index]; - if (strcmp(arg, "-h") == 0) - { - return false; - } - else if (strcmp(arg, "-o") == 0) - { - GlobalArgs.output = argv[++index]; - } - else if (strcmp(arg, "-f") == 0) - { - if (sscanf(argv[++index], "%u", &GlobalArgs.fps) != 1 - || GlobalArgs.fps <= 0) - { - cerr << "Invalid fps argument." << endl; - return false; - } - } - else if (strcmp(arg, "-m") == 0) - { - GlobalArgs.measure = true; - } - else if (strcmp(arg, "-v") == 0) - { - GlobalArgs.verbose = true; - } - else if (strcmp(arg, "-d") == 0) - { - if (sscanf(argv[++index], "%u", &GlobalArgs.minimumFocusStep) != 1 - || GlobalArgs.minimumFocusStep <= 0) - { - cerr << "Invalid minimum focus step argument." << endl; - return false; - } - } - else if (arg[0] != '-') - { - GlobalArgs.deviceName = arg; - } - else - { - cerr << "Unknown option " << arg << endl; - } + parser.printErrors(); + return false; + } + if (GlobalArgs.fps < 0) + { + cerr << "Invalid fps argument." << endl; + return false; + } + if (GlobalArgs.minimumFocusStep < 0) + { + cerr << "Invalid minimum focus step argument." << endl; + return false; } return true; } @@ -343,7 +319,7 @@ int main(int argc, char ** argv) cap.set(CAP_PROP_GPHOTO2_PREVIEW, true); cap.set(CAP_PROP_VIEWFINDER, true); cap >> frame; // To check PREVIEW output Size. - if (GlobalArgs.output != NULL) + if (!GlobalArgs.output.empty()) { Size S = Size((int) cap.get(CAP_PROP_FRAME_WIDTH), (int) cap.get(CAP_PROP_FRAME_HEIGHT)); int fourCC = CV_FOURCC('M', 'J', 'P', 'G'); @@ -375,7 +351,7 @@ int main(int argc, char ** argv) { break; } - if (GlobalArgs.output != NULL) + if (!GlobalArgs.output.empty()) { videoWriter << frame; } diff --git a/samples/cpp/calibration.cpp b/samples/cpp/calibration.cpp index 7c751f8f6f..415d8bb837 100644 --- a/samples/cpp/calibration.cpp +++ b/samples/cpp/calibration.cpp @@ -16,11 +16,11 @@ using namespace std; const char * usage = " \nexample command line for calibration from a live feed.\n" -" calibration -w 4 -h 5 -s 0.025 -o camera.yml -op -oe\n" +" calibration -w=4 -h=5 -s=0.025 -o=camera.yml -op -oe\n" " \n" " example command line for calibration from a list of stored images:\n" " imagelist_creator image_list.xml *.png\n" -" calibration -w 4 -h 5 -s 0.025 -o camera.yml -op -oe image_list.xml\n" +" calibration -w=4 -h=5 -s=0.025 -o=camera.yml -op -oe image_list.xml\n" " where image_list.xml is the standard OpenCV XML/YAML\n" " use imagelist_creator to create the xml or yaml list\n" " file consisting of the list of strings, e.g.:\n" @@ -50,20 +50,20 @@ static void help() { printf( "This is a camera calibration sample.\n" "Usage: calibration\n" - " -w # the number of inner corners per one of board dimension\n" - " -h # the number of inner corners per another board dimension\n" - " [-pt ] # the type of pattern: chessboard or circles' grid\n" - " [-n ] # the number of frames to use for calibration\n" + " -w= # the number of inner corners per one of board dimension\n" + " -h= # the number of inner corners per another board dimension\n" + " [-pt=] # the type of pattern: chessboard or circles' grid\n" + " [-n=] # the number of frames to use for calibration\n" " # (if not specified, it will be set to the number\n" " # of board views actually available)\n" - " [-d ] # a minimum delay in ms between subsequent attempts to capture a next view\n" + " [-d=] # a minimum delay in ms between subsequent attempts to capture a next view\n" " # (used only for video capturing)\n" - " [-s ] # square size in some user-defined units (1 by default)\n" - " [-o ] # the output filename for intrinsic [and extrinsic] parameters\n" + " [-s=] # square size in some user-defined units (1 by default)\n" + " [-o=] # the output filename for intrinsic [and extrinsic] parameters\n" " [-op] # write detected feature points\n" " [-oe] # write extrinsic parameters\n" " [-zt] # assume zero tangential distortion\n" - " [-a ] # fix aspect ratio (fx/fy)\n" + " [-a=] # fix aspect ratio (fx/fy)\n" " [-p] # fix the principal point at the center\n" " [-v] # flip the captured images around the horizontal axis\n" " [-V] # use a video file, and not an image list, uses\n" @@ -297,20 +297,20 @@ static bool runAndSave(const string& outputFilename, int main( int argc, char** argv ) { Size boardSize, imageSize; - float squareSize = 1.f, aspectRatio = 1.f; + float squareSize, aspectRatio; Mat cameraMatrix, distCoeffs; - const char* outputFilename = "out_camera_data.yml"; - const char* inputFilename = 0; + string outputFilename; + string inputFilename = ""; - int i, nframes = 10; - bool writeExtrinsics = false, writePoints = false; + int i, nframes; + bool writeExtrinsics, writePoints; bool undistortImage = false; int flags = 0; VideoCapture capture; - bool flipVertical = false; - bool showUndistorted = false; - bool videofile = false; - int delay = 1000; + bool flipVertical; + bool showUndistorted; + bool videofile; + int delay; clock_t prevTimestamp = 0; int mode = DETECTION; int cameraId = 0; @@ -318,102 +318,70 @@ int main( int argc, char** argv ) vector imageList; Pattern pattern = CHESSBOARD; - if( argc < 2 ) + cv::CommandLineParser parser(argc, argv, + "{help ||}{w||}{h||}{pt|chessboard|}{n|10|}{d|1000|}{s|1|}{o|out_camera_data.yml|}" + "{op||}{oe||}{zt||}{a|1|}{p||}{v||}{V||}{su||}" + "{@input_data|0|}"); + if (parser.has("help")) { help(); return 0; } - - for( i = 1; i < argc; i++ ) + boardSize.width = parser.get( "w" ); + boardSize.height = parser.get( "h" ); + if ( parser.has("pt") ) { - const char* s = argv[i]; - if( strcmp( s, "-w" ) == 0 ) - { - if( sscanf( argv[++i], "%u", &boardSize.width ) != 1 || boardSize.width <= 0 ) - return fprintf( stderr, "Invalid board width\n" ), -1; - } - else if( strcmp( s, "-h" ) == 0 ) - { - if( sscanf( argv[++i], "%u", &boardSize.height ) != 1 || boardSize.height <= 0 ) - return fprintf( stderr, "Invalid board height\n" ), -1; - } - else if( strcmp( s, "-pt" ) == 0 ) - { - i++; - if( !strcmp( argv[i], "circles" ) ) - pattern = CIRCLES_GRID; - else if( !strcmp( argv[i], "acircles" ) ) - pattern = ASYMMETRIC_CIRCLES_GRID; - else if( !strcmp( argv[i], "chessboard" ) ) - pattern = CHESSBOARD; - else - return fprintf( stderr, "Invalid pattern type: must be chessboard or circles\n" ), -1; - } - else if( strcmp( s, "-s" ) == 0 ) - { - if( sscanf( argv[++i], "%f", &squareSize ) != 1 || squareSize <= 0 ) - return fprintf( stderr, "Invalid board square width\n" ), -1; - } - else if( strcmp( s, "-n" ) == 0 ) - { - if( sscanf( argv[++i], "%u", &nframes ) != 1 || nframes <= 3 ) - return printf("Invalid number of images\n" ), -1; - } - else if( strcmp( s, "-a" ) == 0 ) - { - if( sscanf( argv[++i], "%f", &aspectRatio ) != 1 || aspectRatio <= 0 ) - return printf("Invalid aspect ratio\n" ), -1; - flags |= CALIB_FIX_ASPECT_RATIO; - } - else if( strcmp( s, "-d" ) == 0 ) - { - if( sscanf( argv[++i], "%u", &delay ) != 1 || delay <= 0 ) - return printf("Invalid delay\n" ), -1; - } - else if( strcmp( s, "-op" ) == 0 ) - { - writePoints = true; - } - else if( strcmp( s, "-oe" ) == 0 ) - { - writeExtrinsics = true; - } - else if( strcmp( s, "-zt" ) == 0 ) - { - flags |= CALIB_ZERO_TANGENT_DIST; - } - else if( strcmp( s, "-p" ) == 0 ) - { - flags |= CALIB_FIX_PRINCIPAL_POINT; - } - else if( strcmp( s, "-v" ) == 0 ) - { - flipVertical = true; - } - else if( strcmp( s, "-V" ) == 0 ) - { - videofile = true; - } - else if( strcmp( s, "-o" ) == 0 ) - { - outputFilename = argv[++i]; - } - else if( strcmp( s, "-su" ) == 0 ) - { - showUndistorted = true; - } - else if( s[0] != '-' ) - { - if( isdigit(s[0]) ) - sscanf(s, "%d", &cameraId); - else - inputFilename = s; - } + string val = parser.get("pt"); + if( val == "circles" ) + pattern = CIRCLES_GRID; + else if( val == "acircles" ) + pattern = ASYMMETRIC_CIRCLES_GRID; + else if( val == "chessboard" ) + pattern = CHESSBOARD; else - return fprintf( stderr, "Unknown option %s", s ), -1; + return fprintf( stderr, "Invalid pattern type: must be chessboard or circles\n" ), -1; } - - if( inputFilename ) + squareSize = parser.get("s"); + nframes = parser.get("n"); + aspectRatio = parser.get("a"); + delay = parser.get("d"); + writePoints = parser.has("op"); + writeExtrinsics = parser.has("oe"); + if (parser.has("a")) + flags |= CALIB_FIX_ASPECT_RATIO; + if ( parser.has("zt") ) + flags |= CALIB_ZERO_TANGENT_DIST; + if ( parser.has("p") ) + flags |= CALIB_FIX_PRINCIPAL_POINT; + flipVertical = parser.has("v"); + videofile = parser.has("V"); + if ( parser.has("o") ) + outputFilename = parser.get("o"); + showUndistorted = parser.has("su"); + if ( isdigit(parser.get("@input_data")[0]) ) + cameraId = parser.get("@input_data"); + else + inputFilename = parser.get("@input_data"); + if (!parser.check()) + { + help(); + parser.printErrors(); + return -1; + } + if ( squareSize <= 0 ) + return fprintf( stderr, "Invalid board square width\n" ), -1; + if ( nframes <= 3 ) + return printf("Invalid number of images\n" ), -1; + if ( aspectRatio <= 0 ) + return printf( "Invalid aspect ratio\n" ), -1; + if ( delay <= 0 ) + return printf( "Invalid delay\n" ), -1; + if ( boardSize.width <= 0 ) + return fprintf( stderr, "Invalid board width\n" ), -1; + if ( boardSize.height <= 0 ) + return fprintf( stderr, "Invalid board height\n" ), -1; + + if( !inputFilename.empty() ) { if( !videofile && readStringList(inputFilename, imageList) ) mode = CAPTURING; diff --git a/samples/cpp/camshiftdemo.cpp b/samples/cpp/camshiftdemo.cpp index 6400f1ec7d..4286e253e9 100644 --- a/samples/cpp/camshiftdemo.cpp +++ b/samples/cpp/camshiftdemo.cpp @@ -47,6 +47,15 @@ static void onMouse( int event, int x, int y, int, void* ) } } +string hot_keys = + "\n\nHot keys: \n" + "\tESC - quit the program\n" + "\tc - stop the tracking\n" + "\tb - switch to/from backprojection view\n" + "\th - show/hide object histogram\n" + "\tp - pause video\n" + "To initialize tracking, select the object with mouse\n"; + static void help() { cout << "\nThis is a demo that shows mean-shift based tracking\n" @@ -54,33 +63,28 @@ static void help() "This reads from video camera (0 by default, or the camera number the user enters\n" "Usage: \n" " ./camshiftdemo [camera number]\n"; - - cout << "\n\nHot keys: \n" - "\tESC - quit the program\n" - "\tc - stop the tracking\n" - "\tb - switch to/from backprojection view\n" - "\th - show/hide object histogram\n" - "\tp - pause video\n" - "To initialize tracking, select the object with mouse\n"; + cout << hot_keys; } const char* keys = { - "{@camera_number| 0 | camera number}" + "{help h | | show help message}{@camera_number| 0 | camera number}" }; int main( int argc, const char** argv ) { - help(); - VideoCapture cap; Rect trackWindow; int hsize = 16; float hranges[] = {0,180}; const float* phranges = hranges; CommandLineParser parser(argc, argv, keys); + if (parser.has("help")) + { + help(); + return 0; + } int camNum = parser.get(0); - cap.open(camNum); if( !cap.isOpened() ) @@ -91,7 +95,7 @@ int main( int argc, const char** argv ) parser.printMessage(); return -1; } - + cout << hot_keys; namedWindow( "Histogram", 0 ); namedWindow( "CamShift Demo", 0 ); setMouseCallback( "CamShift Demo", onMouse, 0 ); diff --git a/samples/cpp/connected_components.cpp b/samples/cpp/connected_components.cpp index d1c3411a79..6c978f1535 100644 --- a/samples/cpp/connected_components.cpp +++ b/samples/cpp/connected_components.cpp @@ -43,13 +43,17 @@ static void help() const char* keys = { - "{@image|../data/stuff.jpg|image for converting to a grayscale}" + "{help h||}{@image|../data/stuff.jpg|image for converting to a grayscale}" }; int main( int argc, const char** argv ) { - help(); CommandLineParser parser(argc, argv, keys); + if (parser.has("help")) + { + help(); + return 0; + } string inputImage = parser.get(0); img = imread(inputImage.c_str(), 0); diff --git a/samples/cpp/contours2.cpp b/samples/cpp/contours2.cpp index 0b488959ef..c5a1fa70f5 100644 --- a/samples/cpp/contours2.cpp +++ b/samples/cpp/contours2.cpp @@ -33,14 +33,15 @@ static void on_trackbar(int, void*) imshow("contours", cnt_img); } -int main( int argc, char**) +int main( int argc, char** argv) { - Mat img = Mat::zeros(w, w, CV_8UC1); - if(argc > 1) + cv::CommandLineParser parser(argc, argv, "{help h||}"); + if (parser.has("help")) { help(); - return -1; + return 0; } + Mat img = Mat::zeros(w, w, CV_8UC1); //Draw 6 faces for( int i = 0; i < 6; i++ ) { diff --git a/samples/cpp/convexhull.cpp b/samples/cpp/convexhull.cpp index 2aef70fe7d..36e5544548 100644 --- a/samples/cpp/convexhull.cpp +++ b/samples/cpp/convexhull.cpp @@ -13,13 +13,17 @@ static void help() << "./convexhull\n" << endl; } -int main( int /*argc*/, char** /*argv*/ ) +int main( int argc, char** argv ) { + CommandLineParser parser(argc, argv, "{help h||}"); + if (parser.has("help")) + { + help(); + return 0; + } Mat img(500, 500, CV_8UC3); RNG& rng = theRNG(); - help(); - for(;;) { char key; diff --git a/samples/cpp/cout_mat.cpp b/samples/cpp/cout_mat.cpp index 2261d837c9..bf1dfb2a41 100644 --- a/samples/cpp/cout_mat.cpp +++ b/samples/cpp/cout_mat.cpp @@ -25,9 +25,14 @@ static void help() } -int main(int,char**) +int main(int argc, char** argv) { - help(); + cv::CommandLineParser parser(argc, argv, "{help h||}"); + if (parser.has("help")) + { + help(); + return 0; + } Mat I = Mat::eye(4, 4, CV_64F); I.at(1,1) = CV_PI; cout << "I = \n" << I << ";" << endl << endl; diff --git a/samples/cpp/create_mask.cpp b/samples/cpp/create_mask.cpp index 42225ebc6c..7d6a61cfb4 100644 --- a/samples/cpp/create_mask.cpp +++ b/samples/cpp/create_mask.cpp @@ -123,14 +123,21 @@ void mouseHandler(int event, int x, int y, int, void*) int main(int argc, char **argv) { - - if(argc != 2) + cv::CommandLineParser parser(argc, argv, "{help h | | show help message}{@input | | input image}"); + if (parser.has("help")) + { + parser.printMessage(); + return 0; + } + string input_image = parser.get("@input"); + if (input_image.empty()) { - cout << "usage: " << argv[0] << " " << endl; - exit(1); + parser.printMessage(); + parser.printErrors(); + return 0; } - Mat src = imread(argv[1]); + Mat src = imread(input_image); minx = INT_MAX; miny = INT_MAX; maxx = INT_MIN; maxy = INT_MIN; diff --git a/samples/cpp/delaunay2.cpp b/samples/cpp/delaunay2.cpp index a00e31a988..a370feb2a7 100644 --- a/samples/cpp/delaunay2.cpp +++ b/samples/cpp/delaunay2.cpp @@ -103,9 +103,14 @@ static void paint_voronoi( Mat& img, Subdiv2D& subdiv ) } -int main( int, char** ) +int main( int argc, char** argv ) { - help(); + cv::CommandLineParser parser(argc, argv, "{help h||}"); + if (parser.has("help")) + { + help(); + return 0; + } Scalar active_facet_color(0, 0, 255), delaunay_color(255,255,255); Rect rect(0, 0, 600, 600); diff --git a/samples/cpp/demhist.cpp b/samples/cpp/demhist.cpp index 39661f0a88..d4a4c92042 100644 --- a/samples/cpp/demhist.cpp +++ b/samples/cpp/demhist.cpp @@ -64,14 +64,17 @@ static void help() const char* keys = { - "{@image|../data/baboon.jpg|input image file}" + "{help h||}{@image|../data/baboon.jpg|input image file}" }; int main( int argc, const char** argv ) { - help(); - CommandLineParser parser(argc, argv, keys); + if (parser.has("help")) + { + help(); + return 0; + } string inputImage = parser.get(0); // Load the source image. HighGUI use. diff --git a/samples/cpp/detect_blob.cpp b/samples/cpp/detect_blob.cpp index badbaaa416..879b47e69d 100644 --- a/samples/cpp/detect_blob.cpp +++ b/samples/cpp/detect_blob.cpp @@ -69,19 +69,13 @@ int main(int argc, char *argv[]) { vector fileName; Mat img(600, 800, CV_8UC1); - if (argc == 1) - { - fileName.push_back("../data/detect_blob.png"); - } - else if (argc == 2) - { - fileName.push_back(argv[1]); - } - else + cv::CommandLineParser parser(argc, argv, "{@input |../data/detect_blob.png| }{h help | | }"); + if (parser.has("h")) { help(); - return(0); + return 0; } + fileName.push_back(parser.get("@input")); img = imread(fileName[0], IMREAD_COLOR); if (img.rows*img.cols <= 0) { diff --git a/samples/cpp/detect_mser.cpp b/samples/cpp/detect_mser.cpp index 796cfa8046..a9a3fa3298 100644 --- a/samples/cpp/detect_mser.cpp +++ b/samples/cpp/detect_mser.cpp @@ -402,11 +402,18 @@ int main(int argc, char *argv[]) vector fileName; Mat imgOrig,img; Size blurSize(5,5); - if (argc==2) + cv::CommandLineParser parser(argc, argv, "{ help h | | }{ @input | | }"); + if (parser.has("help")) { - fileName.push_back(argv[1]); - imgOrig = imread(fileName[0], IMREAD_GRAYSCALE); blur(imgOrig, img, blurSize); - + help(); + return 0; + } + string input = parser.get("@input"); + if (!input.empty()) + { + fileName.push_back(input); + imgOrig = imread(fileName[0], IMREAD_GRAYSCALE); + blur(imgOrig, img, blurSize); } else { diff --git a/samples/cpp/dft.cpp b/samples/cpp/dft.cpp index 0525d9f4fa..ddb56acf09 100644 --- a/samples/cpp/dft.cpp +++ b/samples/cpp/dft.cpp @@ -19,16 +19,20 @@ static void help() const char* keys = { - "{@image|../data/lena.jpg|input image file}" + "{help h||}{@image|../data/lena.jpg|input image file}" }; int main(int argc, const char ** argv) { help(); CommandLineParser parser(argc, argv, keys); + if (parser.has("help")) + { + help(); + return 0; + } string filename = parser.get(0); - - Mat img = imread(filename.c_str(), IMREAD_GRAYSCALE); + Mat img = imread(filename, IMREAD_GRAYSCALE); if( img.empty() ) { help(); diff --git a/samples/cpp/distrans.cpp b/samples/cpp/distrans.cpp index 070df3c488..4bf4707ba6 100644 --- a/samples/cpp/distrans.cpp +++ b/samples/cpp/distrans.cpp @@ -107,15 +107,17 @@ static void help() const char* keys = { - "{@image |../data/stuff.jpg|input image file}" + "{help h||}{@image |../data/stuff.jpg|input image file}" }; int main( int argc, const char** argv ) { - help(); CommandLineParser parser(argc, argv, keys); + help(); + if (parser.has("help")) + return 0; string filename = parser.get(0); - gray = imread(filename.c_str(), 0); + gray = imread(filename, 0); if(gray.empty()) { printf("Cannot read image file: %s\n", filename.c_str()); diff --git a/samples/cpp/drawing.cpp b/samples/cpp/drawing.cpp index 43e8c112fd..236bcbcc62 100644 --- a/samples/cpp/drawing.cpp +++ b/samples/cpp/drawing.cpp @@ -16,9 +16,14 @@ static Scalar randomColor(RNG& rng) return Scalar(icolor&255, (icolor>>8)&255, (icolor>>16)&255); } -int main() +int main(int argc, char** argv) { - help(); + cv::CommandLineParser parser(argc, argv, "{help h||}"); + if (parser.has("help")) + { + help(); + return 0; + } char wndname[] = "Drawing Demo"; const int NUMBER = 100; const int DELAY = 5; diff --git a/samples/cpp/edge.cpp b/samples/cpp/edge.cpp index 4b398e7774..88abd8b257 100644 --- a/samples/cpp/edge.cpp +++ b/samples/cpp/edge.cpp @@ -33,14 +33,17 @@ static void help() const char* keys = { - "{@image |../data/fruits.jpg|input image name}" + "{help h||}{@image |../data/fruits.jpg|input image name}" }; int main( int argc, const char** argv ) { - help(); - CommandLineParser parser(argc, argv, keys); + if (parser.has("help")) + { + help(); + return 0; + } string filename = parser.get(0); image = imread(filename, 1); diff --git a/samples/cpp/facedetect.cpp b/samples/cpp/facedetect.cpp index 2be4e17e41..39717b7336 100644 --- a/samples/cpp/facedetect.cpp +++ b/samples/cpp/facedetect.cpp @@ -27,73 +27,52 @@ void detectAndDraw( Mat& img, CascadeClassifier& cascade, CascadeClassifier& nestedCascade, double scale, bool tryflip ); -string cascadeName = "../../data/haarcascades/haarcascade_frontalface_alt.xml"; -string nestedCascadeName = "../../data/haarcascades/haarcascade_eye_tree_eyeglasses.xml"; +string cascadeName; +string nestedCascadeName; int main( int argc, const char** argv ) { VideoCapture capture; Mat frame, image; - const string scaleOpt = "--scale="; - size_t scaleOptLen = scaleOpt.length(); - const string cascadeOpt = "--cascade="; - size_t cascadeOptLen = cascadeOpt.length(); - const string nestedCascadeOpt = "--nested-cascade"; - size_t nestedCascadeOptLen = nestedCascadeOpt.length(); - const string tryFlipOpt = "--try-flip"; - size_t tryFlipOptLen = tryFlipOpt.length(); string inputName; - bool tryflip = false; - - help(); - + bool tryflip; CascadeClassifier cascade, nestedCascade; - double scale = 1; - - for( int i = 1; i < argc; i++ ) + double scale; + + cv::CommandLineParser parser(argc, argv, + "{help h||}" + "{cascade|../../data/haarcascades/haarcascade_frontalface_alt.xml|}" + "{nested-cascade|../../data/haarcascades/haarcascade_eye_tree_eyeglasses.xml|}" + "{scale|1|}{try-flip||}{@filename||}" + ); + if (parser.has("help")) { - cout << "Processing " << i << " " << argv[i] << endl; - if( cascadeOpt.compare( 0, cascadeOptLen, argv[i], cascadeOptLen ) == 0 ) - { - cascadeName.assign( argv[i] + cascadeOptLen ); - cout << " from which we have cascadeName= " << cascadeName << endl; - } - else if( nestedCascadeOpt.compare( 0, nestedCascadeOptLen, argv[i], nestedCascadeOptLen ) == 0 ) - { - if( argv[i][nestedCascadeOpt.length()] == '=' ) - nestedCascadeName.assign( argv[i] + nestedCascadeOpt.length() + 1 ); - if( !nestedCascade.load( nestedCascadeName ) ) - cerr << "WARNING: Could not load classifier cascade for nested objects" << endl; - } - else if( scaleOpt.compare( 0, scaleOptLen, argv[i], scaleOptLen ) == 0 ) - { - if( !sscanf( argv[i] + scaleOpt.length(), "%lf", &scale ) || scale < 1 ) - scale = 1; - cout << " from which we read scale = " << scale << endl; - } - else if( tryFlipOpt.compare( 0, tryFlipOptLen, argv[i], tryFlipOptLen ) == 0 ) - { - tryflip = true; - cout << " will try to flip image horizontally to detect assymetric objects\n"; - } - else if( argv[i][0] == '-' ) - { - cerr << "WARNING: Unknown option %s" << argv[i] << endl; - } - else - inputName.assign( argv[i] ); + help(); + return 0; } - + cascadeName = parser.get("cascade"); + nestedCascadeName = parser.get("nested-cascade"); + scale = parser.get("scale"); + if (scale < 1) + scale = 1; + tryflip = parser.has("try-flip"); + inputName = parser.get("@filename"); + if (!parser.check()) + { + parser.printErrors(); + return 0; + } + if ( !nestedCascade.load( nestedCascadeName ) ) + cerr << "WARNING: Could not load classifier cascade for nested objects" << endl; if( !cascade.load( cascadeName ) ) { cerr << "ERROR: Could not load classifier cascade" << endl; help(); return -1; } - - if( inputName.empty() || (isdigit(inputName.c_str()[0]) && inputName.c_str()[1] == '\0') ) + if( inputName.empty() || (isdigit(inputName[0]) && inputName.size() == 1) ) { - int c = inputName.empty() ? 0 : inputName.c_str()[0] - '0' ; + int c = inputName.empty() ? 0 : inputName[0] - '0'; if(!capture.open(c)) cout << "Capture from camera #" << c << " didn't work" << endl; } diff --git a/samples/cpp/facial_features.cpp b/samples/cpp/facial_features.cpp index 9cfbd85c7f..f46fa3fb56 100644 --- a/samples/cpp/facial_features.cpp +++ b/samples/cpp/facial_features.cpp @@ -18,11 +18,6 @@ using namespace std; using namespace cv; -// Functions to parse command-line arguments -static string getCommandOption(const vector&, const string&); -static void setCommandOptions(vector&, int, char**); -static bool doesCmdOptionExist(const vector& , const string&); - // Functions for facial feature detection static void help(); static void detectFaces(Mat&, vector >&, string); @@ -36,22 +31,23 @@ string face_cascade_path, eye_cascade_path, nose_cascade_path, mouth_cascade_pat int main(int argc, char** argv) { - if(argc < 3) + cv::CommandLineParser parser(argc, argv, + "{eyes||}{nose||}{mouth||}{help h||}"); + if (parser.has("help")) { help(); + return 0; + } + input_image_path = parser.get(0); + face_cascade_path = parser.get(1); + eye_cascade_path = parser.has("eyes") ? parser.get("eyes") : ""; + nose_cascade_path = parser.has("nose") ? parser.get("nose") : ""; + mouth_cascade_path = parser.has("mouth") ? parser.get("mouth") : ""; + if (input_image_path.empty() || face_cascade_path.empty()) + { + cout << "IMAGE or FACE_CASCADE are not specified"; return 1; } - - // Extract command-line options - vector args; - setCommandOptions(args, argc, argv); - - input_image_path = argv[1]; - face_cascade_path = argv[2]; - eye_cascade_path = (doesCmdOptionExist(args, "-eyes")) ? getCommandOption(args, "-eyes") : ""; - nose_cascade_path = (doesCmdOptionExist(args, "-nose")) ? getCommandOption(args, "-nose") : ""; - mouth_cascade_path = (doesCmdOptionExist(args, "-mouth")) ? getCommandOption(args, "-mouth") : ""; - // Load image and cascade classifier files Mat image; image = imread(input_image_path); @@ -67,30 +63,6 @@ int main(int argc, char** argv) return 0; } -void setCommandOptions(vector& args, int argc, char** argv) -{ - for(int i = 1; i < argc; ++i) - { - args.push_back(argv[i]); - } - return; -} - -string getCommandOption(const vector& args, const string& opt) -{ - string answer; - vector::const_iterator it = find(args.begin(), args.end(), opt); - if(it != args.end() && (++it != args.end())) - answer = *it; - return answer; -} - -bool doesCmdOptionExist(const vector& args, const string& opt) -{ - vector::const_iterator it = find(args.begin(), args.end(), opt); - return (it != args.end()); -} - static void help() { cout << "\nThis file demonstrates facial feature points detection using Haarcascade classifiers.\n" @@ -103,15 +75,15 @@ static void help() "FACE_CASCSDE\n\t Path to a haarcascade classifier for face detection.\n" "OPTIONS: \nThere are 3 options available which are described in detail. There must be a " "space between the option and it's argument (All three options accept arguments).\n" - "\t-eyes : Specify the haarcascade classifier for eye detection.\n" - "\t-nose : Specify the haarcascade classifier for nose detection.\n" - "\t-mouth : Specify the haarcascade classifier for mouth detection.\n"; + "\t-eyes= : Specify the haarcascade classifier for eye detection.\n" + "\t-nose= : Specify the haarcascade classifier for nose detection.\n" + "\t-mouth= : Specify the haarcascade classifier for mouth detection.\n"; cout << "EXAMPLE:\n" - "(1) ./cpp-example-facial_features image.jpg face.xml -eyes eyes.xml -mouth mouth.xml\n" + "(1) ./cpp-example-facial_features image.jpg face.xml -eyes=eyes.xml -mouth=mouth.xml\n" "\tThis will detect the face, eyes and mouth in image.jpg.\n" - "(2) ./cpp-example-facial_features image.jpg face.xml -nose nose.xml\n" + "(2) ./cpp-example-facial_features image.jpg face.xml -nose=nose.xml\n" "\tThis will detect the face and nose in image.jpg.\n" "(3) ./cpp-example-facial_features image.jpg face.xml\n" "\tThis will detect only the face in image.jpg.\n"; diff --git a/samples/cpp/fback.cpp b/samples/cpp/fback.cpp index af0f2ca09b..5fbec6913c 100644 --- a/samples/cpp/fback.cpp +++ b/samples/cpp/fback.cpp @@ -30,8 +30,14 @@ static void drawOptFlowMap(const Mat& flow, Mat& cflowmap, int step, } } -int main(int, char**) +int main(int argc, char** argv) { + cv::CommandLineParser parser(argc, argv, "{help h||}"); + if (parser.has("help")) + { + help(); + return 0; + } VideoCapture cap(0); help(); if( !cap.isOpened() ) diff --git a/samples/cpp/ffilldemo.cpp b/samples/cpp/ffilldemo.cpp index e099587a11..93bdd672bd 100644 --- a/samples/cpp/ffilldemo.cpp +++ b/samples/cpp/ffilldemo.cpp @@ -73,12 +73,21 @@ static void onMouse( int event, int x, int y, int, void* ) int main( int argc, char** argv ) { - char* filename = argc >= 2 ? argv[1] : (char*)"../data/fruits.jpg"; + cv::CommandLineParser parser (argc, argv, + "{help h | | show help message}{@image|../data/fruits.jpg| input image}" + ); + if (parser.has("help")) + { + parser.printMessage(); + return 0; + } + string filename = parser.get("@image"); image0 = imread(filename, 1); if( image0.empty() ) { - cout << "Image empty. Usage: ffilldemo \n"; + cout << "Image empty\n"; + parser.printMessage(); return 0; } help(); diff --git a/samples/cpp/filestorage.cpp b/samples/cpp/filestorage.cpp index 41043d11cc..60ea51acab 100644 --- a/samples/cpp/filestorage.cpp +++ b/samples/cpp/filestorage.cpp @@ -70,14 +70,21 @@ static ostream& operator<<(ostream& out, const MyData& m){ } int main(int ac, char** av) { - if (ac != 2) + cv::CommandLineParser parser(ac, av, + "{@input||}{help h ||}" + ); + if (parser.has("help")) + { + help(av); + return 0; + } + string filename = parser.get("@input"); + if (filename.empty()) { help(av); return 1; } - string filename = av[1]; - //write { FileStorage fs(filename, FileStorage::WRITE); diff --git a/samples/cpp/fitellipse.cpp b/samples/cpp/fitellipse.cpp index bd6b77d8a6..b83f617c1d 100644 --- a/samples/cpp/fitellipse.cpp +++ b/samples/cpp/fitellipse.cpp @@ -21,14 +21,14 @@ using namespace cv; using namespace std; -// static void help() -// { -// cout << -// "\nThis program is demonstration for ellipse fitting. The program finds\n" -// "contours and approximate it by ellipses.\n" -// "Call:\n" -// "./fitellipse [image_name -- Default ../data/stuff.jpg]\n" << endl; -// } +static void help() +{ + cout << + "\nThis program is demonstration for ellipse fitting. The program finds\n" + "contours and approximate it by ellipses.\n" + "Call:\n" + "./fitellipse [image_name -- Default ../data/stuff.jpg]\n" << endl; +} int sliderPos = 70; @@ -38,11 +38,19 @@ void processImage(int, void*); int main( int argc, char** argv ) { - const char* filename = argc == 2 ? argv[1] : (char*)"../data/stuff.jpg"; + cv::CommandLineParser parser(argc, argv, + "{help h||}{@image|../data/stuff.jpg|}" + ); + if (parser.has("help")) + { + help(); + return 0; + } + string filename = parser.get("@image"); image = imread(filename, 0); if( image.empty() ) { - cout << "Couldn't open image " << filename << "\nUsage: fitellipse \n"; + cout << "Couldn't open image " << filename << "\n"; return 0; } diff --git a/samples/cpp/grabcut.cpp b/samples/cpp/grabcut.cpp index 7ab28f66b0..b6b406000b 100644 --- a/samples/cpp/grabcut.cpp +++ b/samples/cpp/grabcut.cpp @@ -276,15 +276,16 @@ static void on_mouse( int event, int x, int y, int flags, void* param ) int main( int argc, char** argv ) { - if( argc!=2 ) + cv::CommandLineParser parser(argc, argv, "{help h||}{@input||}"); + if (parser.has("help")) { help(); - return 1; + return 0; } - string filename = argv[1]; + string filename = parser.get("@input"); if( filename.empty() ) { - cout << "\nDurn, couldn't read in " << argv[1] << endl; + cout << "\nDurn, empty filename" << endl; return 1; } Mat image = imread( filename, 1 ); diff --git a/samples/cpp/houghcircles.cpp b/samples/cpp/houghcircles.cpp index 34a2e6b7e8..bdafffec30 100644 --- a/samples/cpp/houghcircles.cpp +++ b/samples/cpp/houghcircles.cpp @@ -16,8 +16,21 @@ static void help() int main(int argc, char** argv) { - const char* filename = argc >= 2 ? argv[1] : "../data/board.jpg"; - + cv::CommandLineParser parser(argc, argv, + "{help h ||}{@image|../data/board.jpg|}" + ); + if (parser.has("help")) + { + help(); + return 0; + } + string filename = parser.get("@image"); + if (filename.empty()) + { + help(); + cout << "no image_name provided" << endl; + return -1; + } Mat img = imread(filename, 0); if(img.empty()) { diff --git a/samples/cpp/houghlines.cpp b/samples/cpp/houghlines.cpp index ec825ab6b4..ddeb3bd751 100644 --- a/samples/cpp/houghlines.cpp +++ b/samples/cpp/houghlines.cpp @@ -16,8 +16,21 @@ static void help() int main(int argc, char** argv) { - const char* filename = argc >= 2 ? argv[1] : "../data/pic1.png"; - + cv::CommandLineParser parser(argc, argv, + "{help h||}{@image|../data/pic1.png|}" + ); + if (parser.has("help")) + { + help(); + return 0; + } + string filename = parser.get("@image"); + if (filename.empty()) + { + help(); + cout << "no image_name provided" << endl; + return -1; + } Mat src = imread(filename, 0); if(src.empty()) { diff --git a/samples/cpp/image.cpp b/samples/cpp/image.cpp index a0e6718129..b5925c69af 100644 --- a/samples/cpp/image.cpp +++ b/samples/cpp/image.cpp @@ -27,14 +27,19 @@ static void help() int main( int argc, char** argv ) { - help(); - const char* imagename = argc > 1 ? argv[1] : "../data/lena.jpg"; + cv::CommandLineParser parser(argc, argv, "{help h | |}{@image|../data/lena.jpg|}"); + if (parser.has("help")) + { + help(); + return 0; + } + string imagename = parser.get("@image"); #if DEMO_MIXED_API_USE //! [iplimage] - Ptr iplimg(cvLoadImage(imagename)); // Ptr is safe ref-counting pointer class + Ptr iplimg(cvLoadImage(imagename.c_str())); // Ptr is safe ref-counting pointer class if(!iplimg) { - fprintf(stderr, "Can not load image %s\n", imagename); + fprintf(stderr, "Can not load image %s\n", imagename.c_str()); return -1; } Mat img = cv::cvarrToMat(iplimg); // cv::Mat replaces the CvMat and IplImage, but it's easy to convert @@ -45,7 +50,7 @@ int main( int argc, char** argv ) Mat img = imread(imagename); // the newer cvLoadImage alternative, MATLAB-style function if(img.empty()) { - fprintf(stderr, "Can not load image %s\n", imagename); + fprintf(stderr, "Can not load image %s\n", imagename.c_str()); return -1; } #endif diff --git a/samples/cpp/image_alignment.cpp b/samples/cpp/image_alignment.cpp index 08814b84fd..c62a1608da 100644 --- a/samples/cpp/image_alignment.cpp +++ b/samples/cpp/image_alignment.cpp @@ -53,6 +53,7 @@ const std::string keys = "{m motionType | affine | type of motion (translation, euclidean, affine, homography) }" "{v verbose | 0 | display initial and final images }" "{w warpedImfile | warpedECC.png | warped input image }" + "{h help | | print help message }" ; @@ -176,12 +177,17 @@ int main (const int argc, const char * argv[]) CommandLineParser parser(argc, argv, keys); parser.about("ECC demo"); - if (argc<2) { + if (argc < 2) { + parser.printMessage(); + help(); + return 1; + } + if (parser.has("help")) + { parser.printMessage(); help(); return 1; } - string imgFile = parser.get(0); string tempImgFile = parser.get(1); string inWarpFile = parser.get(2); @@ -192,7 +198,11 @@ int main (const int argc, const char * argv[]) int verbose = parser.get("v"); string finalWarp = parser.get("o"); string warpedImFile = parser.get("w"); - + if (!parser.check()) + { + parser.printErrors(); + return -1; + } if (!(warpType == "translation" || warpType == "euclidean" || warpType == "affine" || warpType == "homography")) { diff --git a/samples/cpp/image_sequence.cpp b/samples/cpp/image_sequence.cpp index b87b3043e2..14b63e39c4 100644 --- a/samples/cpp/image_sequence.cpp +++ b/samples/cpp/image_sequence.cpp @@ -18,13 +18,20 @@ static void help(char** argv) int main(int argc, char** argv) { - if(argc != 2) + cv::CommandLineParser parser(argc, argv, "{help h||}{@image||}"); + if (parser.has("help")) + { + help(argv); + return 0; + } + string first_file = parser.get("@image"); + + if(first_file.empty()) { help(argv); return 1; } - string first_file = argv[1]; VideoCapture sequence(first_file); if (!sequence.isOpened()) diff --git a/samples/cpp/imagelist_creator.cpp b/samples/cpp/imagelist_creator.cpp index f2abb11c9a..bdb023187b 100644 --- a/samples/cpp/imagelist_creator.cpp +++ b/samples/cpp/imagelist_creator.cpp @@ -23,13 +23,19 @@ static void help(char** av) int main(int ac, char** av) { - if (ac < 3) + cv::CommandLineParser parser(ac, av, "{help h||}{@output||}"); + if (parser.has("help")) { help(av); - return 1; + return 0; } + string outputname = parser.get("@output"); - string outputname = av[1]; + if (outputname.empty()) + { + help(av); + return 1; + } Mat m = imread(outputname); //check if the output is an image - prevent overwrites! if(!m.empty()){ diff --git a/samples/cpp/inpaint.cpp b/samples/cpp/inpaint.cpp index 55bd91b73b..62d7521932 100644 --- a/samples/cpp/inpaint.cpp +++ b/samples/cpp/inpaint.cpp @@ -47,7 +47,13 @@ static void onMouse( int event, int x, int y, int flags, void* ) int main( int argc, char** argv ) { - char* filename = argc >= 2 ? argv[1] : (char*)"../data/fruits.jpg"; + cv::CommandLineParser parser(argc, argv, "{help h||}{@image|../data/fruits.jpg|}"); + if (parser.has("help")) + { + help(); + return 0; + } + string filename = parser.get("@image"); Mat img0 = imread(filename, -1); if(img0.empty()) { @@ -55,8 +61,6 @@ int main( int argc, char** argv ) return 0; } - help(); - namedWindow( "image", 1 ); img = img0.clone(); diff --git a/samples/cpp/intelperc_capture.cpp b/samples/cpp/intelperc_capture.cpp index 5726ccdf4f..daae4420fb 100644 --- a/samples/cpp/intelperc_capture.cpp +++ b/samples/cpp/intelperc_capture.cpp @@ -9,14 +9,14 @@ using namespace cv; using namespace std; -static bool g_printStreamSetting = false; -static int g_imageStreamProfileIdx = -1; -static int g_depthStreamProfileIdx = -1; -static bool g_irStreamShow = false; -static double g_imageBrightness = -DBL_MAX; -static double g_imageContrast = -DBL_MAX; -static bool g_printTiming = false; -static bool g_showClosedPoint = false; +static bool g_printStreamSetting; +static int g_imageStreamProfileIdx; +static int g_depthStreamProfileIdx; +static bool g_irStreamShow; +static double g_imageBrightness; +static double g_imageContrast; +static bool g_printTiming; +static bool g_showClosedPoint; static int g_closedDepthPoint[2]; @@ -31,13 +31,13 @@ static void printUsage(const char *arg0) filename++; cout << "This program demonstrates usage of camera supported\nby Intel Perceptual computing SDK." << endl << endl; - cout << "usage: " << filename << "[-ps] [-isp IDX] [-dsp IDX]\n [-ir] [-imb VAL] [-imc VAL]" << endl << endl; + cout << "usage: " << filename << "[-ps] [-isp=IDX] [-dsp=IDX]\n [-ir] [-imb=VAL] [-imc=VAL]" << endl << endl; cout << " -ps, print streams setting and profiles" << endl; - cout << " -isp IDX, set profile index of the image stream" << endl; - cout << " -dsp IDX, set profile index of the depth stream" << endl; + cout << " -isp=IDX, set profile index of the image stream" << endl; + cout << " -dsp=IDX, set profile index of the depth stream" << endl; cout << " -ir, show data from IR stream" << endl; - cout << " -imb VAL, set brighness value for a image stream" << endl; - cout << " -imc VAL, set contrast value for a image stream" << endl; + cout << " -imb=VAL, set brighness value for a image stream" << endl; + cout << " -imc=VAL, set contrast value for a image stream" << endl; cout << " -pts, print frame index and frame time" << endl; cout << " --show-closed, print frame index and frame time" << endl; cout << endl; @@ -45,62 +45,40 @@ static void printUsage(const char *arg0) static void parseCMDLine(int argc, char* argv[]) { - if( argc == 1 ) + cv::CommandLineParser parser(argc, argv, + "{ h help | | }" + "{ ps print-streams | | }" + "{ isp image-stream-prof | -1 | }" + "{ dsp depth-stream-prof | -1 | }" + "{ir||}{imb||}{imc||}{pts||}{show-closed||}"); + if (parser.has("h")) { printUsage(argv[0]); + exit(0); } + g_printStreamSetting = parser.has("ps"); + g_imageStreamProfileIdx = parser.get("isp"); + g_depthStreamProfileIdx = parser.get("dsp"); + g_irStreamShow = parser.has("ir"); + if (parser.has("imb")) + g_imageBrightness = parser.get("imb"); else + g_imageBrightness = -DBL_MAX; + if (parser.has("imc")) + g_imageContrast = parser.get("imc"); + else + g_imageContrast = -DBL_MAX; + g_printTiming = parser.has("pts"); + g_showClosedPoint = parser.has("show-closed"); + if (!parser.check()) { - for( int i = 1; i < argc; i++ ) - { - if ((0 == strcmp(argv[i], "--help")) || (0 == strcmp( argv[i], "-h"))) - { - printUsage(argv[0]); - exit(0); - } - else if ((0 == strcmp( argv[i], "--print-streams")) || (0 == strcmp( argv[i], "-ps"))) - { - g_printStreamSetting = true; - } - else if ((0 == strcmp( argv[i], "--image-stream-prof")) || (0 == strcmp( argv[i], "-isp"))) - { - g_imageStreamProfileIdx = atoi(argv[++i]); - } - else if ((0 == strcmp( argv[i], "--depth-stream-prof")) || (0 == strcmp( argv[i], "-dsp"))) - { - g_depthStreamProfileIdx = atoi(argv[++i]); - } - else if (0 == strcmp( argv[i], "-ir")) - { - g_irStreamShow = true; - } - else if (0 == strcmp( argv[i], "-imb")) - { - g_imageBrightness = atof(argv[++i]); - } - else if (0 == strcmp( argv[i], "-imc")) - { - g_imageContrast = atof(argv[++i]); - } - else if (0 == strcmp(argv[i], "-pts")) - { - g_printTiming = true; - } - else if (0 == strcmp(argv[i], "--show-closed")) - { - g_showClosedPoint = true; - } - else - { - cout << "Unsupported command line argument: " << argv[i] << "." << endl; - exit(-1); - } - } - if (g_showClosedPoint && (-1 == g_depthStreamProfileIdx)) - { - cerr << "For --show-closed depth profile has be selected" << endl; - exit(-1); - } + parser.printErrors(); + exit(-1); + } + if (g_showClosedPoint && (-1 == g_depthStreamProfileIdx)) + { + cerr << "For --show-closed depth profile has be selected" << endl; + exit(-1); } } diff --git a/samples/cpp/laplace.cpp b/samples/cpp/laplace.cpp index bac432ca50..b33b49cbdb 100644 --- a/samples/cpp/laplace.cpp +++ b/samples/cpp/laplace.cpp @@ -15,7 +15,7 @@ static void help() "\nThis program demonstrates Laplace point/edge detection using OpenCV function Laplacian()\n" "It captures from the camera of your choice: 0, 1, ... default 0\n" "Call:\n" - "./laplace [camera #, default 0]\n" << endl; + "./laplace -c= -p=\n" << endl; } enum {GAUSSIAN, BLUR, MEDIAN}; @@ -26,25 +26,31 @@ int smoothType = GAUSSIAN; int main( int argc, char** argv ) { VideoCapture cap; - help(); - - if( argc == 1 || (argc == 2 && strlen(argv[1]) == 1 && isdigit(argv[1][0]))) - cap.open(argc == 2 ? argv[1][0] - '0' : 0); - else if( argc >= 2 ) + cv::CommandLineParser parser(argc, argv, "{help h | | }{ c | 0 | }{ p | | }"); + if ( parser.has("help") ) + { + help(); + return 0; + } + if( parser.get("c").size() == 1 && isdigit(parser.get("c")[0]) ) + cap.open(parser.get("c")); + else + cap.open(parser.get("c")); + if( cap.isOpened() ) + cout << "Video " << parser.get("c") << + ": width=" << cap.get(CAP_PROP_FRAME_WIDTH) << + ", height=" << cap.get(CAP_PROP_FRAME_HEIGHT) << + ", nframes=" << cap.get(CAP_PROP_FRAME_COUNT) << endl; + if( parser.has("p") ) { - cap.open(argv[1]); - if( cap.isOpened() ) - cout << "Video " << argv[1] << - ": width=" << cap.get(CAP_PROP_FRAME_WIDTH) << - ", height=" << cap.get(CAP_PROP_FRAME_HEIGHT) << - ", nframes=" << cap.get(CAP_PROP_FRAME_COUNT) << endl; - if( argc > 2 && isdigit(argv[2][0]) ) + int pos = parser.get("p"); + if (!parser.check()) { - int pos; - sscanf(argv[2], "%d", &pos); - cout << "seeking to frame #" << pos << endl; - cap.set(CAP_PROP_POS_FRAMES, pos); + parser.printErrors(); + return -1; } + cout << "seeking to frame #" << pos << endl; + cap.set(CAP_PROP_POS_FRAMES, pos); } if( !cap.isOpened() ) diff --git a/samples/cpp/letter_recog.cpp b/samples/cpp/letter_recog.cpp index 174e7f9839..3d7e34ab7a 100644 --- a/samples/cpp/letter_recog.cpp +++ b/samples/cpp/letter_recog.cpp @@ -28,9 +28,9 @@ static void help() "and the remaining 4000 (10000 for boosting) - to test the classifier.\n" "======================================================\n"); printf("\nThis is letter recognition sample.\n" - "The usage: letter_recog [-data ] \\\n" - " [-save ] \\\n" - " [-load ] \\\n" + "The usage: letter_recog [-data=] \\\n" + " [-save=] \\\n" + " [-load=] \\\n" " [-boost|-mlp|-knearest|-nbayes|-svm] # to use boost/mlp/knearest/SVM classifier instead of default Random Trees\n" ); } @@ -517,53 +517,32 @@ int main( int argc, char *argv[] ) { string filename_to_save = ""; string filename_to_load = ""; - string data_filename = "../data/letter-recognition.data"; + string data_filename; int method = 0; - int i; - for( i = 1; i < argc; i++ ) + cv::CommandLineParser parser(argc, argv, "{data|../data/letter-recognition.data|}{save||}{load||}{boost||}" + "{mlp||}{knn knearest||}{nbayes||}{svm||}{help h||}"); + data_filename = parser.get("data"); + if (parser.has("save")) + filename_to_save = parser.get("save"); + if (parser.has("load")) + filename_to_load = parser.get("load"); + if (parser.has("boost")) + method = 1; + else if (parser.has("mlp")) + method = 2; + else if (parser.has("knearest")) + method = 3; + else if (parser.has("nbayes")) + method = 4; + else if (parser.has("svm")) + method = 5; + if (parser.has("help")) { - if( strcmp(argv[i],"-data") == 0 ) // flag "-data letter_recognition.xml" - { - i++; - data_filename = argv[i]; - } - else if( strcmp(argv[i],"-save") == 0 ) // flag "-save filename.xml" - { - i++; - filename_to_save = argv[i]; - } - else if( strcmp(argv[i],"-load") == 0) // flag "-load filename.xml" - { - i++; - filename_to_load = argv[i]; - } - else if( strcmp(argv[i],"-boost") == 0) - { - method = 1; - } - else if( strcmp(argv[i],"-mlp") == 0 ) - { - method = 2; - } - else if( strcmp(argv[i], "-knearest") == 0 || strcmp(argv[i], "-knn") == 0 ) - { - method = 3; - } - else if( strcmp(argv[i], "-nbayes") == 0) - { - method = 4; - } - else if( strcmp(argv[i], "-svm") == 0) - { - method = 5; - } - else - break; + help(); + return 0; } - - if( i < argc || - (method == 0 ? + if( (method == 0 ? build_rtrees_classifier( data_filename, filename_to_save, filename_to_load ) : method == 1 ? build_boost_classifier( data_filename, filename_to_save, filename_to_load ) : diff --git a/samples/cpp/lkdemo.cpp b/samples/cpp/lkdemo.cpp index 2f576c3ba8..3881aa8650 100644 --- a/samples/cpp/lkdemo.cpp +++ b/samples/cpp/lkdemo.cpp @@ -37,8 +37,6 @@ static void onMouse( int event, int x, int y, int /*flags*/, void* /*param*/ ) int main( int argc, char** argv ) { - help(); - VideoCapture cap; TermCriteria termcrit(TermCriteria::COUNT|TermCriteria::EPS,20,0.03); Size subPixWinSize(10,10), winSize(31,31); @@ -47,10 +45,19 @@ int main( int argc, char** argv ) bool needToInit = false; bool nightMode = false; - if( argc == 1 || (argc == 2 && strlen(argv[1]) == 1 && isdigit(argv[1][0]))) - cap.open(argc == 2 ? argv[1][0] - '0' : 0); - else if( argc == 2 ) - cap.open(argv[1]); + cv::CommandLineParser parser(argc, argv, "{@input||}{help h||}"); + string input = parser.get("@input"); + if (parser.has("help")) + { + help(); + return 0; + } + if( input.empty() ) + cap.open(0); + else if( input.size() == 1 && isdigit(input[0]) ) + cap.open(input[0] - '0'); + else + cap.open(input); if( !cap.isOpened() ) { diff --git a/samples/cpp/lsd_lines.cpp b/samples/cpp/lsd_lines.cpp index 34f6b906b4..4c8c7e0a41 100644 --- a/samples/cpp/lsd_lines.cpp +++ b/samples/cpp/lsd_lines.cpp @@ -13,15 +13,13 @@ using namespace cv; int main(int argc, char** argv) { std::string in; - if (argc != 2) + cv::CommandLineParser parser(argc, argv, "{@input|../data/building.jpg|input image}{help h||show help message}"); + if (parser.has("help")) { - std::cout << "Usage: lsd_lines [input image]. Now loading ../data/building.jpg" << std::endl; - in = "../data/building.jpg"; - } - else - { - in = argv[1]; + parser.printMessage(); + return 0; } + in = parser.get("@input"); Mat image = imread(in, IMREAD_GRAYSCALE); diff --git a/samples/cpp/mask_tmpl.cpp b/samples/cpp/mask_tmpl.cpp index 2b6bb77bf1..6617783266 100644 --- a/samples/cpp/mask_tmpl.cpp +++ b/samples/cpp/mask_tmpl.cpp @@ -13,16 +13,25 @@ static void help() { cout << "\nThis program demonstrates template match with mask.\n" "Usage:\n" - "./mask_tmpl , Default is ../data/lena_tmpl.jpg\n" + "./mask_tmpl -i= -t= -m=, Default is ../data/lena_tmpl.jpg\n" << endl; } int main( int argc, const char** argv ) { - const char* filename = argc == 4 ? argv[1] : "../data/lena_tmpl.jpg"; - const char* tmplname = argc == 4 ? argv[2] : "../data/tmpl.png"; - const char* maskname = argc == 4 ? argv[3] : "../data/mask.png"; - + cv::CommandLineParser parser(argc, argv, + "{help h||}" + "{ i | ../data/lena_tmpl.jpg | }" + "{ t | ../data/tmpl.png | }" + "{ m | ../data/mask.png | }"); + if (parser.has("help")) + { + help(); + return 0; + } + string filename = parser.get("i"); + string tmplname = parser.get("t"); + string maskname = parser.get("m"); Mat img = imread(filename); Mat tmpl = imread(tmplname); Mat mask = imread(maskname); diff --git a/samples/cpp/matchmethod_orb_akaze_brisk.cpp b/samples/cpp/matchmethod_orb_akaze_brisk.cpp index 4e3884d690..379b53ae1d 100644 --- a/samples/cpp/matchmethod_orb_akaze_brisk.cpp +++ b/samples/cpp/matchmethod_orb_akaze_brisk.cpp @@ -9,7 +9,7 @@ static void help() { cout << "\n This program demonstrates how to detect compute and match ORB BRISK and AKAZE descriptors \n" "Usage: \n" - " ./matchmethod_orb_akaze_brisk \n" + " ./matchmethod_orb_akaze_brisk --image1= --image2=\n" "Press a key when image window is active to change algorithm or descriptor"; } @@ -20,7 +20,6 @@ int main(int argc, char *argv[]) vector typeDesc; vector typeAlgoMatch; vector fileName; - help(); // This descriptor are going to be detect and compute typeDesc.push_back("AKAZE-DESCRIPTOR_KAZE_UPRIGHT"); // see http://docs.opencv.org/trunk/d8/d30/classcv_1_1AKAZE.html typeDesc.push_back("AKAZE"); // see http://docs.opencv.org/trunk/d8/d30/classcv_1_1AKAZE.html @@ -31,21 +30,17 @@ int main(int argc, char *argv[]) typeAlgoMatch.push_back("BruteForce-L1"); typeAlgoMatch.push_back("BruteForce-Hamming"); typeAlgoMatch.push_back("BruteForce-Hamming(2)"); - if (argc==1) - { - fileName.push_back("../data/basketball1.png"); - fileName.push_back("../data/basketball2.png"); - } - else if (argc==3) - { - fileName.push_back(argv[1]); - fileName.push_back(argv[2]); - } - else + cv::CommandLineParser parser(argc, argv, + "{ @image1 | ../data/basketball1.png | }" + "{ @image2 | ../data/basketball2.png | }" + "{help h ||}"); + if (parser.has("help")) { help(); - return(0); + return 0; } + fileName.push_back(parser.get(0)); + fileName.push_back(parser.get(1)); Mat img1 = imread(fileName[0], IMREAD_GRAYSCALE); Mat img2 = imread(fileName[1], IMREAD_GRAYSCALE); if (img1.rows*img1.cols <= 0) diff --git a/samples/cpp/morphology2.cpp b/samples/cpp/morphology2.cpp index 27eb52aee7..04e916c64a 100644 --- a/samples/cpp/morphology2.cpp +++ b/samples/cpp/morphology2.cpp @@ -3,6 +3,7 @@ #include "opencv2/highgui/highgui.hpp" #include #include +#include using namespace cv; @@ -58,11 +59,18 @@ static void ErodeDilate(int, void*) int main( int argc, char** argv ) { - char* filename = argc == 2 ? argv[1] : (char*)"../data/baboon.jpg"; + cv::CommandLineParser parser(argc, argv, "{help h||}{ @image | ../data/baboon.jpg | }"); + if (parser.has("help")) + { + help(); + return 0; + } + std::string filename = parser.get("@image"); if( (src = imread(filename,1)).empty() ) + { + help(); return -1; - - help(); + } //create windows for output images namedWindow("Open/Close",1); diff --git a/samples/cpp/npr_demo.cpp b/samples/cpp/npr_demo.cpp index e4fade0d8d..64a3e05389 100644 --- a/samples/cpp/npr_demo.cpp +++ b/samples/cpp/npr_demo.cpp @@ -28,15 +28,21 @@ using namespace cv; int main(int argc, char* argv[]) { - if(argc < 2) + cv::CommandLineParser parser(argc, argv, "{help h||show help message}{@image||input image}"); + if (parser.has("help")) { - cout << "usage: " << argv[0] << " " << endl; + parser.printMessage(); + exit(0); + } + if (parser.get("@image").empty()) + { + parser.printMessage(); exit(0); } - int num,type; + Mat I = imread(parser.get("@image")); - Mat I = imread(argv[1]); + int num,type; if(I.empty()) { diff --git a/samples/cpp/openni_capture.cpp b/samples/cpp/openni_capture.cpp index 09f1d21e09..70d4a7c610 100644 --- a/samples/cpp/openni_capture.cpp +++ b/samples/cpp/openni_capture.cpp @@ -87,90 +87,49 @@ static float getMaxDisparity( VideoCapture& capture ) static void printCommandLineParams() { - cout << "-cd Colorized disparity? (0 or 1; 1 by default) Ignored if disparity map is not selected to show." << endl; - cout << "-fmd Fixed max disparity? (0 or 1; 0 by default) Ignored if disparity map is not colorized (-cd 0)." << endl; - cout << "-mode image mode: resolution and fps, supported three values: 0 - CAP_OPENNI_VGA_30HZ, 1 - CAP_OPENNI_SXGA_15HZ," << endl; + cout << "-cd= Colorized disparity? (0 or 1; 1 by default) Ignored if disparity map is not selected to show." << endl; + cout << "-fmd= Fixed max disparity? (0 or 1; 0 by default) Ignored if disparity map is not colorized (-cd 0)." << endl; + cout << "-mode= image mode: resolution and fps, supported three values: 0 - CAP_OPENNI_VGA_30HZ, 1 - CAP_OPENNI_SXGA_15HZ," << endl; cout << " 2 - CAP_OPENNI_SXGA_30HZ (0 by default). Ignored if rgb image or gray image are not selected to show." << endl; - cout << "-m Mask to set which output images are need. It is a string of size 5. Each element of this is '0' or '1' and" << endl; + cout << "-m= Mask to set which output images are need. It is a string of size 5. Each element of this is '0' or '1' and" << endl; cout << " determine: is depth map, disparity map, valid pixels mask, rgb image, gray image need or not (correspondently)?" << endl ; - cout << " By default -m 01010 i.e. disparity map and rgb image will be shown." << endl ; - cout << "-r Filename of .oni video file. The data will grabbed from it." << endl ; + cout << " By default -m=01010 i.e. disparity map and rgb image will be shown." << endl ; + cout << "-r= Filename of .oni video file. The data will grabbed from it." << endl ; } static void parseCommandLine( int argc, char* argv[], bool& isColorizeDisp, bool& isFixedMaxDisp, int& imageMode, bool retrievedImageFlags[], string& filename, bool& isFileReading ) { - // set defaut values - isColorizeDisp = true; - isFixedMaxDisp = false; - imageMode = 0; - - retrievedImageFlags[0] = false; - retrievedImageFlags[1] = true; - retrievedImageFlags[2] = false; - retrievedImageFlags[3] = true; - retrievedImageFlags[4] = false; - filename.clear(); - isFileReading = false; - - if( argc == 1 ) + cv::CommandLineParser parser(argc, argv, "{h help||}{cd|1|}{fmd|0|}{mode|0|}{m|01010|}{r||}"); + if (parser.has("h")) { help(); + printCommandLineParams(); + exit(0); } - else + isColorizeDisp = (parser.get("cd") != 0); + isFixedMaxDisp = (parser.get("fmd") != 0); + imageMode = parser.get("mode"); + int flags = parser.get("m"); + isFileReading = parser.has("r"); + if (isFileReading) + filename = parser.get("r"); + if (!parser.check()) { - for( int i = 1; i < argc; i++ ) - { - if( !strcmp( argv[i], "--help" ) || !strcmp( argv[i], "-h" ) ) - { - printCommandLineParams(); - exit(0); - } - else if( !strcmp( argv[i], "-cd" ) ) - { - isColorizeDisp = atoi(argv[++i]) == 0 ? false : true; - } - else if( !strcmp( argv[i], "-fmd" ) ) - { - isFixedMaxDisp = atoi(argv[++i]) == 0 ? false : true; - } - else if( !strcmp( argv[i], "-mode" ) ) - { - imageMode = atoi(argv[++i]); - } - else if( !strcmp( argv[i], "-m" ) ) - { - string mask( argv[++i] ); - if( mask.size() != 5) - CV_Error( Error::StsBadArg, "Incorrect length of -m argument string" ); - int val = atoi(mask.c_str()); - - int l = 100000, r = 10000, sum = 0; - for( int j = 0; j < 5; j++ ) - { - retrievedImageFlags[j] = ((val % l) / r ) == 0 ? false : true; - l /= 10; r /= 10; - if( retrievedImageFlags[j] ) sum++; - } - - if( sum == 0 ) - { - cout << "No one output image is selected." << endl; - exit(0); - } - } - else if( !strcmp( argv[i], "-r" ) ) - { - filename = argv[++i]; - isFileReading = true; - } - else - { - cout << "Unsupported command line argument: " << argv[i] << "." << endl; - exit(-1); - } - } + parser.printErrors(); + help(); + exit(-1); + } + if (flags % 100000 == 0) + { + cout << "No one output image is selected." << endl; + exit(0); + } + for (int i = 0; i < 5; i++) + { + retrievedImageFlags[4 - i] = (flags % 10 != 0); + flags /= 10; } } diff --git a/samples/cpp/pca.cpp b/samples/cpp/pca.cpp index db5fb3802f..35fd0c1a04 100644 --- a/samples/cpp/pca.cpp +++ b/samples/cpp/pca.cpp @@ -121,13 +121,19 @@ static void onTrackbar(int pos, void* ptr) // Main int main(int argc, char** argv) { - if (argc != 2) { - cout << "usage: " << argv[0] << " " << endl; - exit(1); + cv::CommandLineParser parser(argc, argv, "{@input||image list}{help h||show help message}"); + if (parser.has("help")) + { + parser.printMessage(); + exit(0); } - // Get the path to your CSV. - string imgList = string(argv[1]); + string imgList = parser.get("@input"); + if (imgList.empty()) + { + parser.printMessage(); + exit(1); + } // vector to hold the images vector images; diff --git a/samples/cpp/polar_transforms.cpp b/samples/cpp/polar_transforms.cpp index 3e2810e74b..872dda8c3f 100644 --- a/samples/cpp/polar_transforms.cpp +++ b/samples/cpp/polar_transforms.cpp @@ -1,6 +1,7 @@ #include "opencv2/imgproc/imgproc_c.h" #include "opencv2/videoio/videoio_c.h" #include "opencv2/highgui/highgui_c.h" +#include "opencv2/core/utility.hpp" #include #include @@ -20,15 +21,22 @@ int main( int argc, char** argv ) IplImage* recovered_img = 0; help(); - - if( argc == 1 || (argc == 2 && strlen(argv[1]) == 1 && isdigit(argv[1][0]))) - capture = cvCaptureFromCAM( argc == 2 ? argv[1][0] - '0' : 0 ); - else if( argc == 2 ) - capture = cvCaptureFromAVI( argv[1] ); + cv::CommandLineParser parser(argc, argv, "{help h||}{@input|0|}"); + if (parser.has("help")) + { + help(); + return 0; + } + std::string arg = parser.get("@input"); + if( arg.size() == 1 && isdigit(arg[0]) ) + capture = cvCaptureFromCAM( arg[0] - '0' ); + else + capture = cvCaptureFromAVI( arg.c_str() ); if( !capture ) { + const char* name = argv[0]; fprintf(stderr,"Could not initialize capturing...\n"); - fprintf(stderr,"Usage: %s , or \n %s \n",argv[0],argv[0]); + fprintf(stderr,"Usage: %s , or \n %s \n", name, name); help(); return -1; } diff --git a/samples/cpp/segment_objects.cpp b/samples/cpp/segment_objects.cpp index 72afbdeed3..3c217f679d 100644 --- a/samples/cpp/segment_objects.cpp +++ b/samples/cpp/segment_objects.cpp @@ -63,12 +63,17 @@ int main(int argc, char** argv) VideoCapture cap; bool update_bg_model = true; - help(); - - if( argc < 2 ) + CommandLineParser parser(argc, argv, "{help h||}{@input||}"); + if (parser.has("help")) + { + help(); + return 0; + } + string input = parser.get("@input"); + if (input.empty()) cap.open(0); else - cap.open(std::string(argv[1])); + cap.open(input); if( !cap.isOpened() ) { diff --git a/samples/cpp/select3dobj.cpp b/samples/cpp/select3dobj.cpp index ed598f2a1f..b13697fec2 100644 --- a/samples/cpp/select3dobj.cpp +++ b/samples/cpp/select3dobj.cpp @@ -30,14 +30,14 @@ const char* helphelp = "compute the homography of the plane the calibration pattern is on. It also shows grabCut\n" "segmentation etc.\n" "\n" -"select3dobj -w -h [-s ]\n" -" -i -o [video_filename/cameraId]\n" +"select3dobj -w= -h= [-s=]\n" +" -i= -o=\n" "\n" -" -w Number of chessboard corners wide\n" -" -h Number of chessboard corners width\n" -" [-s ] Optional measure of chessboard squares in meters\n" -" -i Camera matrix .yml file from calibration.cpp\n" -" -o Prefix the output segmentation images with this\n" +" -w= Number of chessboard corners wide\n" +" -h= Number of chessboard corners width\n" +" [-s=] Optional measure of chessboard squares in meters\n" +" -i= Camera matrix .yml file from calibration.cpp\n" +" -o= Prefix the output segmentation images with this\n" " [video_filename/cameraId] If present, read from that video file or that ID\n" "\n" "Using a camera's intrinsics (from calibrating a camera -- see calibration.cpp) and an\n" @@ -384,8 +384,8 @@ static bool readStringList( const string& filename, vector& l ) int main(int argc, char** argv) { - const char* help = "Usage: select3dobj -w -h [-s ]\n" - "\t-i -o [video_filename/cameraId]\n"; + const char* help = "Usage: select3dobj -w= -h= [-s=]\n" + "\t-i= -o= [video_filename/cameraId]\n"; const char* screen_help = "Actions: \n" "\tSelect object as 3D box with the mouse. That's it\n" @@ -394,82 +394,59 @@ int main(int argc, char** argv) "\tENTER - Confirm the selection. Grab next object in video mode.\n" "\tq - Exit the program\n"; - if(argc < 5) + cv::CommandLineParser parser(argc, argv, "{help h||}{w||}{h||}{s|1|}{i||}{o||}{@input|0|}"); + if (parser.has("help")) { puts(helphelp); puts(help); return 0; } - const char* intrinsicsFilename = 0; - const char* outprefix = 0; - const char* inputName = 0; + string intrinsicsFilename; + string outprefix = ""; + string inputName = ""; int cameraId = 0; Size boardSize; - double squareSize = 1; + double squareSize; vector imageList; - - for( int i = 1; i < argc; i++ ) + intrinsicsFilename = parser.get("i"); + outprefix = parser.get("o"); + boardSize.width = parser.get("w"); + boardSize.height = parser.get("h"); + squareSize = parser.get("s"); + if ( parser.get("@input").size() == 1 && isdigit(parser.get("@input")[0]) ) + cameraId = parser.get("@input"); + else + inputName = parser.get("@input"); + if (!parser.check()) { - if( strcmp(argv[i], "-i") == 0 ) - intrinsicsFilename = argv[++i]; - else if( strcmp(argv[i], "-o") == 0 ) - outprefix = argv[++i]; - else if( strcmp(argv[i], "-w") == 0 ) - { - if(sscanf(argv[++i], "%d", &boardSize.width) != 1 || boardSize.width <= 0) - { - printf("Incorrect -w parameter (must be a positive integer)\n"); - puts(help); - return 0; - } - } - else if( strcmp(argv[i], "-h") == 0 ) - { - if(sscanf(argv[++i], "%d", &boardSize.height) != 1 || boardSize.height <= 0) - { - printf("Incorrect -h parameter (must be a positive integer)\n"); - puts(help); - return 0; - } - } - else if( strcmp(argv[i], "-s") == 0 ) - { - if(sscanf(argv[++i], "%lf", &squareSize) != 1 || squareSize <= 0) - { - printf("Incorrect -w parameter (must be a positive real number)\n"); - puts(help); - return 0; - } - } - else if( argv[i][0] != '-' ) - { - if( isdigit(argv[i][0])) - sscanf(argv[i], "%d", &cameraId); - else - inputName = argv[i]; - } - else - { - printf("Incorrect option\n"); - puts(help); - return 0; - } + puts(help); + parser.printErrors(); + return 0; } - - if( !intrinsicsFilename || !outprefix || - boardSize.width <= 0 || boardSize.height <= 0 ) + if ( boardSize.width <= 0 ) { - printf("Some of the required parameters are missing\n"); + printf("Incorrect -w parameter (must be a positive integer)\n"); + puts(help); + return 0; + } + if ( boardSize.height <= 0 ) + { + printf("Incorrect -h parameter (must be a positive integer)\n"); + puts(help); + return 0; + } + if ( squareSize <= 0 ) + { + printf("Incorrect -s parameter (must be a positive real number)\n"); puts(help); return 0; } - Mat cameraMatrix, distCoeffs; Size calibratedImageSize; readCameraMatrix(intrinsicsFilename, cameraMatrix, distCoeffs, calibratedImageSize ); VideoCapture capture; - if( inputName ) + if( !inputName.empty() ) { if( !readStringList(inputName, imageList) && !capture.open(inputName)) @@ -486,21 +463,21 @@ int main(int argc, char** argv) const char* outbarename = 0; { - outbarename = strrchr(outprefix, '/'); - const char* tmp = strrchr(outprefix, '\\'); + outbarename = strrchr(outprefix.c_str(), '/'); + const char* tmp = strrchr(outprefix.c_str(), '\\'); char cmd[1000]; - sprintf(cmd, "mkdir %s", outprefix); + sprintf(cmd, "mkdir %s", outprefix.c_str()); if( tmp && tmp > outbarename ) outbarename = tmp; if( outbarename ) { - cmd[6 + outbarename - outprefix] = '\0'; + cmd[6 + outbarename - outprefix.c_str()] = '\0'; int result = system(cmd); CV_Assert(result == 0); outbarename++; } else - outbarename = outprefix; + outbarename = outprefix.c_str(); } Mat frame, shownFrame, selectedObjFrame, mapxy; @@ -510,7 +487,7 @@ int main(int argc, char** argv) setMouseCallback("View", onMouse, 0); bool boardFound = false; - string indexFilename = format("%s_index.yml", outprefix); + string indexFilename = format("%s_index.yml", outprefix.c_str()); vector capturedImgList; vector roiList; @@ -588,7 +565,7 @@ int main(int argc, char** argv) char path[1000]; for(;frameIdx < maxFrameIdx;frameIdx++) { - sprintf(path, "%s%04d.jpg", outprefix, frameIdx); + sprintf(path, "%s%04d.jpg", outprefix.c_str(), frameIdx); FILE* f = fopen(path, "rb"); if( !f ) break; @@ -596,7 +573,7 @@ int main(int argc, char** argv) } if( frameIdx == maxFrameIdx ) { - printf("Can not save the image as %s<...>.jpg", outprefix); + printf("Can not save the image as %s<...>.jpg", outprefix.c_str()); break; } imwrite(path, selectedObjFrame(r)); diff --git a/samples/cpp/shape_example.cpp b/samples/cpp/shape_example.cpp index e1c925f8c7..cb6cfbeef4 100644 --- a/samples/cpp/shape_example.cpp +++ b/samples/cpp/shape_example.cpp @@ -19,7 +19,7 @@ static void help() "This program demonstrates a method for shape comparisson based on Shape Context\n" "You should run the program providing a number between 1 and 20 for selecting an image in the folder ../data/shape_sample.\n" "Call\n" - "./shape_example [number between 1 and 20]\n\n"); + "./shape_example [number between 1 and 20, 1 default]\n\n"); } static vector simpleContour( const Mat& currentQuery, int n=300 ) @@ -54,16 +54,24 @@ static vector simpleContour( const Mat& currentQuery, int n=300 ) int main(int argc, char** argv) { - help(); string path = "../data/shape_sample/"; - int indexQuery = 1; - if( argc < 2 ) + cv::CommandLineParser parser(argc, argv, "{help h||}{@input|1|}"); + if (parser.has("help")) { - std::cout<<"Using first image as query."<("@input"); + if (!parser.check()) { - sscanf( argv[1], "%i", &indexQuery ); + parser.printErrors(); + help(); + return 1; + } + if (indexQuery < 1 || indexQuery > 20) + { + help(); + return 1; } cv::Ptr mysc = cv::createShapeContextDistanceExtractor(); diff --git a/samples/cpp/smiledetect.cpp b/samples/cpp/smiledetect.cpp index d15183fb06..f3f85764f7 100644 --- a/samples/cpp/smiledetect.cpp +++ b/samples/cpp/smiledetect.cpp @@ -25,61 +25,42 @@ void detectAndDraw( Mat& img, CascadeClassifier& cascade, CascadeClassifier& nestedCascade, double scale, bool tryflip ); -string cascadeName = "../../data/haarcascades/haarcascade_frontalface_alt.xml"; -string nestedCascadeName = "../../data/haarcascades/haarcascade_smile.xml"; +string cascadeName; +string nestedCascadeName; int main( int argc, const char** argv ) { VideoCapture capture; Mat frame, image; - const string scaleOpt = "--scale="; - size_t scaleOptLen = scaleOpt.length(); - const string cascadeOpt = "--cascade="; - size_t cascadeOptLen = cascadeOpt.length(); - const string nestedCascadeOpt = "--smile-cascade"; - size_t nestedCascadeOptLen = nestedCascadeOpt.length(); - const string tryFlipOpt = "--try-flip"; - size_t tryFlipOptLen = tryFlipOpt.length(); string inputName; - bool tryflip = false; + bool tryflip; help(); CascadeClassifier cascade, nestedCascade; - double scale = 1; - - for( int i = 1; i < argc; i++ ) + double scale; + cv::CommandLineParser parser(argc, argv, + "{help h||}{scale|1|}" + "{cascade|../../data/haarcascades/haarcascade_frontalface_alt.xml|}" + "{smile-cascade|../../data/haarcascades/haarcascade_smile.xml|}" + "{try-flip||}{@input||}"); + if (parser.has("help")) { - cout << "Processing " << i << " " << argv[i] << endl; - if( cascadeOpt.compare( 0, cascadeOptLen, argv[i], cascadeOptLen ) == 0 ) - { - cascadeName.assign( argv[i] + cascadeOptLen ); - cout << " from which we have cascadeName= " << cascadeName << endl; - } - else if( nestedCascadeOpt.compare( 0, nestedCascadeOptLen, argv[i], nestedCascadeOptLen ) == 0 ) - { - if( argv[i][nestedCascadeOpt.length()] == '=' ) - nestedCascadeName.assign( argv[i] + nestedCascadeOpt.length() + 1 ); - } - else if( scaleOpt.compare( 0, scaleOptLen, argv[i], scaleOptLen ) == 0 ) - { - if( !sscanf( argv[i] + scaleOpt.length(), "%lf", &scale ) || scale < 1 ) - scale = 1; - cout << " from which we read scale = " << scale << endl; - } - else if( tryFlipOpt.compare( 0, tryFlipOptLen, argv[i], tryFlipOptLen ) == 0 ) - { - tryflip = true; - cout << " will try to flip image horizontally to detect assymetric objects\n"; - } - else if( argv[i][0] == '-' ) - { - cerr << "WARNING: Unknown option " << argv[i] << endl; - } - else - inputName.assign( argv[i] ); + help(); + return 0; } - + cascadeName = parser.get("cascade"); + nestedCascadeName = parser.get("smile-cascade"); + tryflip = parser.has("try-flip"); + inputName = parser.get("@input"); + scale = parser.get("scale"); + if (!parser.check()) + { + help(); + return 1; + } + if (scale < 1) + scale = 1; if( !cascade.load( cascadeName ) ) { cerr << "ERROR: Could not load face cascade" << endl; @@ -92,10 +73,9 @@ int main( int argc, const char** argv ) help(); return -1; } - - if( inputName.empty() || (isdigit(inputName.c_str()[0]) && inputName.c_str()[1] == '\0') ) + if( inputName.empty() || (isdigit(inputName[0]) && inputName.size() == 1) ) { - int c = inputName.empty() ? 0 : inputName.c_str()[0] - '0' ; + int c = inputName.empty() ? 0 : inputName[0] - '0' ; if(!capture.open(c)) cout << "Capture from camera #" << c << " didn't work" << endl; } diff --git a/samples/cpp/starter_imagelist.cpp b/samples/cpp/starter_imagelist.cpp index a576030b95..89df0cc1b5 100644 --- a/samples/cpp/starter_imagelist.cpp +++ b/samples/cpp/starter_imagelist.cpp @@ -62,13 +62,18 @@ int process(vector images) int main(int ac, char** av) { - - if (ac != 2) + cv::CommandLineParser parser(ac, av, "{help h||}{@input||}"); + if (parser.has("help")) + { + help(av); + return 0; + } + std::string arg = parser.get("@input"); + if (arg.empty()) { help(av); return 1; } - std::string arg = av[1]; vector imagelist; if (!readStringList(arg,imagelist)) diff --git a/samples/cpp/starter_video.cpp b/samples/cpp/starter_video.cpp index 34f23d376c..d6bf1b7664 100644 --- a/samples/cpp/starter_video.cpp +++ b/samples/cpp/starter_video.cpp @@ -71,12 +71,17 @@ namespace { } int main(int ac, char** av) { - - if (ac != 2) { + cv::CommandLineParser parser(ac, av, "{help h||}{@input||}"); + if (parser.has("help")) + { + help(av); + return 0; + } + std::string arg = parser.get("@input"); + if (arg.empty()) { help(av); return 1; } - std::string arg = av[1]; VideoCapture capture(arg); //try to open string, this will attempt to open it as a video file or image sequence if (!capture.isOpened()) //if this fails, try to open as a video camera, through the use of an integer param capture.open(atoi(arg.c_str())); diff --git a/samples/cpp/stereo_calib.cpp b/samples/cpp/stereo_calib.cpp index 12ed3ef1ee..117c9bac5d 100644 --- a/samples/cpp/stereo_calib.cpp +++ b/samples/cpp/stereo_calib.cpp @@ -50,7 +50,7 @@ static int print_help() " matrix separately) stereo. \n" " Calibrate the cameras and display the\n" " rectified results along with the computed disparity images. \n" << endl; - cout << "Usage:\n ./stereo_calib -w board_width -h board_height [-nr /*dot not view results*/] \n" << endl; + cout << "Usage:\n ./stereo_calib -w= -h= \n" << endl; return 0; } @@ -347,50 +347,19 @@ int main(int argc, char** argv) { Size boardSize; string imagelistfn; - bool showRectified = true; - - for( int i = 1; i < argc; i++ ) - { - if( string(argv[i]) == "-w" ) - { - if( sscanf(argv[++i], "%d", &boardSize.width) != 1 || boardSize.width <= 0 ) - { - cout << "invalid board width" << endl; - return print_help(); - } - } - else if( string(argv[i]) == "-h" ) - { - if( sscanf(argv[++i], "%d", &boardSize.height) != 1 || boardSize.height <= 0 ) - { - cout << "invalid board height" << endl; - return print_help(); - } - } - else if( string(argv[i]) == "-nr" ) - showRectified = false; - else if( string(argv[i]) == "--help" ) - return print_help(); - else if( argv[i][0] == '-' ) - { - cout << "invalid option " << argv[i] << endl; - return 0; - } - else - imagelistfn = argv[i]; - } - - if( imagelistfn == "" ) - { - imagelistfn = "../data/stereo_calib.xml"; - boardSize = Size(9, 6); - } - else if( boardSize.width <= 0 || boardSize.height <= 0 ) + bool showRectified; + cv::CommandLineParser parser(argc, argv, "{w|9|}{h|6|}{nr||}{help||}{@input|../data/stereo_calib.xml|}"); + if (parser.has("help")) + return print_help(); + showRectified = !parser.has("nr"); + imagelistfn = parser.get("@input"); + boardSize.width = parser.get("w"); + boardSize.height = parser.get("h"); + if (!parser.check()) { - cout << "if you specified XML file with chessboards, you should also specify the board width and height (-w and -h options)" << endl; - return 0; + parser.printErrors(); + return 1; } - vector imagelist; bool ok = readStringList(imagelistfn, imagelist); if(!ok || imagelist.empty()) diff --git a/samples/cpp/stereo_match.cpp b/samples/cpp/stereo_match.cpp index 3a2943afe0..e3ebb5ddf0 100644 --- a/samples/cpp/stereo_match.cpp +++ b/samples/cpp/stereo_match.cpp @@ -21,8 +21,8 @@ static void print_help() { printf("\nDemo stereo matching converting L and R images into disparity and point clouds\n"); printf("\nUsage: stereo_match [--algorithm=bm|sgbm|hh|sgbm3way] [--blocksize=]\n" - "[--max-disparity=] [--scale=scale_factor>] [-i ] [-e ]\n" - "[--no-display] [-o ] [-p ]\n"); + "[--max-disparity=] [--scale=scale_factor>] [-i=] [-e=]\n" + "[--no-display] [-o=] [-p=]\n"); } static void saveXYZ(const char* filename, const Mat& mat) @@ -43,114 +43,90 @@ static void saveXYZ(const char* filename, const Mat& mat) int main(int argc, char** argv) { - const char* algorithm_opt = "--algorithm="; - const char* maxdisp_opt = "--max-disparity="; - const char* blocksize_opt = "--blocksize="; - const char* nodisplay_opt = "--no-display"; - const char* scale_opt = "--scale="; - - if(argc < 3) - { - print_help(); - return 0; - } - const char* img1_filename = 0; - const char* img2_filename = 0; - const char* intrinsic_filename = 0; - const char* extrinsic_filename = 0; - const char* disparity_filename = 0; - const char* point_cloud_filename = 0; + std::string img1_filename = ""; + std::string img2_filename = ""; + std::string intrinsic_filename = ""; + std::string extrinsic_filename = ""; + std::string disparity_filename = ""; + std::string point_cloud_filename = ""; enum { STEREO_BM=0, STEREO_SGBM=1, STEREO_HH=2, STEREO_VAR=3, STEREO_3WAY=4 }; int alg = STEREO_SGBM; - int SADWindowSize = 0, numberOfDisparities = 0; - bool no_display = false; - float scale = 1.f; + int SADWindowSize, numberOfDisparities; + bool no_display; + float scale; Ptr bm = StereoBM::create(16,9); Ptr sgbm = StereoSGBM::create(0,16,3); - - for( int i = 1; i < argc; i++ ) + cv::CommandLineParser parser(argc, argv, + "{help h||}{algorithm||}{max-disparity|0|}{blocksize|0|}{no-display||}{scale|1|}{i||}{e||}{o||}{p||}"); + if(parser.has("help")) { - if( argv[i][0] != '-' ) - { - if( !img1_filename ) - img1_filename = argv[i]; - else - img2_filename = argv[i]; - } - else if( strncmp(argv[i], algorithm_opt, strlen(algorithm_opt)) == 0 ) - { - char* _alg = argv[i] + strlen(algorithm_opt); - alg = strcmp(_alg, "bm") == 0 ? STEREO_BM : - strcmp(_alg, "sgbm") == 0 ? STEREO_SGBM : - strcmp(_alg, "hh") == 0 ? STEREO_HH : - strcmp(_alg, "var") == 0 ? STEREO_VAR : - strcmp(_alg, "sgbm3way") == 0 ? STEREO_3WAY : -1; - if( alg < 0 ) - { - printf("Command-line parameter error: Unknown stereo algorithm\n\n"); - print_help(); - return -1; - } - } - else if( strncmp(argv[i], maxdisp_opt, strlen(maxdisp_opt)) == 0 ) - { - if( sscanf( argv[i] + strlen(maxdisp_opt), "%d", &numberOfDisparities ) != 1 || - numberOfDisparities < 1 || numberOfDisparities % 16 != 0 ) - { - printf("Command-line parameter error: The max disparity (--maxdisparity=<...>) must be a positive integer divisible by 16\n"); - print_help(); - return -1; - } - } - else if( strncmp(argv[i], blocksize_opt, strlen(blocksize_opt)) == 0 ) - { - if( sscanf( argv[i] + strlen(blocksize_opt), "%d", &SADWindowSize ) != 1 || - SADWindowSize < 1 || SADWindowSize % 2 != 1 ) - { - printf("Command-line parameter error: The block size (--blocksize=<...>) must be a positive odd number\n"); - return -1; - } - } - else if( strncmp(argv[i], scale_opt, strlen(scale_opt)) == 0 ) - { - if( sscanf( argv[i] + strlen(scale_opt), "%f", &scale ) != 1 || scale < 0 ) - { - printf("Command-line parameter error: The scale factor (--scale=<...>) must be a positive floating-point number\n"); - return -1; - } - } - else if( strcmp(argv[i], nodisplay_opt) == 0 ) - no_display = true; - else if( strcmp(argv[i], "-i" ) == 0 ) - intrinsic_filename = argv[++i]; - else if( strcmp(argv[i], "-e" ) == 0 ) - extrinsic_filename = argv[++i]; - else if( strcmp(argv[i], "-o" ) == 0 ) - disparity_filename = argv[++i]; - else if( strcmp(argv[i], "-p" ) == 0 ) - point_cloud_filename = argv[++i]; - else - { - printf("Command-line parameter error: unknown option %s\n", argv[i]); - return -1; - } + print_help(); + return 0; } - - if( !img1_filename || !img2_filename ) + img1_filename = parser.get(0); + img2_filename = parser.get(1); + if (parser.has("algorithm")) + { + std::string _alg = parser.get("algorithm"); + alg = _alg == "bm" ? STEREO_BM : + _alg == "sgbm" ? STEREO_SGBM : + _alg == "hh" ? STEREO_HH : + _alg == "var" ? STEREO_VAR : + _alg == "sgbm3way" ? STEREO_3WAY : -1; + } + numberOfDisparities = parser.get("max-disparity"); + SADWindowSize = parser.get("blocksize"); + scale = parser.get("scale"); + no_display = parser.has("no-display"); + if( parser.has("i") ) + intrinsic_filename = parser.get("i"); + if( parser.has("e") ) + extrinsic_filename = parser.get("e"); + if( parser.has("o") ) + disparity_filename = parser.get("o"); + if( parser.has("p") ) + point_cloud_filename = parser.get("p"); + if (!parser.check()) + { + parser.printErrors(); + return 1; + } + if( alg < 0 ) + { + printf("Command-line parameter error: Unknown stereo algorithm\n\n"); + print_help(); + return -1; + } + if ( numberOfDisparities < 1 || numberOfDisparities % 16 != 0 ) + { + printf("Command-line parameter error: The max disparity (--maxdisparity=<...>) must be a positive integer divisible by 16\n"); + print_help(); + return -1; + } + if (scale < 0) + { + printf("Command-line parameter error: The scale factor (--scale=<...>) must be a positive floating-point number\n"); + return -1; + } + if (SADWindowSize < 1 || SADWindowSize % 2 != 1) + { + printf("Command-line parameter error: The block size (--blocksize=<...>) must be a positive odd number\n"); + return -1; + } + if( img1_filename.empty() || img2_filename.empty() ) { printf("Command-line parameter error: both left and right images must be specified\n"); return -1; } - - if( (intrinsic_filename != 0) ^ (extrinsic_filename != 0) ) + if( (!intrinsic_filename.empty()) ^ (!extrinsic_filename.empty()) ) { printf("Command-line parameter error: either both intrinsic and extrinsic parameters must be specified, or none of them (when the stereo pair is already rectified)\n"); return -1; } - if( extrinsic_filename == 0 && point_cloud_filename ) + if( extrinsic_filename.empty() && !point_cloud_filename.empty() ) { printf("Command-line parameter error: extrinsic and intrinsic parameters must be specified to compute the point cloud\n"); return -1; @@ -186,13 +162,13 @@ int main(int argc, char** argv) Rect roi1, roi2; Mat Q; - if( intrinsic_filename ) + if( !intrinsic_filename.empty() ) { // reading intrinsic parameters FileStorage fs(intrinsic_filename, FileStorage::READ); if(!fs.isOpened()) { - printf("Failed to open file %s\n", intrinsic_filename); + printf("Failed to open file %s\n", intrinsic_filename.c_str()); return -1; } @@ -208,7 +184,7 @@ int main(int argc, char** argv) fs.open(extrinsic_filename, FileStorage::READ); if(!fs.isOpened()) { - printf("Failed to open file %s\n", extrinsic_filename); + printf("Failed to open file %s\n", extrinsic_filename.c_str()); return -1; } @@ -297,16 +273,16 @@ int main(int argc, char** argv) printf("\n"); } - if(disparity_filename) + if(!disparity_filename.empty()) imwrite(disparity_filename, disp8); - if(point_cloud_filename) + if(!point_cloud_filename.empty()) { printf("storing the point cloud..."); fflush(stdout); Mat xyz; reprojectImageTo3D(disp, xyz, Q, true); - saveXYZ(point_cloud_filename, xyz); + saveXYZ(point_cloud_filename.c_str(), xyz); printf("\n"); } diff --git a/samples/cpp/train_HOG.cpp b/samples/cpp/train_HOG.cpp index 0a94e348c5..900637b6b3 100644 --- a/samples/cpp/train_HOG.cpp +++ b/samples/cpp/train_HOG.cpp @@ -88,7 +88,7 @@ void load_images( const string & prefix, const string & filename, vector< Mat > while( !end_of_parsing ) { getline( file, line ); - if( line == "" ) // no more file to read + if( line.empty() ) // no more file to read { end_of_parsing = true; break; @@ -403,23 +403,33 @@ void test_it( const Size & size ) int main( int argc, char** argv ) { - if( argc != 5 ) + cv::CommandLineParser parser(argc, argv, "{help h|| show help message}" + "{pd||pos_dir}{p||pos.lst}{nd||neg_dir}{n||neg.lst}"); + if (parser.has("help")) { - cout << "Wrong number of parameters." << endl - << "Usage: " << argv[0] << " pos_dir pos.lst neg_dir neg.lst" << endl - << "example: " << argv[0] << " /INRIA_dataset/ Train/pos.lst /INRIA_dataset/ Train/neg.lst" << endl; - exit( -1 ); + parser.printMessage(); + exit(0); } vector< Mat > pos_lst; vector< Mat > full_neg_lst; vector< Mat > neg_lst; vector< Mat > gradient_lst; vector< int > labels; - - load_images( argv[1], argv[2], pos_lst ); + string pos_dir = parser.get("pd"); + string pos = parser.get("p"); + string neg_dir = parser.get("nd"); + string neg = parser.get("n"); + if( pos_dir.empty() || pos.empty() || neg_dir.empty() || neg.empty() ) + { + cout << "Wrong number of parameters." << endl + << "Usage: " << argv[0] << " --pd=pos_dir -p=pos.lst --nd=neg_dir -n=neg.lst" << endl + << "example: " << argv[0] << " --pd=/INRIA_dataset/ -p=Train/pos.lst --nd=/INRIA_dataset/ -n=Train/neg.lst" << endl; + exit( -1 ); + } + load_images( pos_dir, pos, pos_lst ); labels.assign( pos_lst.size(), +1 ); const unsigned int old = (unsigned int)labels.size(); - load_images( argv[3], argv[4], full_neg_lst ); + load_images( neg_dir, neg, full_neg_lst ); sample_neg( full_neg_lst, neg_lst, Size( 96,160 ) ); labels.insert( labels.end(), neg_lst.size(), -1 ); CV_Assert( old < labels.size() ); diff --git a/samples/cpp/tree_engine.cpp b/samples/cpp/tree_engine.cpp index d9fbb96788..4412588753 100644 --- a/samples/cpp/tree_engine.cpp +++ b/samples/cpp/tree_engine.cpp @@ -12,9 +12,9 @@ static void help() { printf( "\nThis sample demonstrates how to use different decision trees and forests including boosting and random trees.\n" - "Usage:\n\t./tree_engine [-r ] [-ts type_spec] \n" - "where -r specified the 0-based index of the response (0 by default)\n" - "-ts specifies the var type spec in the form ord[n1,n2-n3,n4-n5,...]cat[m1-m2,m3,m4-m5,...]\n" + "Usage:\n\t./tree_engine [-r=] [-ts=type_spec] \n" + "where -r= specified the 0-based index of the response (0 by default)\n" + "-ts= specifies the var type spec in the form ord[n1,n2-n3,n4-n5,...]cat[m1-m2,m3,m4-m5,...]\n" " is the name of training data file in comma-separated value format\n\n"); } @@ -34,38 +34,30 @@ static void train_and_print_errs(Ptr model, const Ptr& dat int main(int argc, char** argv) { - if(argc < 2) + cv::CommandLineParser parser(argc, argv, "{ help h | | }{r | 0 | }{ts | | }{@input | | }"); + if (parser.has("help")) { help(); return 0; } - const char* filename = 0; - int response_idx = 0; + std::string filename = parser.get("@input"); + int response_idx; std::string typespec; - - for(int i = 1; i < argc; i++) + response_idx = parser.get("r"); + typespec = parser.get("ts"); + if( filename.empty() || !parser.check() ) { - if(strcmp(argv[i], "-r") == 0) - sscanf(argv[++i], "%d", &response_idx); - else if(strcmp(argv[i], "-ts") == 0) - typespec = argv[++i]; - else if(argv[i][0] != '-' ) - filename = argv[i]; - else - { - printf("Error. Invalid option %s\n", argv[i]); - help(); - return -1; - } + parser.printErrors(); + help(); + return 0; } - - printf("\nReading in %s...\n\n",filename); + printf("\nReading in %s...\n\n",filename.c_str()); const double train_test_split_ratio = 0.5; Ptr data = TrainData::loadFromCSV(filename, 0, response_idx, response_idx+1, typespec); if( data.empty() ) { - printf("ERROR: File %s can not be read\n", filename); + printf("ERROR: File %s can not be read\n", filename.c_str()); return 0; } diff --git a/samples/cpp/tvl1_optical_flow.cpp b/samples/cpp/tvl1_optical_flow.cpp index dee9cf6e33..55b5558ebe 100644 --- a/samples/cpp/tvl1_optical_flow.cpp +++ b/samples/cpp/tvl1_optical_flow.cpp @@ -148,23 +148,33 @@ static void writeOpticalFlowToFile(const Mat_& flow, const string& file int main(int argc, const char* argv[]) { - if (argc < 3) + cv::CommandLineParser parser(argc, argv, "{help h || show help message}" + "{ @frame0 | | frame 0}{ @frame1 | | frame 1}{ @output | | output flow}"); + if (parser.has("help")) { - cerr << "Usage : " << argv[0] << " []" << endl; + parser.printMessage(); + return 0; + } + string frame0_name = parser.get("@frame0"); + string frame1_name = parser.get("@frame1"); + string file = parser.get("@output"); + if (frame0_name.empty() || frame1_name.empty() || file.empty()) + { + cerr << "Usage : " << argv[0] << " [] [] []" << endl; return -1; } - Mat frame0 = imread(argv[1], IMREAD_GRAYSCALE); - Mat frame1 = imread(argv[2], IMREAD_GRAYSCALE); + Mat frame0 = imread(frame0_name, IMREAD_GRAYSCALE); + Mat frame1 = imread(frame1_name, IMREAD_GRAYSCALE); if (frame0.empty()) { - cerr << "Can't open image [" << argv[1] << "]" << endl; + cerr << "Can't open image [" << parser.get("frame0") << "]" << endl; return -1; } if (frame1.empty()) { - cerr << "Can't open image [" << argv[2] << "]" << endl; + cerr << "Can't open image [" << parser.get("frame1") << "]" << endl; return -1; } @@ -184,9 +194,8 @@ int main(int argc, const char* argv[]) Mat out; drawOpticalFlow(flow, out); - - if (argc == 4) - writeOpticalFlowToFile(flow, argv[3]); + if (!file.empty()) + writeOpticalFlowToFile(flow, file); imshow("Flow", out); waitKey(); diff --git a/samples/cpp/videostab.cpp b/samples/cpp/videostab.cpp index 2eea9b9026..3fb7fb40bd 100644 --- a/samples/cpp/videostab.cpp +++ b/samples/cpp/videostab.cpp @@ -73,9 +73,9 @@ void printHelp() cout << "OpenCV video stabilizer.\n" "Usage: videostab [arguments]\n\n" "Arguments:\n" - " -m, --model=(transl|transl_and_scale|rigid|similarity|affine|homography)\n" + " -m=, --model=(transl|transl_and_scale|rigid|similarity|affine|homography)\n" " Set motion model. The default is affine.\n" - " -lp, --lin-prog-motion-est=(yes|no)\n" + " -lp=, --lin-prog-motion-est=(yes|no)\n" " Turn on/off LP based motion estimation. The default is no.\n" " --subset=(|auto)\n" " Number of random samples per one motion hypothesis. The default is auto.\n" @@ -89,16 +89,16 @@ void printHelp() " Number of keypoints to find in each frame. The default is 1000.\n" " --local-outlier-rejection=(yes|no)\n" " Perform local outlier rejection. The default is no.\n\n" - " -sm, --save-motions=(|no)\n" + " -sm=, --save-motions=(|no)\n" " Save estimated motions into file. The default is no.\n" - " -lm, --load-motions=(|no)\n" + " -lm=, --load-motions=(|no)\n" " Load motions from file. The default is no.\n\n" - " -r, --radius=\n" + " -r=, --radius=\n" " Set sliding window radius. The default is 15.\n" " --stdev=(|auto)\n" " Set smoothing weights standard deviation. The default is auto\n" " (i.e. sqrt(radius)).\n" - " -lps, --lin-prog-stab=(yes|no)\n" + " -lps=, --lin-prog-stab=(yes|no)\n" " Turn on/off linear programming based stabilization method.\n" " --lps-trim-ratio=(|auto)\n" " Trimming ratio used in linear programming based method.\n" @@ -114,28 +114,28 @@ void printHelp() " Do deblurring.\n" " --deblur-sens=\n" " Set deblurring sensitivity (from 0 to +inf). The default is 0.1.\n\n" - " -t, --trim-ratio=\n" + " -t=, --trim-ratio=\n" " Set trimming ratio (from 0 to 0.5). The default is 0.1.\n" - " -et, --est-trim=(yes|no)\n" + " -et=, --est-trim=(yes|no)\n" " Estimate trim ratio automatically. The default is yes.\n" - " -ic, --incl-constr=(yes|no)\n" + " -ic=, --incl-constr=(yes|no)\n" " Ensure the inclusion constraint is always satisfied. The default is no.\n\n" - " -bm, --border-mode=(replicate|reflect|const)\n" + " -bm=, --border-mode=(replicate|reflect|const)\n" " Set border extrapolation mode. The default is replicate.\n\n" " --mosaic=(yes|no)\n" " Do consistent mosaicing. The default is no.\n" " --mosaic-stdev=\n" " Consistent mosaicing stdev threshold. The default is 10.0.\n\n" - " -mi, --motion-inpaint=(yes|no)\n" + " -mi=, --motion-inpaint=(yes|no)\n" " Do motion inpainting (requires CUDA support). The default is no.\n" " --mi-dist-thresh=\n" " Estimated flow distance threshold for motion inpainting. The default is 5.0.\n\n" - " -ci, --color-inpaint=(no|average|ns|telea)\n" + " -ci=, --color-inpaint=(no|average|ns|telea)\n" " Do color inpainting. The defailt is no.\n" " --ci-radius=\n" " Set color inpainting radius (for ns and telea options only).\n" " The default is 2.0\n\n" - " -ws, --wobble-suppress=(yes|no)\n" + " -ws=, --wobble-suppress=(yes|no)\n" " Perform wobble suppression. The default is no.\n" " --ws-lp=(yes|no)\n" " Turn on/off LP based motion estimation. The default is no.\n" @@ -156,13 +156,13 @@ void printHelp() " Number of keypoints to find in each frame. The default is 1000.\n" " --ws-local-outlier-rejection=(yes|no)\n" " Perform local outlier rejection. The default is no.\n\n" - " -sm2, --save-motions2=(|no)\n" + " -sm2=, --save-motions2=(|no)\n" " Save motions estimated for wobble suppression. The default is no.\n" - " -lm2, --load-motions2=(|no)\n" + " -lm2=, --load-motions2=(|no)\n" " Load motions for wobble suppression from file. The default is no.\n\n" " -gpu=(yes|no)\n" " Use CUDA optimization whenever possible. The default is no.\n\n" - " -o, --output=(no|)\n" + " -o=, --output=(no|)\n" " Set output file path explicitely. The default is stabilized.avi.\n" " --fps=(|auto)\n" " Set output video FPS explicitely. By default the source FPS is used (auto).\n" diff --git a/samples/cpp/watershed.cpp b/samples/cpp/watershed.cpp index b92bbf1fd1..9f2e69ec6b 100644 --- a/samples/cpp/watershed.cpp +++ b/samples/cpp/watershed.cpp @@ -48,7 +48,13 @@ static void onMouse( int event, int x, int y, int flags, void* ) int main( int argc, char** argv ) { - char* filename = argc >= 2 ? argv[1] : (char*)"../data/fruits.jpg"; + cv::CommandLineParser parser(argc, argv, "{help h | | }{ @input | ../data/fruits.jpg | }"); + if (parser.has("help")) + { + help(); + return 0; + } + string filename = parser.get("@input"); Mat img0 = imread(filename, 1), imgGray; if( img0.empty() ) diff --git a/samples/tapi/ufacedetect.cpp b/samples/tapi/ufacedetect.cpp index e3c82a2c6a..f6dc0ce1d9 100644 --- a/samples/tapi/ufacedetect.cpp +++ b/samples/tapi/ufacedetect.cpp @@ -36,56 +36,37 @@ int main( int argc, const char** argv ) VideoCapture capture; UMat frame, image; Mat canvas; - const string scaleOpt = "--scale="; - size_t scaleOptLen = scaleOpt.length(); - const string cascadeOpt = "--cascade="; - size_t cascadeOptLen = cascadeOpt.length(); - const string nestedCascadeOpt = "--nested-cascade"; - size_t nestedCascadeOptLen = nestedCascadeOpt.length(); - const string tryFlipOpt = "--try-flip"; - size_t tryFlipOptLen = tryFlipOpt.length(); - String inputName; - bool tryflip = false; - help(); + string inputName; + bool tryflip; CascadeClassifier cascade, nestedCascade; - double scale = 1; + double scale; - for( int i = 1; i < argc; i++ ) + cv::CommandLineParser parser(argc, argv, + "{cascade|../../data/haarcascades/haarcascade_frontalface_alt.xml|}" + "{nested-cascade|../../data/haarcascades/haarcascade_eye_tree_eyeglasses.xml|}" + "{help h ||}{scale|1|}{try-flip||}{@filename||}" + ); + if (parser.has("help")) { - cout << "Processing " << i << " " << argv[i] << endl; - if( cascadeOpt.compare( 0, cascadeOptLen, argv[i], cascadeOptLen ) == 0 ) - { - cascadeName.assign( argv[i] + cascadeOptLen ); - cout << " from which we have cascadeName= " << cascadeName << endl; - } - else if( nestedCascadeOpt.compare( 0, nestedCascadeOptLen, argv[i], nestedCascadeOptLen ) == 0 ) - { - if( argv[i][nestedCascadeOpt.length()] == '=' ) - nestedCascadeName.assign( argv[i] + nestedCascadeOpt.length() + 1 ); - if( !nestedCascade.load( nestedCascadeName ) ) - cerr << "WARNING: Could not load classifier cascade for nested objects" << endl; - } - else if( scaleOpt.compare( 0, scaleOptLen, argv[i], scaleOptLen ) == 0 ) - { - if( !sscanf( argv[i] + scaleOpt.length(), "%lf", &scale ) ) - scale = 1; - cout << " from which we read scale = " << scale << endl; - } - else if( tryFlipOpt.compare( 0, tryFlipOptLen, argv[i], tryFlipOptLen ) == 0 ) - { - tryflip = true; - cout << " will try to flip image horizontally to detect assymetric objects\n"; - } - else if( argv[i][0] == '-' ) - { - cerr << "WARNING: Unknown option " << argv[i] << endl; - } - else - inputName = argv[i]; + help(); + return 0; + } + cascadeName = parser.get("cascade"); + nestedCascadeName = parser.get("nested-cascade"); + scale = parser.get("scale"); + tryflip = parser.has("try-flip"); + inputName = parser.get("@filename"); + if ( !parser.check()) + { + parser.printErrors(); + help(); + return -1; } + if ( !nestedCascade.load( nestedCascadeName ) ) + cerr << "WARNING: Could not load classifier cascade for nested objects" << endl; if( !cascade.load( cascadeName ) ) { cerr << "ERROR: Could not load classifier cascade" << endl; @@ -95,9 +76,9 @@ int main( int argc, const char** argv ) cout << "old cascade: " << (cascade.isOldFormatCascade() ? "TRUE" : "FALSE") << endl; - if( inputName.empty() || (isdigit(inputName.c_str()[0]) && inputName.c_str()[1] == '\0') ) + if( inputName.empty() || (isdigit(inputName[0]) && inputName.size() == 1) ) { - int c = inputName.empty() ? 0 : inputName.c_str()[0] - '0'; + int c = inputName.empty() ? 0 : inputName[0] - '0'; if(!capture.open(c)) cout << "Capture from camera #" << c << " didn't work" << endl; }