Merge pull request #5828 from mshabunin:CommandLineArgs

pull/5833/head
Alexander Alekhin 9 years ago
commit 03e74330fa
  1. 96
      samples/cpp/3calibration.cpp
  2. 100
      samples/cpp/autofocus.cpp
  3. 184
      samples/cpp/calibration.cpp
  4. 30
      samples/cpp/camshiftdemo.cpp
  5. 8
      samples/cpp/connected_components.cpp
  6. 9
      samples/cpp/contours2.cpp
  7. 10
      samples/cpp/convexhull.cpp
  8. 9
      samples/cpp/cout_mat.cpp
  9. 17
      samples/cpp/create_mask.cpp
  10. 9
      samples/cpp/delaunay2.cpp
  11. 9
      samples/cpp/demhist.cpp
  12. 14
      samples/cpp/detect_blob.cpp
  13. 15
      samples/cpp/detect_mser.cpp
  14. 10
      samples/cpp/dft.cpp
  15. 8
      samples/cpp/distrans.cpp
  16. 9
      samples/cpp/drawing.cpp
  17. 9
      samples/cpp/edge.cpp
  18. 81
      samples/cpp/facedetect.cpp
  19. 64
      samples/cpp/facial_features.cpp
  20. 8
      samples/cpp/fback.cpp
  21. 13
      samples/cpp/ffilldemo.cpp
  22. 13
      samples/cpp/filestorage.cpp
  23. 28
      samples/cpp/fitellipse.cpp
  24. 9
      samples/cpp/grabcut.cpp
  25. 17
      samples/cpp/houghcircles.cpp
  26. 17
      samples/cpp/houghlines.cpp
  27. 15
      samples/cpp/image.cpp
  28. 16
      samples/cpp/image_alignment.cpp
  29. 11
      samples/cpp/image_sequence.cpp
  30. 12
      samples/cpp/imagelist_creator.cpp
  31. 10
      samples/cpp/inpaint.cpp
  32. 106
      samples/cpp/intelperc_capture.cpp
  33. 40
      samples/cpp/laplace.cpp
  34. 71
      samples/cpp/letter_recog.cpp
  35. 19
      samples/cpp/lkdemo.cpp
  36. 12
      samples/cpp/lsd_lines.cpp
  37. 19
      samples/cpp/mask_tmpl.cpp
  38. 23
      samples/cpp/matchmethod_orb_akaze_brisk.cpp
  39. 14
      samples/cpp/morphology2.cpp
  40. 14
      samples/cpp/npr_demo.cpp
  41. 103
      samples/cpp/openni_capture.cpp
  42. 16
      samples/cpp/pca.cpp
  43. 20
      samples/cpp/polar_transforms.cpp
  44. 13
      samples/cpp/segment_objects.cpp
  45. 125
      samples/cpp/select3dobj.cpp
  46. 22
      samples/cpp/shape_example.cpp
  47. 72
      samples/cpp/smiledetect.cpp
  48. 11
      samples/cpp/starter_imagelist.cpp
  49. 11
      samples/cpp/starter_video.cpp
  50. 55
      samples/cpp/stereo_calib.cpp
  51. 174
      samples/cpp/stereo_match.cpp
  52. 28
      samples/cpp/train_HOG.cpp
  53. 38
      samples/cpp/tree_engine.cpp
  54. 27
      samples/cpp/tvl1_optical_flow.cpp
  55. 32
      samples/cpp/videostab.cpp
  56. 8
      samples/cpp/watershed.cpp
  57. 71
      samples/tapi/ufacedetect.cpp

@ -6,6 +6,7 @@
#include "opencv2/imgproc/imgproc.hpp" #include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/imgcodecs/imgcodecs.hpp" #include "opencv2/imgcodecs/imgcodecs.hpp"
#include "opencv2/highgui/highgui.hpp" #include "opencv2/highgui/highgui.hpp"
#include "opencv2/core/utility.hpp"
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
@ -20,12 +21,12 @@ static void help()
{ {
printf( "\nThis is a camera calibration sample that calibrates 3 horizontally placed cameras together.\n" printf( "\nThis is a camera calibration sample that calibrates 3 horizontally placed cameras together.\n"
"Usage: 3calibration\n" "Usage: 3calibration\n"
" -w <board_width> # the number of inner corners per one of board dimension\n" " -w=<board_width> # the number of inner corners per one of board dimension\n"
" -h <board_height> # the number of inner corners per another board dimension\n" " -h=<board_height> # the number of inner corners per another board dimension\n"
" [-s <squareSize>] # square size in some user-defined units (1 by default)\n" " [-s=<squareSize>] # square size in some user-defined units (1 by default)\n"
" [-o <out_camera_params>] # the output filename for intrinsic [and extrinsic] parameters\n" " [-o=<out_camera_params>] # the output filename for intrinsic [and extrinsic] parameters\n"
" [-zt] # assume zero tangential distortion\n" " [-zt] # assume zero tangential distortion\n"
" [-a <aspectRatio>] # fix aspect ratio (fx/fy)\n" " [-a=<aspectRatio>] # fix aspect ratio (fx/fy)\n"
" [-p] # fix the principal point at the center\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" " [input_data] # input data - text file with a list of the images of the board\n"
"\n" ); "\n" );
@ -42,7 +43,7 @@ static void calcChessboardCorners(Size boardSize, float squareSize, vector<Point
float(i*squareSize), 0)); float(i*squareSize), 0));
} }
static bool run3Calibration( vector<vector<Point2f> > imagePoints1, static bool run3Calibration(vector<vector<Point2f> > imagePoints1,
vector<vector<Point2f> > imagePoints2, vector<vector<Point2f> > imagePoints2,
vector<vector<Point2f> > imagePoints3, vector<vector<Point2f> > imagePoints3,
Size imageSize, Size boardSize, Size imageSize, Size boardSize,
@ -177,65 +178,48 @@ int main( int argc, char** argv )
int i, k; int i, k;
int flags = 0; int flags = 0;
Size boardSize, imageSize; Size boardSize, imageSize;
float squareSize = 1.f, aspectRatio = 1.f; float squareSize, aspectRatio;
const char* outputFilename = "out_camera_data.yml"; string outputFilename;
const char* inputFilename = 0; string inputFilename = "";
vector<vector<Point2f> > imgpt[3]; vector<vector<Point2f> > imgpt[3];
vector<string> imageList; vector<string> 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(); help();
return 1; return 0;
} }
boardSize.width = parser.get<int>("w");
boardSize.height = parser.get<int>("h");
for( i = 1; i < argc; i++ ) squareSize = parser.get<float>("s");
aspectRatio = parser.get<float>("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<string>("o");
inputFilename = parser.get<string>("@input");
if (!parser.check())
{ {
const char* s = argv[i]; help();
if( strcmp( s, "-w" ) == 0 ) parser.printErrors();
{ return -1;
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;
} }
if (boardSize.width <= 0)
if( !inputFilename || 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) || !readStringList(inputFilename, imageList) ||
imageList.size() == 0 || imageList.size() % 3 != 0 ) imageList.size() == 0 || imageList.size() % 3 != 0 )
{ {

@ -43,11 +43,11 @@ const double epsylon = 0.0005; // compression, noice, etc.
struct Args_t struct Args_t
{ {
const char * deviceName; string deviceName;
const char * output; string output;
unsigned int fps; int fps;
unsigned int minimumFocusStep; int minimumFocusStep;
unsigned int breakLimit; int breakLimit;
bool measure; bool measure;
bool verbose; bool verbose;
} GlobalArgs; } GlobalArgs;
@ -218,12 +218,12 @@ static void showHelp(const char * pName, bool welcomeMsg)
cout << "usage " << pName << ": [OPTIONS] DEVICE_NAME\n\n" cout << "usage " << pName << ": [OPTIONS] DEVICE_NAME\n\n"
"OPTIONS:\n" "OPTIONS:\n"
"\t-h\t\treturns this help message,\n" "\t-h\t\treturns this help message,\n"
"\t-o FILENAME\tsave output video in file (MJPEG only),\n" "\t-o=<FILENAME>\tsave output video in file (MJPEG only),\n"
"\t-f FPS\t\tframes per second in output video,\n" "\t-f=FPS\t\tframes per second in output video,\n"
"\t-m\t\tmeasure exposition\n" "\t-m\t\tmeasure exposition\n"
"\t\t\t(returns rates from closest focus to INTY\n" "\t\t\t(returns rates from closest focus to INTY\n"
"\t\t\tfor every minimum step),\n" "\t\t\tfor every minimum step),\n"
"\t-d INT\t\tset minimum focus step,\n" "\t-d=<INT>\t\tset minimum focus step,\n"
"\t-v\t\tverbose mode.\n\n\n" "\t-v\t\tverbose mode.\n\n\n"
"DEVICE_NAME\t\tis your digital camera model substring.\n\n\n" "DEVICE_NAME\t\tis your digital camera model substring.\n\n\n"
"On runtime you can use keys to control:\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) static bool parseArguments(int argc, char ** argv)
{ {
int index; cv::CommandLineParser parser(argc, argv, "{h help ||}{o||}{f||}{m||}{d|0|}{v||}{@device|Nikon|}");
GlobalArgs.deviceName = "Nikon"; if (parser.has("help"))
GlobalArgs.output = NULL; return false;
GlobalArgs.fps = DEFAULT_OUTPUT_FPS;
GlobalArgs.minimumFocusStep = 0;
GlobalArgs.breakLimit = DEFAULT_BREAK_LIMIT; GlobalArgs.breakLimit = DEFAULT_BREAK_LIMIT;
GlobalArgs.measure = false; if (parser.has("o"))
GlobalArgs.verbose = false; GlobalArgs.output = parser.get<string>("o");
else
for (index = 1; index < argc; index++) GlobalArgs.output = "";
if (parser.has("f"))
GlobalArgs.fps = parser.get<int>("f");
else
GlobalArgs.fps = DEFAULT_OUTPUT_FPS;
GlobalArgs.measure = parser.has("m");
GlobalArgs.verbose = parser.has("v");
GlobalArgs.minimumFocusStep = parser.get<int>("d");
GlobalArgs.deviceName = parser.get<string>("@device");
if (!parser.check())
{ {
const char * arg = argv[index]; parser.printErrors();
if (strcmp(arg, "-h") == 0) return false;
{ }
return false; if (GlobalArgs.fps < 0)
} {
else if (strcmp(arg, "-o") == 0) cerr << "Invalid fps argument." << endl;
{ return false;
GlobalArgs.output = argv[++index]; }
} if (GlobalArgs.minimumFocusStep < 0)
else if (strcmp(arg, "-f") == 0) {
{ cerr << "Invalid minimum focus step argument." << endl;
if (sscanf(argv[++index], "%u", &GlobalArgs.fps) != 1 return false;
|| 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;
}
} }
return true; return true;
} }
@ -343,7 +319,7 @@ int main(int argc, char ** argv)
cap.set(CAP_PROP_GPHOTO2_PREVIEW, true); cap.set(CAP_PROP_GPHOTO2_PREVIEW, true);
cap.set(CAP_PROP_VIEWFINDER, true); cap.set(CAP_PROP_VIEWFINDER, true);
cap >> frame; // To check PREVIEW output Size. 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)); 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'); int fourCC = CV_FOURCC('M', 'J', 'P', 'G');
@ -375,7 +351,7 @@ int main(int argc, char ** argv)
{ {
break; break;
} }
if (GlobalArgs.output != NULL) if (!GlobalArgs.output.empty())
{ {
videoWriter << frame; videoWriter << frame;
} }

@ -16,11 +16,11 @@ using namespace std;
const char * usage = const char * usage =
" \nexample command line for calibration from a live feed.\n" " \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" " \n"
" example command line for calibration from a list of stored images:\n" " example command line for calibration from a list of stored images:\n"
" imagelist_creator image_list.xml *.png\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" " where image_list.xml is the standard OpenCV XML/YAML\n"
" use imagelist_creator to create the xml or yaml list\n" " use imagelist_creator to create the xml or yaml list\n"
" file consisting of the list of strings, e.g.:\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" printf( "This is a camera calibration sample.\n"
"Usage: calibration\n" "Usage: calibration\n"
" -w <board_width> # the number of inner corners per one of board dimension\n" " -w=<board_width> # the number of inner corners per one of board dimension\n"
" -h <board_height> # the number of inner corners per another board dimension\n" " -h=<board_height> # the number of inner corners per another board dimension\n"
" [-pt <pattern>] # the type of pattern: chessboard or circles' grid\n" " [-pt=<pattern>] # the type of pattern: chessboard or circles' grid\n"
" [-n <number_of_frames>] # the number of frames to use for calibration\n" " [-n=<number_of_frames>] # the number of frames to use for calibration\n"
" # (if not specified, it will be set to the number\n" " # (if not specified, it will be set to the number\n"
" # of board views actually available)\n" " # of board views actually available)\n"
" [-d <delay>] # a minimum delay in ms between subsequent attempts to capture a next view\n" " [-d=<delay>] # a minimum delay in ms between subsequent attempts to capture a next view\n"
" # (used only for video capturing)\n" " # (used only for video capturing)\n"
" [-s <squareSize>] # square size in some user-defined units (1 by default)\n" " [-s=<squareSize>] # square size in some user-defined units (1 by default)\n"
" [-o <out_camera_params>] # the output filename for intrinsic [and extrinsic] parameters\n" " [-o=<out_camera_params>] # the output filename for intrinsic [and extrinsic] parameters\n"
" [-op] # write detected feature points\n" " [-op] # write detected feature points\n"
" [-oe] # write extrinsic parameters\n" " [-oe] # write extrinsic parameters\n"
" [-zt] # assume zero tangential distortion\n" " [-zt] # assume zero tangential distortion\n"
" [-a <aspectRatio>] # fix aspect ratio (fx/fy)\n" " [-a=<aspectRatio>] # fix aspect ratio (fx/fy)\n"
" [-p] # fix the principal point at the center\n" " [-p] # fix the principal point at the center\n"
" [-v] # flip the captured images around the horizontal axis\n" " [-v] # flip the captured images around the horizontal axis\n"
" [-V] # use a video file, and not an image list, uses\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 ) int main( int argc, char** argv )
{ {
Size boardSize, imageSize; Size boardSize, imageSize;
float squareSize = 1.f, aspectRatio = 1.f; float squareSize, aspectRatio;
Mat cameraMatrix, distCoeffs; Mat cameraMatrix, distCoeffs;
const char* outputFilename = "out_camera_data.yml"; string outputFilename;
const char* inputFilename = 0; string inputFilename = "";
int i, nframes = 10; int i, nframes;
bool writeExtrinsics = false, writePoints = false; bool writeExtrinsics, writePoints;
bool undistortImage = false; bool undistortImage = false;
int flags = 0; int flags = 0;
VideoCapture capture; VideoCapture capture;
bool flipVertical = false; bool flipVertical;
bool showUndistorted = false; bool showUndistorted;
bool videofile = false; bool videofile;
int delay = 1000; int delay;
clock_t prevTimestamp = 0; clock_t prevTimestamp = 0;
int mode = DETECTION; int mode = DETECTION;
int cameraId = 0; int cameraId = 0;
@ -318,102 +318,70 @@ int main( int argc, char** argv )
vector<string> imageList; vector<string> imageList;
Pattern pattern = CHESSBOARD; 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(); help();
return 0; return 0;
} }
boardSize.width = parser.get<int>( "w" );
for( i = 1; i < argc; i++ ) boardSize.height = parser.get<int>( "h" );
if ( parser.has("pt") )
{ {
const char* s = argv[i]; string val = parser.get<string>("pt");
if( strcmp( s, "-w" ) == 0 ) if( val == "circles" )
{ pattern = CIRCLES_GRID;
if( sscanf( argv[++i], "%u", &boardSize.width ) != 1 || boardSize.width <= 0 ) else if( val == "acircles" )
return fprintf( stderr, "Invalid board width\n" ), -1; pattern = ASYMMETRIC_CIRCLES_GRID;
} else if( val == "chessboard" )
else if( strcmp( s, "-h" ) == 0 ) pattern = CHESSBOARD;
{
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;
}
else else
return fprintf( stderr, "Unknown option %s", s ), -1; return fprintf( stderr, "Invalid pattern type: must be chessboard or circles\n" ), -1;
} }
squareSize = parser.get<float>("s");
if( inputFilename ) nframes = parser.get<int>("n");
aspectRatio = parser.get<float>("a");
delay = parser.get<int>("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<string>("o");
showUndistorted = parser.has("su");
if ( isdigit(parser.get<string>("@input_data")[0]) )
cameraId = parser.get<int>("@input_data");
else
inputFilename = parser.get<string>("@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) ) if( !videofile && readStringList(inputFilename, imageList) )
mode = CAPTURING; mode = CAPTURING;

@ -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() static void help()
{ {
cout << "\nThis is a demo that shows mean-shift based tracking\n" 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" "This reads from video camera (0 by default, or the camera number the user enters\n"
"Usage: \n" "Usage: \n"
" ./camshiftdemo [camera number]\n"; " ./camshiftdemo [camera number]\n";
cout << hot_keys;
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";
} }
const char* 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 ) int main( int argc, const char** argv )
{ {
help();
VideoCapture cap; VideoCapture cap;
Rect trackWindow; Rect trackWindow;
int hsize = 16; int hsize = 16;
float hranges[] = {0,180}; float hranges[] = {0,180};
const float* phranges = hranges; const float* phranges = hranges;
CommandLineParser parser(argc, argv, keys); CommandLineParser parser(argc, argv, keys);
if (parser.has("help"))
{
help();
return 0;
}
int camNum = parser.get<int>(0); int camNum = parser.get<int>(0);
cap.open(camNum); cap.open(camNum);
if( !cap.isOpened() ) if( !cap.isOpened() )
@ -91,7 +95,7 @@ int main( int argc, const char** argv )
parser.printMessage(); parser.printMessage();
return -1; return -1;
} }
cout << hot_keys;
namedWindow( "Histogram", 0 ); namedWindow( "Histogram", 0 );
namedWindow( "CamShift Demo", 0 ); namedWindow( "CamShift Demo", 0 );
setMouseCallback( "CamShift Demo", onMouse, 0 ); setMouseCallback( "CamShift Demo", onMouse, 0 );

@ -43,13 +43,17 @@ static void help()
const char* keys = 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 ) int main( int argc, const char** argv )
{ {
help();
CommandLineParser parser(argc, argv, keys); CommandLineParser parser(argc, argv, keys);
if (parser.has("help"))
{
help();
return 0;
}
string inputImage = parser.get<string>(0); string inputImage = parser.get<string>(0);
img = imread(inputImage.c_str(), 0); img = imread(inputImage.c_str(), 0);

@ -33,14 +33,15 @@ static void on_trackbar(int, void*)
imshow("contours", cnt_img); imshow("contours", cnt_img);
} }
int main( int argc, char**) int main( int argc, char** argv)
{ {
Mat img = Mat::zeros(w, w, CV_8UC1); cv::CommandLineParser parser(argc, argv, "{help h||}");
if(argc > 1) if (parser.has("help"))
{ {
help(); help();
return -1; return 0;
} }
Mat img = Mat::zeros(w, w, CV_8UC1);
//Draw 6 faces //Draw 6 faces
for( int i = 0; i < 6; i++ ) for( int i = 0; i < 6; i++ )
{ {

@ -13,13 +13,17 @@ static void help()
<< "./convexhull\n" << endl; << "./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); Mat img(500, 500, CV_8UC3);
RNG& rng = theRNG(); RNG& rng = theRNG();
help();
for(;;) for(;;)
{ {
char key; char key;

@ -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); Mat I = Mat::eye(4, 4, CV_64F);
I.at<double>(1,1) = CV_PI; I.at<double>(1,1) = CV_PI;
cout << "I = \n" << I << ";" << endl << endl; cout << "I = \n" << I << ";" << endl << endl;

@ -123,14 +123,21 @@ void mouseHandler(int event, int x, int y, int, void*)
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
cv::CommandLineParser parser(argc, argv, "{help h | | show help message}{@input | | input image}");
if(argc != 2) if (parser.has("help"))
{
parser.printMessage();
return 0;
}
string input_image = parser.get<string>("@input");
if (input_image.empty())
{ {
cout << "usage: " << argv[0] << " <input_image>" << endl; parser.printMessage();
exit(1); 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; minx = INT_MAX; miny = INT_MAX; maxx = INT_MIN; maxy = INT_MIN;

@ -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); Scalar active_facet_color(0, 0, 255), delaunay_color(255,255,255);
Rect rect(0, 0, 600, 600); Rect rect(0, 0, 600, 600);

@ -64,14 +64,17 @@ static void help()
const char* keys = 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 ) int main( int argc, const char** argv )
{ {
help();
CommandLineParser parser(argc, argv, keys); CommandLineParser parser(argc, argv, keys);
if (parser.has("help"))
{
help();
return 0;
}
string inputImage = parser.get<string>(0); string inputImage = parser.get<string>(0);
// Load the source image. HighGUI use. // Load the source image. HighGUI use.

@ -69,19 +69,13 @@ int main(int argc, char *argv[])
{ {
vector<String> fileName; vector<String> fileName;
Mat img(600, 800, CV_8UC1); Mat img(600, 800, CV_8UC1);
if (argc == 1) cv::CommandLineParser parser(argc, argv, "{@input |../data/detect_blob.png| }{h help | | }");
{ if (parser.has("h"))
fileName.push_back("../data/detect_blob.png");
}
else if (argc == 2)
{
fileName.push_back(argv[1]);
}
else
{ {
help(); help();
return(0); return 0;
} }
fileName.push_back(parser.get<string>("@input"));
img = imread(fileName[0], IMREAD_COLOR); img = imread(fileName[0], IMREAD_COLOR);
if (img.rows*img.cols <= 0) if (img.rows*img.cols <= 0)
{ {

@ -402,11 +402,18 @@ int main(int argc, char *argv[])
vector<String> fileName; vector<String> fileName;
Mat imgOrig,img; Mat imgOrig,img;
Size blurSize(5,5); Size blurSize(5,5);
if (argc==2) cv::CommandLineParser parser(argc, argv, "{ help h | | }{ @input | | }");
if (parser.has("help"))
{ {
fileName.push_back(argv[1]); help();
imgOrig = imread(fileName[0], IMREAD_GRAYSCALE); blur(imgOrig, img, blurSize); return 0;
}
string input = parser.get<string>("@input");
if (!input.empty())
{
fileName.push_back(input);
imgOrig = imread(fileName[0], IMREAD_GRAYSCALE);
blur(imgOrig, img, blurSize);
} }
else else
{ {

@ -19,16 +19,20 @@ static void help()
const char* keys = 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) int main(int argc, const char ** argv)
{ {
help(); help();
CommandLineParser parser(argc, argv, keys); CommandLineParser parser(argc, argv, keys);
if (parser.has("help"))
{
help();
return 0;
}
string filename = parser.get<string>(0); string filename = parser.get<string>(0);
Mat img = imread(filename, IMREAD_GRAYSCALE);
Mat img = imread(filename.c_str(), IMREAD_GRAYSCALE);
if( img.empty() ) if( img.empty() )
{ {
help(); help();

@ -107,15 +107,17 @@ static void help()
const char* keys = 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 ) int main( int argc, const char** argv )
{ {
help();
CommandLineParser parser(argc, argv, keys); CommandLineParser parser(argc, argv, keys);
help();
if (parser.has("help"))
return 0;
string filename = parser.get<string>(0); string filename = parser.get<string>(0);
gray = imread(filename.c_str(), 0); gray = imread(filename, 0);
if(gray.empty()) if(gray.empty())
{ {
printf("Cannot read image file: %s\n", filename.c_str()); printf("Cannot read image file: %s\n", filename.c_str());

@ -16,9 +16,14 @@ static Scalar randomColor(RNG& rng)
return Scalar(icolor&255, (icolor>>8)&255, (icolor>>16)&255); 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"; char wndname[] = "Drawing Demo";
const int NUMBER = 100; const int NUMBER = 100;
const int DELAY = 5; const int DELAY = 5;

@ -33,14 +33,17 @@ static void help()
const char* keys = 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 ) int main( int argc, const char** argv )
{ {
help();
CommandLineParser parser(argc, argv, keys); CommandLineParser parser(argc, argv, keys);
if (parser.has("help"))
{
help();
return 0;
}
string filename = parser.get<string>(0); string filename = parser.get<string>(0);
image = imread(filename, 1); image = imread(filename, 1);

@ -27,73 +27,52 @@ void detectAndDraw( Mat& img, CascadeClassifier& cascade,
CascadeClassifier& nestedCascade, CascadeClassifier& nestedCascade,
double scale, bool tryflip ); double scale, bool tryflip );
string cascadeName = "../../data/haarcascades/haarcascade_frontalface_alt.xml"; string cascadeName;
string nestedCascadeName = "../../data/haarcascades/haarcascade_eye_tree_eyeglasses.xml"; string nestedCascadeName;
int main( int argc, const char** argv ) int main( int argc, const char** argv )
{ {
VideoCapture capture; VideoCapture capture;
Mat frame, image; 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; string inputName;
bool tryflip = false; bool tryflip;
help();
CascadeClassifier cascade, nestedCascade; CascadeClassifier cascade, nestedCascade;
double scale = 1; double scale;
for( int i = 1; i < argc; i++ ) 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; help();
if( cascadeOpt.compare( 0, cascadeOptLen, argv[i], cascadeOptLen ) == 0 ) return 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] );
} }
cascadeName = parser.get<string>("cascade");
nestedCascadeName = parser.get<string>("nested-cascade");
scale = parser.get<double>("scale");
if (scale < 1)
scale = 1;
tryflip = parser.has("try-flip");
inputName = parser.get<string>("@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 ) ) if( !cascade.load( cascadeName ) )
{ {
cerr << "ERROR: Could not load classifier cascade" << endl; cerr << "ERROR: Could not load classifier cascade" << endl;
help(); help();
return -1; return -1;
} }
if( inputName.empty() || (isdigit(inputName[0]) && inputName.size() == 1) )
if( inputName.empty() || (isdigit(inputName.c_str()[0]) && inputName.c_str()[1] == '\0') )
{ {
int c = inputName.empty() ? 0 : inputName.c_str()[0] - '0' ; int c = inputName.empty() ? 0 : inputName[0] - '0';
if(!capture.open(c)) if(!capture.open(c))
cout << "Capture from camera #" << c << " didn't work" << endl; cout << "Capture from camera #" << c << " didn't work" << endl;
} }

@ -18,11 +18,6 @@
using namespace std; using namespace std;
using namespace cv; using namespace cv;
// Functions to parse command-line arguments
static string getCommandOption(const vector<string>&, const string&);
static void setCommandOptions(vector<string>&, int, char**);
static bool doesCmdOptionExist(const vector<string>& , const string&);
// Functions for facial feature detection // Functions for facial feature detection
static void help(); static void help();
static void detectFaces(Mat&, vector<Rect_<int> >&, string); static void detectFaces(Mat&, vector<Rect_<int> >&, string);
@ -36,22 +31,23 @@ string face_cascade_path, eye_cascade_path, nose_cascade_path, mouth_cascade_pat
int main(int argc, char** argv) int main(int argc, char** argv)
{ {
if(argc < 3) cv::CommandLineParser parser(argc, argv,
"{eyes||}{nose||}{mouth||}{help h||}");
if (parser.has("help"))
{ {
help(); help();
return 0;
}
input_image_path = parser.get<string>(0);
face_cascade_path = parser.get<string>(1);
eye_cascade_path = parser.has("eyes") ? parser.get<string>("eyes") : "";
nose_cascade_path = parser.has("nose") ? parser.get<string>("nose") : "";
mouth_cascade_path = parser.has("mouth") ? parser.get<string>("mouth") : "";
if (input_image_path.empty() || face_cascade_path.empty())
{
cout << "IMAGE or FACE_CASCADE are not specified";
return 1; return 1;
} }
// Extract command-line options
vector<string> 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 // Load image and cascade classifier files
Mat image; Mat image;
image = imread(input_image_path); image = imread(input_image_path);
@ -67,30 +63,6 @@ int main(int argc, char** argv)
return 0; return 0;
} }
void setCommandOptions(vector<string>& args, int argc, char** argv)
{
for(int i = 1; i < argc; ++i)
{
args.push_back(argv[i]);
}
return;
}
string getCommandOption(const vector<string>& args, const string& opt)
{
string answer;
vector<string>::const_iterator it = find(args.begin(), args.end(), opt);
if(it != args.end() && (++it != args.end()))
answer = *it;
return answer;
}
bool doesCmdOptionExist(const vector<string>& args, const string& opt)
{
vector<string>::const_iterator it = find(args.begin(), args.end(), opt);
return (it != args.end());
}
static void help() static void help()
{ {
cout << "\nThis file demonstrates facial feature points detection using Haarcascade classifiers.\n" 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" "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 " "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" "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-eyes=<eyes_cascade> : Specify the haarcascade classifier for eye detection.\n"
"\t-nose : Specify the haarcascade classifier for nose detection.\n" "\t-nose=<nose_cascade> : Specify the haarcascade classifier for nose detection.\n"
"\t-mouth : Specify the haarcascade classifier for mouth detection.\n"; "\t-mouth=<mouth-cascade> : Specify the haarcascade classifier for mouth detection.\n";
cout << "EXAMPLE:\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" "\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" "\tThis will detect the face and nose in image.jpg.\n"
"(3) ./cpp-example-facial_features image.jpg face.xml\n" "(3) ./cpp-example-facial_features image.jpg face.xml\n"
"\tThis will detect only the face in image.jpg.\n"; "\tThis will detect only the face in image.jpg.\n";

@ -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); VideoCapture cap(0);
help(); help();
if( !cap.isOpened() ) if( !cap.isOpened() )

@ -73,12 +73,21 @@ static void onMouse( int event, int x, int y, int, void* )
int main( int argc, char** argv ) 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<string>("@image");
image0 = imread(filename, 1); image0 = imread(filename, 1);
if( image0.empty() ) if( image0.empty() )
{ {
cout << "Image empty. Usage: ffilldemo <image_name>\n"; cout << "Image empty\n";
parser.printMessage();
return 0; return 0;
} }
help(); help();

@ -70,14 +70,21 @@ static ostream& operator<<(ostream& out, const MyData& m){
} }
int main(int ac, char** av) 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<string>("@input");
if (filename.empty())
{ {
help(av); help(av);
return 1; return 1;
} }
string filename = av[1];
//write //write
{ {
FileStorage fs(filename, FileStorage::WRITE); FileStorage fs(filename, FileStorage::WRITE);

@ -21,14 +21,14 @@
using namespace cv; using namespace cv;
using namespace std; using namespace std;
// static void help() static void help()
// { {
// cout << cout <<
// "\nThis program is demonstration for ellipse fitting. The program finds\n" "\nThis program is demonstration for ellipse fitting. The program finds\n"
// "contours and approximate it by ellipses.\n" "contours and approximate it by ellipses.\n"
// "Call:\n" "Call:\n"
// "./fitellipse [image_name -- Default ../data/stuff.jpg]\n" << endl; "./fitellipse [image_name -- Default ../data/stuff.jpg]\n" << endl;
// } }
int sliderPos = 70; int sliderPos = 70;
@ -38,11 +38,19 @@ void processImage(int, void*);
int main( int argc, char** argv ) 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<string>("@image");
image = imread(filename, 0); image = imread(filename, 0);
if( image.empty() ) if( image.empty() )
{ {
cout << "Couldn't open image " << filename << "\nUsage: fitellipse <image_name>\n"; cout << "Couldn't open image " << filename << "\n";
return 0; return 0;
} }

@ -276,15 +276,16 @@ static void on_mouse( int event, int x, int y, int flags, void* param )
int main( int argc, char** argv ) int main( int argc, char** argv )
{ {
if( argc!=2 ) cv::CommandLineParser parser(argc, argv, "{help h||}{@input||}");
if (parser.has("help"))
{ {
help(); help();
return 1; return 0;
} }
string filename = argv[1]; string filename = parser.get<string>("@input");
if( filename.empty() ) if( filename.empty() )
{ {
cout << "\nDurn, couldn't read in " << argv[1] << endl; cout << "\nDurn, empty filename" << endl;
return 1; return 1;
} }
Mat image = imread( filename, 1 ); Mat image = imread( filename, 1 );

@ -16,8 +16,21 @@ static void help()
int main(int argc, char** argv) 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<string>("@image");
if (filename.empty())
{
help();
cout << "no image_name provided" << endl;
return -1;
}
Mat img = imread(filename, 0); Mat img = imread(filename, 0);
if(img.empty()) if(img.empty())
{ {

@ -16,8 +16,21 @@ static void help()
int main(int argc, char** argv) 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<string>("@image");
if (filename.empty())
{
help();
cout << "no image_name provided" << endl;
return -1;
}
Mat src = imread(filename, 0); Mat src = imread(filename, 0);
if(src.empty()) if(src.empty())
{ {

@ -27,14 +27,19 @@ static void help()
int main( int argc, char** argv ) int main( int argc, char** argv )
{ {
help(); cv::CommandLineParser parser(argc, argv, "{help h | |}{@image|../data/lena.jpg|}");
const char* imagename = argc > 1 ? argv[1] : "../data/lena.jpg"; if (parser.has("help"))
{
help();
return 0;
}
string imagename = parser.get<string>("@image");
#if DEMO_MIXED_API_USE #if DEMO_MIXED_API_USE
//! [iplimage] //! [iplimage]
Ptr<IplImage> iplimg(cvLoadImage(imagename)); // Ptr<T> is safe ref-counting pointer class Ptr<IplImage> iplimg(cvLoadImage(imagename.c_str())); // Ptr<T> is safe ref-counting pointer class
if(!iplimg) if(!iplimg)
{ {
fprintf(stderr, "Can not load image %s\n", imagename); fprintf(stderr, "Can not load image %s\n", imagename.c_str());
return -1; return -1;
} }
Mat img = cv::cvarrToMat(iplimg); // cv::Mat replaces the CvMat and IplImage, but it's easy to convert 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 Mat img = imread(imagename); // the newer cvLoadImage alternative, MATLAB-style function
if(img.empty()) 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; return -1;
} }
#endif #endif

@ -53,6 +53,7 @@ const std::string keys =
"{m motionType | affine | type of motion (translation, euclidean, affine, homography) }" "{m motionType | affine | type of motion (translation, euclidean, affine, homography) }"
"{v verbose | 0 | display initial and final images }" "{v verbose | 0 | display initial and final images }"
"{w warpedImfile | warpedECC.png | warped input image }" "{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); CommandLineParser parser(argc, argv, keys);
parser.about("ECC demo"); parser.about("ECC demo");
if (argc<2) { if (argc < 2) {
parser.printMessage();
help();
return 1;
}
if (parser.has("help"))
{
parser.printMessage(); parser.printMessage();
help(); help();
return 1; return 1;
} }
string imgFile = parser.get<string>(0); string imgFile = parser.get<string>(0);
string tempImgFile = parser.get<string>(1); string tempImgFile = parser.get<string>(1);
string inWarpFile = parser.get<string>(2); string inWarpFile = parser.get<string>(2);
@ -192,7 +198,11 @@ int main (const int argc, const char * argv[])
int verbose = parser.get<int>("v"); int verbose = parser.get<int>("v");
string finalWarp = parser.get<string>("o"); string finalWarp = parser.get<string>("o");
string warpedImFile = parser.get<string>("w"); string warpedImFile = parser.get<string>("w");
if (!parser.check())
{
parser.printErrors();
return -1;
}
if (!(warpType == "translation" || warpType == "euclidean" if (!(warpType == "translation" || warpType == "euclidean"
|| warpType == "affine" || warpType == "homography")) || warpType == "affine" || warpType == "homography"))
{ {

@ -18,13 +18,20 @@ static void help(char** argv)
int main(int argc, 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<string>("@image");
if(first_file.empty())
{ {
help(argv); help(argv);
return 1; return 1;
} }
string first_file = argv[1];
VideoCapture sequence(first_file); VideoCapture sequence(first_file);
if (!sequence.isOpened()) if (!sequence.isOpened())

@ -23,13 +23,19 @@ static void help(char** av)
int main(int ac, 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); help(av);
return 1; return 0;
} }
string outputname = parser.get<string>("@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! Mat m = imread(outputname); //check if the output is an image - prevent overwrites!
if(!m.empty()){ if(!m.empty()){

@ -47,7 +47,13 @@ static void onMouse( int event, int x, int y, int flags, void* )
int main( int argc, char** argv ) 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<string>("@image");
Mat img0 = imread(filename, -1); Mat img0 = imread(filename, -1);
if(img0.empty()) if(img0.empty())
{ {
@ -55,8 +61,6 @@ int main( int argc, char** argv )
return 0; return 0;
} }
help();
namedWindow( "image", 1 ); namedWindow( "image", 1 );
img = img0.clone(); img = img0.clone();

@ -9,14 +9,14 @@
using namespace cv; using namespace cv;
using namespace std; using namespace std;
static bool g_printStreamSetting = false; static bool g_printStreamSetting;
static int g_imageStreamProfileIdx = -1; static int g_imageStreamProfileIdx;
static int g_depthStreamProfileIdx = -1; static int g_depthStreamProfileIdx;
static bool g_irStreamShow = false; static bool g_irStreamShow;
static double g_imageBrightness = -DBL_MAX; static double g_imageBrightness;
static double g_imageContrast = -DBL_MAX; static double g_imageContrast;
static bool g_printTiming = false; static bool g_printTiming;
static bool g_showClosedPoint = false; static bool g_showClosedPoint;
static int g_closedDepthPoint[2]; static int g_closedDepthPoint[2];
@ -31,13 +31,13 @@ static void printUsage(const char *arg0)
filename++; filename++;
cout << "This program demonstrates usage of camera supported\nby Intel Perceptual computing SDK." << endl << endl; 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 << " -ps, print streams setting and profiles" << endl;
cout << " -isp IDX, set profile index of the image 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 << " -dsp=IDX, set profile index of the depth stream" << endl;
cout << " -ir, show data from IR stream" << endl; cout << " -ir, show data from IR stream" << endl;
cout << " -imb VAL, set brighness 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 << " -imc=VAL, set contrast value for a image stream" << endl;
cout << " -pts, print frame index and frame time" << endl; cout << " -pts, print frame index and frame time" << endl;
cout << " --show-closed, print frame index and frame time" << endl; cout << " --show-closed, print frame index and frame time" << endl;
cout << endl; cout << endl;
@ -45,62 +45,40 @@ static void printUsage(const char *arg0)
static void parseCMDLine(int argc, char* argv[]) 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]); printUsage(argv[0]);
exit(0);
} }
g_printStreamSetting = parser.has("ps");
g_imageStreamProfileIdx = parser.get<int>("isp");
g_depthStreamProfileIdx = parser.get<int>("dsp");
g_irStreamShow = parser.has("ir");
if (parser.has("imb"))
g_imageBrightness = parser.get<double>("imb");
else else
g_imageBrightness = -DBL_MAX;
if (parser.has("imc"))
g_imageContrast = parser.get<double>("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++ ) parser.printErrors();
{ exit(-1);
if ((0 == strcmp(argv[i], "--help")) || (0 == strcmp( argv[i], "-h"))) }
{ if (g_showClosedPoint && (-1 == g_depthStreamProfileIdx))
printUsage(argv[0]); {
exit(0); cerr << "For --show-closed depth profile has be selected" << endl;
} exit(-1);
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);
}
} }
} }

@ -15,7 +15,7 @@ static void help()
"\nThis program demonstrates Laplace point/edge detection using OpenCV function Laplacian()\n" "\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" "It captures from the camera of your choice: 0, 1, ... default 0\n"
"Call:\n" "Call:\n"
"./laplace [camera #, default 0]\n" << endl; "./laplace -c=<camera #, default 0> -p=<index of the frame to be decoded/captured next>\n" << endl;
} }
enum {GAUSSIAN, BLUR, MEDIAN}; enum {GAUSSIAN, BLUR, MEDIAN};
@ -26,25 +26,31 @@ int smoothType = GAUSSIAN;
int main( int argc, char** argv ) int main( int argc, char** argv )
{ {
VideoCapture cap; VideoCapture cap;
help(); cv::CommandLineParser parser(argc, argv, "{help h | | }{ c | 0 | }{ p | | }");
if ( parser.has("help") )
if( argc == 1 || (argc == 2 && strlen(argv[1]) == 1 && isdigit(argv[1][0]))) {
cap.open(argc == 2 ? argv[1][0] - '0' : 0); help();
else if( argc >= 2 ) return 0;
}
if( parser.get<string>("c").size() == 1 && isdigit(parser.get<string>("c")[0]) )
cap.open(parser.get<int>("c"));
else
cap.open(parser.get<string>("c"));
if( cap.isOpened() )
cout << "Video " << parser.get<string>("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]); int pos = parser.get<int>("p");
if( cap.isOpened() ) if (!parser.check())
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.printErrors();
sscanf(argv[2], "%d", &pos); return -1;
cout << "seeking to frame #" << pos << endl;
cap.set(CAP_PROP_POS_FRAMES, pos);
} }
cout << "seeking to frame #" << pos << endl;
cap.set(CAP_PROP_POS_FRAMES, pos);
} }
if( !cap.isOpened() ) if( !cap.isOpened() )

@ -28,9 +28,9 @@ static void help()
"and the remaining 4000 (10000 for boosting) - to test the classifier.\n" "and the remaining 4000 (10000 for boosting) - to test the classifier.\n"
"======================================================\n"); "======================================================\n");
printf("\nThis is letter recognition sample.\n" printf("\nThis is letter recognition sample.\n"
"The usage: letter_recog [-data <path to letter-recognition.data>] \\\n" "The usage: letter_recog [-data=<path to letter-recognition.data>] \\\n"
" [-save <output XML file for the classifier>] \\\n" " [-save=<output XML file for the classifier>] \\\n"
" [-load <XML file with the pre-trained classifier>] \\\n" " [-load=<XML file with the pre-trained classifier>] \\\n"
" [-boost|-mlp|-knearest|-nbayes|-svm] # to use boost/mlp/knearest/SVM classifier instead of default Random Trees\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_save = "";
string filename_to_load = ""; string filename_to_load = "";
string data_filename = "../data/letter-recognition.data"; string data_filename;
int method = 0; int method = 0;
int i; cv::CommandLineParser parser(argc, argv, "{data|../data/letter-recognition.data|}{save||}{load||}{boost||}"
for( i = 1; i < argc; i++ ) "{mlp||}{knn knearest||}{nbayes||}{svm||}{help h||}");
data_filename = parser.get<string>("data");
if (parser.has("save"))
filename_to_save = parser.get<string>("save");
if (parser.has("load"))
filename_to_load = parser.get<string>("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" help();
{ return 0;
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;
} }
if( (method == 0 ?
if( i < argc ||
(method == 0 ?
build_rtrees_classifier( data_filename, filename_to_save, filename_to_load ) : build_rtrees_classifier( data_filename, filename_to_save, filename_to_load ) :
method == 1 ? method == 1 ?
build_boost_classifier( data_filename, filename_to_save, filename_to_load ) : build_boost_classifier( data_filename, filename_to_save, filename_to_load ) :

@ -37,8 +37,6 @@ static void onMouse( int event, int x, int y, int /*flags*/, void* /*param*/ )
int main( int argc, char** argv ) int main( int argc, char** argv )
{ {
help();
VideoCapture cap; VideoCapture cap;
TermCriteria termcrit(TermCriteria::COUNT|TermCriteria::EPS,20,0.03); TermCriteria termcrit(TermCriteria::COUNT|TermCriteria::EPS,20,0.03);
Size subPixWinSize(10,10), winSize(31,31); Size subPixWinSize(10,10), winSize(31,31);
@ -47,10 +45,19 @@ int main( int argc, char** argv )
bool needToInit = false; bool needToInit = false;
bool nightMode = false; bool nightMode = false;
if( argc == 1 || (argc == 2 && strlen(argv[1]) == 1 && isdigit(argv[1][0]))) cv::CommandLineParser parser(argc, argv, "{@input||}{help h||}");
cap.open(argc == 2 ? argv[1][0] - '0' : 0); string input = parser.get<string>("@input");
else if( argc == 2 ) if (parser.has("help"))
cap.open(argv[1]); {
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() ) if( !cap.isOpened() )
{ {

@ -13,15 +13,13 @@ using namespace cv;
int main(int argc, char** argv) int main(int argc, char** argv)
{ {
std::string in; 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; parser.printMessage();
in = "../data/building.jpg"; return 0;
}
else
{
in = argv[1];
} }
in = parser.get<string>("@input");
Mat image = imread(in, IMREAD_GRAYSCALE); Mat image = imread(in, IMREAD_GRAYSCALE);

@ -13,16 +13,25 @@ static void help()
{ {
cout << "\nThis program demonstrates template match with mask.\n" cout << "\nThis program demonstrates template match with mask.\n"
"Usage:\n" "Usage:\n"
"./mask_tmpl <image_name> <template_name> <mask_name>, Default is ../data/lena_tmpl.jpg\n" "./mask_tmpl -i=<image_name> -t=<template_name> -m=<mask_name>, Default is ../data/lena_tmpl.jpg\n"
<< endl; << endl;
} }
int main( int argc, const char** argv ) int main( int argc, const char** argv )
{ {
const char* filename = argc == 4 ? argv[1] : "../data/lena_tmpl.jpg"; cv::CommandLineParser parser(argc, argv,
const char* tmplname = argc == 4 ? argv[2] : "../data/tmpl.png"; "{help h||}"
const char* maskname = argc == 4 ? argv[3] : "../data/mask.png"; "{ i | ../data/lena_tmpl.jpg | }"
"{ t | ../data/tmpl.png | }"
"{ m | ../data/mask.png | }");
if (parser.has("help"))
{
help();
return 0;
}
string filename = parser.get<string>("i");
string tmplname = parser.get<string>("t");
string maskname = parser.get<string>("m");
Mat img = imread(filename); Mat img = imread(filename);
Mat tmpl = imread(tmplname); Mat tmpl = imread(tmplname);
Mat mask = imread(maskname); Mat mask = imread(maskname);

@ -9,7 +9,7 @@ static void help()
{ {
cout << "\n This program demonstrates how to detect compute and match ORB BRISK and AKAZE descriptors \n" cout << "\n This program demonstrates how to detect compute and match ORB BRISK and AKAZE descriptors \n"
"Usage: \n" "Usage: \n"
" ./matchmethod_orb_akaze_brisk <image1(../data/basketball1.png as default)> <image2(../data/basketball2.png as default)>\n" " ./matchmethod_orb_akaze_brisk --image1=<image1(../data/basketball1.png as default)> --image2=<image2(../data/basketball2.png as default)>\n"
"Press a key when image window is active to change algorithm or descriptor"; "Press a key when image window is active to change algorithm or descriptor";
} }
@ -20,7 +20,6 @@ int main(int argc, char *argv[])
vector<String> typeDesc; vector<String> typeDesc;
vector<String> typeAlgoMatch; vector<String> typeAlgoMatch;
vector<String> fileName; vector<String> fileName;
help();
// This descriptor are going to be detect and compute // 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-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 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-L1");
typeAlgoMatch.push_back("BruteForce-Hamming"); typeAlgoMatch.push_back("BruteForce-Hamming");
typeAlgoMatch.push_back("BruteForce-Hamming(2)"); typeAlgoMatch.push_back("BruteForce-Hamming(2)");
if (argc==1) cv::CommandLineParser parser(argc, argv,
{ "{ @image1 | ../data/basketball1.png | }"
fileName.push_back("../data/basketball1.png"); "{ @image2 | ../data/basketball2.png | }"
fileName.push_back("../data/basketball2.png"); "{help h ||}");
} if (parser.has("help"))
else if (argc==3)
{
fileName.push_back(argv[1]);
fileName.push_back(argv[2]);
}
else
{ {
help(); help();
return(0); return 0;
} }
fileName.push_back(parser.get<string>(0));
fileName.push_back(parser.get<string>(1));
Mat img1 = imread(fileName[0], IMREAD_GRAYSCALE); Mat img1 = imread(fileName[0], IMREAD_GRAYSCALE);
Mat img2 = imread(fileName[1], IMREAD_GRAYSCALE); Mat img2 = imread(fileName[1], IMREAD_GRAYSCALE);
if (img1.rows*img1.cols <= 0) if (img1.rows*img1.cols <= 0)

@ -3,6 +3,7 @@
#include "opencv2/highgui/highgui.hpp" #include "opencv2/highgui/highgui.hpp"
#include <stdlib.h> #include <stdlib.h>
#include <stdio.h> #include <stdio.h>
#include <string>
using namespace cv; using namespace cv;
@ -58,11 +59,18 @@ static void ErodeDilate(int, void*)
int main( int argc, char** argv ) 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<std::string>("@image");
if( (src = imread(filename,1)).empty() ) if( (src = imread(filename,1)).empty() )
{
help();
return -1; return -1;
}
help();
//create windows for output images //create windows for output images
namedWindow("Open/Close",1); namedWindow("Open/Close",1);

@ -28,15 +28,21 @@ using namespace cv;
int main(int argc, char* argv[]) 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] << " <Input image> " << endl; parser.printMessage();
exit(0);
}
if (parser.get<string>("@image").empty())
{
parser.printMessage();
exit(0); exit(0);
} }
int num,type; Mat I = imread(parser.get<string>("@image"));
Mat I = imread(argv[1]); int num,type;
if(I.empty()) if(I.empty())
{ {

@ -87,90 +87,49 @@ static float getMaxDisparity( VideoCapture& capture )
static void printCommandLineParams() static void printCommandLineParams()
{ {
cout << "-cd Colorized disparity? (0 or 1; 1 by default) Ignored if disparity map is not selected to show." << 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 << "-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 << "-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 << " 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 << " 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 << " 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 << "-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[], static void parseCommandLine( int argc, char* argv[], bool& isColorizeDisp, bool& isFixedMaxDisp, int& imageMode, bool retrievedImageFlags[],
string& filename, bool& isFileReading ) 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(); filename.clear();
isFileReading = false; cv::CommandLineParser parser(argc, argv, "{h help||}{cd|1|}{fmd|0|}{mode|0|}{m|01010|}{r||}");
if (parser.has("h"))
if( argc == 1 )
{ {
help(); help();
printCommandLineParams();
exit(0);
} }
else isColorizeDisp = (parser.get<int>("cd") != 0);
isFixedMaxDisp = (parser.get<int>("fmd") != 0);
imageMode = parser.get<int>("mode");
int flags = parser.get<int>("m");
isFileReading = parser.has("r");
if (isFileReading)
filename = parser.get<string>("r");
if (!parser.check())
{ {
for( int i = 1; i < argc; i++ ) parser.printErrors();
{ help();
if( !strcmp( argv[i], "--help" ) || !strcmp( argv[i], "-h" ) ) exit(-1);
{ }
printCommandLineParams(); if (flags % 100000 == 0)
exit(0); {
} cout << "No one output image is selected." << endl;
else if( !strcmp( argv[i], "-cd" ) ) exit(0);
{ }
isColorizeDisp = atoi(argv[++i]) == 0 ? false : true; for (int i = 0; i < 5; i++)
} {
else if( !strcmp( argv[i], "-fmd" ) ) retrievedImageFlags[4 - i] = (flags % 10 != 0);
{ flags /= 10;
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);
}
}
} }
} }

@ -121,13 +121,19 @@ static void onTrackbar(int pos, void* ptr)
// Main // Main
int main(int argc, char** argv) int main(int argc, char** argv)
{ {
if (argc != 2) { cv::CommandLineParser parser(argc, argv, "{@input||image list}{help h||show help message}");
cout << "usage: " << argv[0] << " <image_list.txt>" << endl; if (parser.has("help"))
exit(1); {
parser.printMessage();
exit(0);
} }
// Get the path to your CSV. // Get the path to your CSV.
string imgList = string(argv[1]); string imgList = parser.get<string>("@input");
if (imgList.empty())
{
parser.printMessage();
exit(1);
}
// vector to hold the images // vector to hold the images
vector<Mat> images; vector<Mat> images;

@ -1,6 +1,7 @@
#include "opencv2/imgproc/imgproc_c.h" #include "opencv2/imgproc/imgproc_c.h"
#include "opencv2/videoio/videoio_c.h" #include "opencv2/videoio/videoio_c.h"
#include "opencv2/highgui/highgui_c.h" #include "opencv2/highgui/highgui_c.h"
#include "opencv2/core/utility.hpp"
#include <ctype.h> #include <ctype.h>
#include <stdio.h> #include <stdio.h>
@ -20,15 +21,22 @@ int main( int argc, char** argv )
IplImage* recovered_img = 0; IplImage* recovered_img = 0;
help(); help();
cv::CommandLineParser parser(argc, argv, "{help h||}{@input|0|}");
if( argc == 1 || (argc == 2 && strlen(argv[1]) == 1 && isdigit(argv[1][0]))) if (parser.has("help"))
capture = cvCaptureFromCAM( argc == 2 ? argv[1][0] - '0' : 0 ); {
else if( argc == 2 ) help();
capture = cvCaptureFromAVI( argv[1] ); return 0;
}
std::string arg = parser.get<std::string>("@input");
if( arg.size() == 1 && isdigit(arg[0]) )
capture = cvCaptureFromCAM( arg[0] - '0' );
else
capture = cvCaptureFromAVI( arg.c_str() );
if( !capture ) if( !capture )
{ {
const char* name = argv[0];
fprintf(stderr,"Could not initialize capturing...\n"); fprintf(stderr,"Could not initialize capturing...\n");
fprintf(stderr,"Usage: %s <CAMERA_NUMBER> , or \n %s <VIDEO_FILE>\n",argv[0],argv[0]); fprintf(stderr,"Usage: %s <CAMERA_NUMBER> , or \n %s <VIDEO_FILE>\n", name, name);
help(); help();
return -1; return -1;
} }

@ -63,12 +63,17 @@ int main(int argc, char** argv)
VideoCapture cap; VideoCapture cap;
bool update_bg_model = true; bool update_bg_model = true;
help(); CommandLineParser parser(argc, argv, "{help h||}{@input||}");
if (parser.has("help"))
if( argc < 2 ) {
help();
return 0;
}
string input = parser.get<std::string>("@input");
if (input.empty())
cap.open(0); cap.open(0);
else else
cap.open(std::string(argv[1])); cap.open(input);
if( !cap.isOpened() ) if( !cap.isOpened() )
{ {

@ -30,14 +30,14 @@ const char* helphelp =
"compute the homography of the plane the calibration pattern is on. It also shows grabCut\n" "compute the homography of the plane the calibration pattern is on. It also shows grabCut\n"
"segmentation etc.\n" "segmentation etc.\n"
"\n" "\n"
"select3dobj -w <board_width> -h <board_height> [-s <square_size>]\n" "select3dobj -w=<board_width> -h=<board_height> [-s=<square_size>]\n"
" -i <camera_intrinsics_filename> -o <output_prefix> [video_filename/cameraId]\n" " -i=<camera_intrinsics_filename> -o=<output_prefix>\n"
"\n" "\n"
" -w <board_width> Number of chessboard corners wide\n" " -w=<board_width> Number of chessboard corners wide\n"
" -h <board_height> Number of chessboard corners width\n" " -h=<board_height> Number of chessboard corners width\n"
" [-s <square_size>] Optional measure of chessboard squares in meters\n" " [-s=<square_size>] Optional measure of chessboard squares in meters\n"
" -i <camera_intrinsics_filename> Camera matrix .yml file from calibration.cpp\n" " -i=<camera_intrinsics_filename> Camera matrix .yml file from calibration.cpp\n"
" -o <output_prefix> Prefix the output segmentation images with this\n" " -o=<output_prefix> Prefix the output segmentation images with this\n"
" [video_filename/cameraId] If present, read from that video file or that ID\n" " [video_filename/cameraId] If present, read from that video file or that ID\n"
"\n" "\n"
"Using a camera's intrinsics (from calibrating a camera -- see calibration.cpp) and an\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<string>& l )
int main(int argc, char** argv) int main(int argc, char** argv)
{ {
const char* help = "Usage: select3dobj -w <board_width> -h <board_height> [-s <square_size>]\n" const char* help = "Usage: select3dobj -w=<board_width> -h=<board_height> [-s=<square_size>]\n"
"\t-i <intrinsics_filename> -o <output_prefix> [video_filename/cameraId]\n"; "\t-i=<intrinsics_filename> -o=<output_prefix> [video_filename/cameraId]\n";
const char* screen_help = const char* screen_help =
"Actions: \n" "Actions: \n"
"\tSelect object as 3D box with the mouse. That's it\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" "\tENTER - Confirm the selection. Grab next object in video mode.\n"
"\tq - Exit the program\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(helphelp);
puts(help); puts(help);
return 0; return 0;
} }
const char* intrinsicsFilename = 0; string intrinsicsFilename;
const char* outprefix = 0; string outprefix = "";
const char* inputName = 0; string inputName = "";
int cameraId = 0; int cameraId = 0;
Size boardSize; Size boardSize;
double squareSize = 1; double squareSize;
vector<string> imageList; vector<string> imageList;
intrinsicsFilename = parser.get<string>("i");
for( int i = 1; i < argc; i++ ) outprefix = parser.get<string>("o");
boardSize.width = parser.get<int>("w");
boardSize.height = parser.get<int>("h");
squareSize = parser.get<double>("s");
if ( parser.get<string>("@input").size() == 1 && isdigit(parser.get<string>("@input")[0]) )
cameraId = parser.get<int>("@input");
else
inputName = parser.get<string>("@input");
if (!parser.check())
{ {
if( strcmp(argv[i], "-i") == 0 ) puts(help);
intrinsicsFilename = argv[++i]; parser.printErrors();
else if( strcmp(argv[i], "-o") == 0 ) return 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;
}
} }
if ( boardSize.width <= 0 )
if( !intrinsicsFilename || !outprefix ||
boardSize.width <= 0 || boardSize.height <= 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); puts(help);
return 0; return 0;
} }
Mat cameraMatrix, distCoeffs; Mat cameraMatrix, distCoeffs;
Size calibratedImageSize; Size calibratedImageSize;
readCameraMatrix(intrinsicsFilename, cameraMatrix, distCoeffs, calibratedImageSize ); readCameraMatrix(intrinsicsFilename, cameraMatrix, distCoeffs, calibratedImageSize );
VideoCapture capture; VideoCapture capture;
if( inputName ) if( !inputName.empty() )
{ {
if( !readStringList(inputName, imageList) && if( !readStringList(inputName, imageList) &&
!capture.open(inputName)) !capture.open(inputName))
@ -486,21 +463,21 @@ int main(int argc, char** argv)
const char* outbarename = 0; const char* outbarename = 0;
{ {
outbarename = strrchr(outprefix, '/'); outbarename = strrchr(outprefix.c_str(), '/');
const char* tmp = strrchr(outprefix, '\\'); const char* tmp = strrchr(outprefix.c_str(), '\\');
char cmd[1000]; char cmd[1000];
sprintf(cmd, "mkdir %s", outprefix); sprintf(cmd, "mkdir %s", outprefix.c_str());
if( tmp && tmp > outbarename ) if( tmp && tmp > outbarename )
outbarename = tmp; outbarename = tmp;
if( outbarename ) if( outbarename )
{ {
cmd[6 + outbarename - outprefix] = '\0'; cmd[6 + outbarename - outprefix.c_str()] = '\0';
int result = system(cmd); int result = system(cmd);
CV_Assert(result == 0); CV_Assert(result == 0);
outbarename++; outbarename++;
} }
else else
outbarename = outprefix; outbarename = outprefix.c_str();
} }
Mat frame, shownFrame, selectedObjFrame, mapxy; Mat frame, shownFrame, selectedObjFrame, mapxy;
@ -510,7 +487,7 @@ int main(int argc, char** argv)
setMouseCallback("View", onMouse, 0); setMouseCallback("View", onMouse, 0);
bool boardFound = false; bool boardFound = false;
string indexFilename = format("%s_index.yml", outprefix); string indexFilename = format("%s_index.yml", outprefix.c_str());
vector<string> capturedImgList; vector<string> capturedImgList;
vector<Rect> roiList; vector<Rect> roiList;
@ -588,7 +565,7 @@ int main(int argc, char** argv)
char path[1000]; char path[1000];
for(;frameIdx < maxFrameIdx;frameIdx++) 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"); FILE* f = fopen(path, "rb");
if( !f ) if( !f )
break; break;
@ -596,7 +573,7 @@ int main(int argc, char** argv)
} }
if( frameIdx == maxFrameIdx ) 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; break;
} }
imwrite(path, selectedObjFrame(r)); imwrite(path, selectedObjFrame(r));

@ -19,7 +19,7 @@ static void help()
"This program demonstrates a method for shape comparisson based on Shape Context\n" "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" "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" "Call\n"
"./shape_example [number between 1 and 20]\n\n"); "./shape_example [number between 1 and 20, 1 default]\n\n");
} }
static vector<Point> simpleContour( const Mat& currentQuery, int n=300 ) static vector<Point> simpleContour( const Mat& currentQuery, int n=300 )
@ -54,16 +54,24 @@ static vector<Point> simpleContour( const Mat& currentQuery, int n=300 )
int main(int argc, char** argv) int main(int argc, char** argv)
{ {
help();
string path = "../data/shape_sample/"; string path = "../data/shape_sample/";
int indexQuery = 1; cv::CommandLineParser parser(argc, argv, "{help h||}{@input|1|}");
if( argc < 2 ) if (parser.has("help"))
{ {
std::cout<<"Using first image as query."<<std::endl; help();
return 0;
} }
else int indexQuery = parser.get<int>("@input");
if (!parser.check())
{ {
sscanf( argv[1], "%i", &indexQuery ); parser.printErrors();
help();
return 1;
}
if (indexQuery < 1 || indexQuery > 20)
{
help();
return 1;
} }
cv::Ptr <cv::ShapeContextDistanceExtractor> mysc = cv::createShapeContextDistanceExtractor(); cv::Ptr <cv::ShapeContextDistanceExtractor> mysc = cv::createShapeContextDistanceExtractor();

@ -25,61 +25,42 @@ void detectAndDraw( Mat& img, CascadeClassifier& cascade,
CascadeClassifier& nestedCascade, CascadeClassifier& nestedCascade,
double scale, bool tryflip ); double scale, bool tryflip );
string cascadeName = "../../data/haarcascades/haarcascade_frontalface_alt.xml"; string cascadeName;
string nestedCascadeName = "../../data/haarcascades/haarcascade_smile.xml"; string nestedCascadeName;
int main( int argc, const char** argv ) int main( int argc, const char** argv )
{ {
VideoCapture capture; VideoCapture capture;
Mat frame, image; 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; string inputName;
bool tryflip = false; bool tryflip;
help(); help();
CascadeClassifier cascade, nestedCascade; CascadeClassifier cascade, nestedCascade;
double scale = 1; double scale;
cv::CommandLineParser parser(argc, argv,
for( int i = 1; i < argc; i++ ) "{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; help();
if( cascadeOpt.compare( 0, cascadeOptLen, argv[i], cascadeOptLen ) == 0 ) return 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] );
} }
cascadeName = parser.get<string>("cascade");
nestedCascadeName = parser.get<string>("smile-cascade");
tryflip = parser.has("try-flip");
inputName = parser.get<string>("@input");
scale = parser.get<int>("scale");
if (!parser.check())
{
help();
return 1;
}
if (scale < 1)
scale = 1;
if( !cascade.load( cascadeName ) ) if( !cascade.load( cascadeName ) )
{ {
cerr << "ERROR: Could not load face cascade" << endl; cerr << "ERROR: Could not load face cascade" << endl;
@ -92,10 +73,9 @@ int main( int argc, const char** argv )
help(); help();
return -1; return -1;
} }
if( inputName.empty() || (isdigit(inputName[0]) && inputName.size() == 1) )
if( inputName.empty() || (isdigit(inputName.c_str()[0]) && inputName.c_str()[1] == '\0') )
{ {
int c = inputName.empty() ? 0 : inputName.c_str()[0] - '0' ; int c = inputName.empty() ? 0 : inputName[0] - '0' ;
if(!capture.open(c)) if(!capture.open(c))
cout << "Capture from camera #" << c << " didn't work" << endl; cout << "Capture from camera #" << c << " didn't work" << endl;
} }

@ -62,13 +62,18 @@ int process(vector<string> images)
int main(int ac, char** av) int main(int ac, char** av)
{ {
cv::CommandLineParser parser(ac, av, "{help h||}{@input||}");
if (ac != 2) if (parser.has("help"))
{
help(av);
return 0;
}
std::string arg = parser.get<std::string>("@input");
if (arg.empty())
{ {
help(av); help(av);
return 1; return 1;
} }
std::string arg = av[1];
vector<string> imagelist; vector<string> imagelist;
if (!readStringList(arg,imagelist)) if (!readStringList(arg,imagelist))

@ -71,12 +71,17 @@ namespace {
} }
int main(int ac, char** av) { int main(int ac, char** av) {
cv::CommandLineParser parser(ac, av, "{help h||}{@input||}");
if (ac != 2) { if (parser.has("help"))
{
help(av);
return 0;
}
std::string arg = parser.get<std::string>("@input");
if (arg.empty()) {
help(av); help(av);
return 1; 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 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 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())); capture.open(atoi(arg.c_str()));

@ -50,7 +50,7 @@ static int print_help()
" matrix separately) stereo. \n" " matrix separately) stereo. \n"
" Calibrate the cameras and display the\n" " Calibrate the cameras and display the\n"
" rectified results along with the computed disparity images. \n" << endl; " 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*/] <image list XML/YML file>\n" << endl; cout << "Usage:\n ./stereo_calib -w=<board_width default=9> -h=<board_height default=6> <image list XML/YML file default=../data/stereo_calib.xml>\n" << endl;
return 0; return 0;
} }
@ -347,50 +347,19 @@ int main(int argc, char** argv)
{ {
Size boardSize; Size boardSize;
string imagelistfn; string imagelistfn;
bool showRectified = true; bool showRectified;
cv::CommandLineParser parser(argc, argv, "{w|9|}{h|6|}{nr||}{help||}{@input|../data/stereo_calib.xml|}");
for( int i = 1; i < argc; i++ ) if (parser.has("help"))
{ return print_help();
if( string(argv[i]) == "-w" ) showRectified = !parser.has("nr");
{ imagelistfn = parser.get<string>("@input");
if( sscanf(argv[++i], "%d", &boardSize.width) != 1 || boardSize.width <= 0 ) boardSize.width = parser.get<int>("w");
{ boardSize.height = parser.get<int>("h");
cout << "invalid board width" << endl; if (!parser.check())
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 )
{ {
cout << "if you specified XML file with chessboards, you should also specify the board width and height (-w and -h options)" << endl; parser.printErrors();
return 0; return 1;
} }
vector<string> imagelist; vector<string> imagelist;
bool ok = readStringList(imagelistfn, imagelist); bool ok = readStringList(imagelistfn, imagelist);
if(!ok || imagelist.empty()) if(!ok || imagelist.empty())

@ -21,8 +21,8 @@ static void print_help()
{ {
printf("\nDemo stereo matching converting L and R images into disparity and point clouds\n"); printf("\nDemo stereo matching converting L and R images into disparity and point clouds\n");
printf("\nUsage: stereo_match <left_image> <right_image> [--algorithm=bm|sgbm|hh|sgbm3way] [--blocksize=<block_size>]\n" printf("\nUsage: stereo_match <left_image> <right_image> [--algorithm=bm|sgbm|hh|sgbm3way] [--blocksize=<block_size>]\n"
"[--max-disparity=<max_disparity>] [--scale=scale_factor>] [-i <intrinsic_filename>] [-e <extrinsic_filename>]\n" "[--max-disparity=<max_disparity>] [--scale=scale_factor>] [-i=<intrinsic_filename>] [-e=<extrinsic_filename>]\n"
"[--no-display] [-o <disparity_image>] [-p <point_cloud_file>]\n"); "[--no-display] [-o=<disparity_image>] [-p=<point_cloud_file>]\n");
} }
static void saveXYZ(const char* filename, const Mat& mat) 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) int main(int argc, char** argv)
{ {
const char* algorithm_opt = "--algorithm="; std::string img1_filename = "";
const char* maxdisp_opt = "--max-disparity="; std::string img2_filename = "";
const char* blocksize_opt = "--blocksize="; std::string intrinsic_filename = "";
const char* nodisplay_opt = "--no-display"; std::string extrinsic_filename = "";
const char* scale_opt = "--scale="; std::string disparity_filename = "";
std::string point_cloud_filename = "";
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;
enum { STEREO_BM=0, STEREO_SGBM=1, STEREO_HH=2, STEREO_VAR=3, STEREO_3WAY=4 }; enum { STEREO_BM=0, STEREO_SGBM=1, STEREO_HH=2, STEREO_VAR=3, STEREO_3WAY=4 };
int alg = STEREO_SGBM; int alg = STEREO_SGBM;
int SADWindowSize = 0, numberOfDisparities = 0; int SADWindowSize, numberOfDisparities;
bool no_display = false; bool no_display;
float scale = 1.f; float scale;
Ptr<StereoBM> bm = StereoBM::create(16,9); Ptr<StereoBM> bm = StereoBM::create(16,9);
Ptr<StereoSGBM> sgbm = StereoSGBM::create(0,16,3); Ptr<StereoSGBM> sgbm = StereoSGBM::create(0,16,3);
cv::CommandLineParser parser(argc, argv,
for( int i = 1; i < argc; i++ ) "{help h||}{algorithm||}{max-disparity|0|}{blocksize|0|}{no-display||}{scale|1|}{i||}{e||}{o||}{p||}");
if(parser.has("help"))
{ {
if( argv[i][0] != '-' ) print_help();
{ return 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;
}
} }
img1_filename = parser.get<std::string>(0);
if( !img1_filename || !img2_filename ) img2_filename = parser.get<std::string>(1);
if (parser.has("algorithm"))
{
std::string _alg = parser.get<std::string>("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<int>("max-disparity");
SADWindowSize = parser.get<int>("blocksize");
scale = parser.get<float>("scale");
no_display = parser.has("no-display");
if( parser.has("i") )
intrinsic_filename = parser.get<std::string>("i");
if( parser.has("e") )
extrinsic_filename = parser.get<std::string>("e");
if( parser.has("o") )
disparity_filename = parser.get<std::string>("o");
if( parser.has("p") )
point_cloud_filename = parser.get<std::string>("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"); printf("Command-line parameter error: both left and right images must be specified\n");
return -1; return -1;
} }
if( (!intrinsic_filename.empty()) ^ (!extrinsic_filename.empty()) )
if( (intrinsic_filename != 0) ^ (extrinsic_filename != 0) )
{ {
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"); 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; 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"); printf("Command-line parameter error: extrinsic and intrinsic parameters must be specified to compute the point cloud\n");
return -1; return -1;
@ -186,13 +162,13 @@ int main(int argc, char** argv)
Rect roi1, roi2; Rect roi1, roi2;
Mat Q; Mat Q;
if( intrinsic_filename ) if( !intrinsic_filename.empty() )
{ {
// reading intrinsic parameters // reading intrinsic parameters
FileStorage fs(intrinsic_filename, FileStorage::READ); FileStorage fs(intrinsic_filename, FileStorage::READ);
if(!fs.isOpened()) 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; return -1;
} }
@ -208,7 +184,7 @@ int main(int argc, char** argv)
fs.open(extrinsic_filename, FileStorage::READ); fs.open(extrinsic_filename, FileStorage::READ);
if(!fs.isOpened()) 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; return -1;
} }
@ -297,16 +273,16 @@ int main(int argc, char** argv)
printf("\n"); printf("\n");
} }
if(disparity_filename) if(!disparity_filename.empty())
imwrite(disparity_filename, disp8); imwrite(disparity_filename, disp8);
if(point_cloud_filename) if(!point_cloud_filename.empty())
{ {
printf("storing the point cloud..."); printf("storing the point cloud...");
fflush(stdout); fflush(stdout);
Mat xyz; Mat xyz;
reprojectImageTo3D(disp, xyz, Q, true); reprojectImageTo3D(disp, xyz, Q, true);
saveXYZ(point_cloud_filename, xyz); saveXYZ(point_cloud_filename.c_str(), xyz);
printf("\n"); printf("\n");
} }

@ -88,7 +88,7 @@ void load_images( const string & prefix, const string & filename, vector< Mat >
while( !end_of_parsing ) while( !end_of_parsing )
{ {
getline( file, line ); getline( file, line );
if( line == "" ) // no more file to read if( line.empty() ) // no more file to read
{ {
end_of_parsing = true; end_of_parsing = true;
break; break;
@ -403,23 +403,33 @@ void test_it( const Size & size )
int main( int argc, char** argv ) 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 parser.printMessage();
<< "Usage: " << argv[0] << " pos_dir pos.lst neg_dir neg.lst" << endl exit(0);
<< "example: " << argv[0] << " /INRIA_dataset/ Train/pos.lst /INRIA_dataset/ Train/neg.lst" << endl;
exit( -1 );
} }
vector< Mat > pos_lst; vector< Mat > pos_lst;
vector< Mat > full_neg_lst; vector< Mat > full_neg_lst;
vector< Mat > neg_lst; vector< Mat > neg_lst;
vector< Mat > gradient_lst; vector< Mat > gradient_lst;
vector< int > labels; vector< int > labels;
string pos_dir = parser.get<string>("pd");
load_images( argv[1], argv[2], pos_lst ); string pos = parser.get<string>("p");
string neg_dir = parser.get<string>("nd");
string neg = parser.get<string>("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 ); labels.assign( pos_lst.size(), +1 );
const unsigned int old = (unsigned int)labels.size(); 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 ) ); sample_neg( full_neg_lst, neg_lst, Size( 96,160 ) );
labels.insert( labels.end(), neg_lst.size(), -1 ); labels.insert( labels.end(), neg_lst.size(), -1 );
CV_Assert( old < labels.size() ); CV_Assert( old < labels.size() );

@ -12,9 +12,9 @@ static void help()
{ {
printf( printf(
"\nThis sample demonstrates how to use different decision trees and forests including boosting and random trees.\n" "\nThis sample demonstrates how to use different decision trees and forests including boosting and random trees.\n"
"Usage:\n\t./tree_engine [-r <response_column>] [-ts type_spec] <csv filename>\n" "Usage:\n\t./tree_engine [-r=<response_column>] [-ts=type_spec] <csv filename>\n"
"where -r <response_column> specified the 0-based index of the response (0 by default)\n" "where -r=<response_column> 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" "-ts= specifies the var type spec in the form ord[n1,n2-n3,n4-n5,...]cat[m1-m2,m3,m4-m5,...]\n"
"<csv filename> is the name of training data file in comma-separated value format\n\n"); "<csv filename> 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<StatModel> model, const Ptr<TrainData>& dat
int main(int argc, char** argv) 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(); help();
return 0; return 0;
} }
const char* filename = 0; std::string filename = parser.get<std::string>("@input");
int response_idx = 0; int response_idx;
std::string typespec; std::string typespec;
response_idx = parser.get<int>("r");
for(int i = 1; i < argc; i++) typespec = parser.get<std::string>("ts");
if( filename.empty() || !parser.check() )
{ {
if(strcmp(argv[i], "-r") == 0) parser.printErrors();
sscanf(argv[++i], "%d", &response_idx); help();
else if(strcmp(argv[i], "-ts") == 0) return 0;
typespec = argv[++i];
else if(argv[i][0] != '-' )
filename = argv[i];
else
{
printf("Error. Invalid option %s\n", argv[i]);
help();
return -1;
}
} }
printf("\nReading in %s...\n\n",filename.c_str());
printf("\nReading in %s...\n\n",filename);
const double train_test_split_ratio = 0.5; const double train_test_split_ratio = 0.5;
Ptr<TrainData> data = TrainData::loadFromCSV(filename, 0, response_idx, response_idx+1, typespec); Ptr<TrainData> data = TrainData::loadFromCSV(filename, 0, response_idx, response_idx+1, typespec);
if( data.empty() ) 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; return 0;
} }

@ -148,23 +148,33 @@ static void writeOpticalFlowToFile(const Mat_<Point2f>& flow, const string& file
int main(int argc, const char* argv[]) 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] << "<frame0> <frame1> [<output_flow>]" << endl; parser.printMessage();
return 0;
}
string frame0_name = parser.get<string>("@frame0");
string frame1_name = parser.get<string>("@frame1");
string file = parser.get<string>("@output");
if (frame0_name.empty() || frame1_name.empty() || file.empty())
{
cerr << "Usage : " << argv[0] << " [<frame0>] [<frame1>] [<output_flow>]" << endl;
return -1; return -1;
} }
Mat frame0 = imread(argv[1], IMREAD_GRAYSCALE); Mat frame0 = imread(frame0_name, IMREAD_GRAYSCALE);
Mat frame1 = imread(argv[2], IMREAD_GRAYSCALE); Mat frame1 = imread(frame1_name, IMREAD_GRAYSCALE);
if (frame0.empty()) if (frame0.empty())
{ {
cerr << "Can't open image [" << argv[1] << "]" << endl; cerr << "Can't open image [" << parser.get<string>("frame0") << "]" << endl;
return -1; return -1;
} }
if (frame1.empty()) if (frame1.empty())
{ {
cerr << "Can't open image [" << argv[2] << "]" << endl; cerr << "Can't open image [" << parser.get<string>("frame1") << "]" << endl;
return -1; return -1;
} }
@ -184,9 +194,8 @@ int main(int argc, const char* argv[])
Mat out; Mat out;
drawOpticalFlow(flow, out); drawOpticalFlow(flow, out);
if (!file.empty())
if (argc == 4) writeOpticalFlowToFile(flow, file);
writeOpticalFlowToFile(flow, argv[3]);
imshow("Flow", out); imshow("Flow", out);
waitKey(); waitKey();

@ -73,9 +73,9 @@ void printHelp()
cout << "OpenCV video stabilizer.\n" cout << "OpenCV video stabilizer.\n"
"Usage: videostab <file_path> [arguments]\n\n" "Usage: videostab <file_path> [arguments]\n\n"
"Arguments:\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" " 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" " Turn on/off LP based motion estimation. The default is no.\n"
" --subset=(<int_number>|auto)\n" " --subset=(<int_number>|auto)\n"
" Number of random samples per one motion hypothesis. The default is 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" " Number of keypoints to find in each frame. The default is 1000.\n"
" --local-outlier-rejection=(yes|no)\n" " --local-outlier-rejection=(yes|no)\n"
" Perform local outlier rejection. The default is no.\n\n" " Perform local outlier rejection. The default is no.\n\n"
" -sm, --save-motions=(<file_path>|no)\n" " -sm=, --save-motions=(<file_path>|no)\n"
" Save estimated motions into file. The default is no.\n" " Save estimated motions into file. The default is no.\n"
" -lm, --load-motions=(<file_path>|no)\n" " -lm=, --load-motions=(<file_path>|no)\n"
" Load motions from file. The default is no.\n\n" " Load motions from file. The default is no.\n\n"
" -r, --radius=<int_number>\n" " -r=, --radius=<int_number>\n"
" Set sliding window radius. The default is 15.\n" " Set sliding window radius. The default is 15.\n"
" --stdev=(<float_number>|auto)\n" " --stdev=(<float_number>|auto)\n"
" Set smoothing weights standard deviation. The default is auto\n" " Set smoothing weights standard deviation. The default is auto\n"
" (i.e. sqrt(radius)).\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" " Turn on/off linear programming based stabilization method.\n"
" --lps-trim-ratio=(<float_number>|auto)\n" " --lps-trim-ratio=(<float_number>|auto)\n"
" Trimming ratio used in linear programming based method.\n" " Trimming ratio used in linear programming based method.\n"
@ -114,28 +114,28 @@ void printHelp()
" Do deblurring.\n" " Do deblurring.\n"
" --deblur-sens=<float_number>\n" " --deblur-sens=<float_number>\n"
" Set deblurring sensitivity (from 0 to +inf). The default is 0.1.\n\n" " Set deblurring sensitivity (from 0 to +inf). The default is 0.1.\n\n"
" -t, --trim-ratio=<float_number>\n" " -t=, --trim-ratio=<float_number>\n"
" Set trimming ratio (from 0 to 0.5). The default is 0.1.\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" " 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" " 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" " Set border extrapolation mode. The default is replicate.\n\n"
" --mosaic=(yes|no)\n" " --mosaic=(yes|no)\n"
" Do consistent mosaicing. The default is no.\n" " Do consistent mosaicing. The default is no.\n"
" --mosaic-stdev=<float_number>\n" " --mosaic-stdev=<float_number>\n"
" Consistent mosaicing stdev threshold. The default is 10.0.\n\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" " Do motion inpainting (requires CUDA support). The default is no.\n"
" --mi-dist-thresh=<float_number>\n" " --mi-dist-thresh=<float_number>\n"
" Estimated flow distance threshold for motion inpainting. The default is 5.0.\n\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" " Do color inpainting. The defailt is no.\n"
" --ci-radius=<float_number>\n" " --ci-radius=<float_number>\n"
" Set color inpainting radius (for ns and telea options only).\n" " Set color inpainting radius (for ns and telea options only).\n"
" The default is 2.0\n\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" " Perform wobble suppression. The default is no.\n"
" --ws-lp=(yes|no)\n" " --ws-lp=(yes|no)\n"
" Turn on/off LP based motion estimation. The default is 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" " Number of keypoints to find in each frame. The default is 1000.\n"
" --ws-local-outlier-rejection=(yes|no)\n" " --ws-local-outlier-rejection=(yes|no)\n"
" Perform local outlier rejection. The default is no.\n\n" " Perform local outlier rejection. The default is no.\n\n"
" -sm2, --save-motions2=(<file_path>|no)\n" " -sm2=, --save-motions2=(<file_path>|no)\n"
" Save motions estimated for wobble suppression. The default is no.\n" " Save motions estimated for wobble suppression. The default is no.\n"
" -lm2, --load-motions2=(<file_path>|no)\n" " -lm2=, --load-motions2=(<file_path>|no)\n"
" Load motions for wobble suppression from file. The default is no.\n\n" " Load motions for wobble suppression from file. The default is no.\n\n"
" -gpu=(yes|no)\n" " -gpu=(yes|no)\n"
" Use CUDA optimization whenever possible. The default is no.\n\n" " Use CUDA optimization whenever possible. The default is no.\n\n"
" -o, --output=(no|<file_path>)\n" " -o=, --output=(no|<file_path>)\n"
" Set output file path explicitely. The default is stabilized.avi.\n" " Set output file path explicitely. The default is stabilized.avi.\n"
" --fps=(<float_number>|auto)\n" " --fps=(<float_number>|auto)\n"
" Set output video FPS explicitely. By default the source FPS is used (auto).\n" " Set output video FPS explicitely. By default the source FPS is used (auto).\n"

@ -48,7 +48,13 @@ static void onMouse( int event, int x, int y, int flags, void* )
int main( int argc, char** argv ) 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<string>("@input");
Mat img0 = imread(filename, 1), imgGray; Mat img0 = imread(filename, 1), imgGray;
if( img0.empty() ) if( img0.empty() )

@ -36,56 +36,37 @@ int main( int argc, const char** argv )
VideoCapture capture; VideoCapture capture;
UMat frame, image; UMat frame, image;
Mat canvas; 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; 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; help();
if( cascadeOpt.compare( 0, cascadeOptLen, argv[i], cascadeOptLen ) == 0 ) return 0;
{ }
cascadeName.assign( argv[i] + cascadeOptLen ); cascadeName = parser.get<string>("cascade");
cout << " from which we have cascadeName= " << cascadeName << endl; nestedCascadeName = parser.get<string>("nested-cascade");
} scale = parser.get<double>("scale");
else if( nestedCascadeOpt.compare( 0, nestedCascadeOptLen, argv[i], nestedCascadeOptLen ) == 0 ) tryflip = parser.has("try-flip");
{ inputName = parser.get<string>("@filename");
if( argv[i][nestedCascadeOpt.length()] == '=' ) if ( !parser.check())
nestedCascadeName.assign( argv[i] + nestedCascadeOpt.length() + 1 ); {
if( !nestedCascade.load( nestedCascadeName ) ) parser.printErrors();
cerr << "WARNING: Could not load classifier cascade for nested objects" << endl; help();
} return -1;
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];
} }
if ( !nestedCascade.load( nestedCascadeName ) )
cerr << "WARNING: Could not load classifier cascade for nested objects" << endl;
if( !cascade.load( cascadeName ) ) if( !cascade.load( cascadeName ) )
{ {
cerr << "ERROR: Could not load classifier cascade" << endl; 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; 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)) if(!capture.open(c))
cout << "Capture from camera #" << c << " didn't work" << endl; cout << "Capture from camera #" << c << " didn't work" << endl;
} }

Loading…
Cancel
Save