参数是什么意思

What does argc mean?

本文关键字:意思 是什么 参数      更新时间:2023-10-16

我不明白,OpenCV中的代码加载图像的功能是什么。if(argc !=2(的功能是什么?你能告诉我吗?

 if( argc != 2)
    {
     cout <<" Usage: display_image ImageToLoadAndDisplay" << endl;
     return -1;
    }

完整代码:

1 #include <opencv2/core/core.hpp>
2 #include <opencv2/highgui/highgui.hpp>
3 #include <iostream>
4
5 using namespace cv;
6 using namespace std;
7
8 int main( int argc, char** argv )
9 {
10 if( argc != 2)
11 {
12 cout <<" Usage: display_image ImageToLoadAndDisplay" << endl;
13 return -1;
14 }
15
16 Mat image;
17 image = imread(argv[1], CV_LOAD_IMAGE_COLOR); // Read the file
18
19 if(! image.data ) // Check for invalid input
20 {
21 cout << "Could not open or find the image" << std::endl ;
22 return -1;
23 }
24
25 namedWindow( "Display window", CV_WINDOW_AUTOSIZE );// Create a window for display.
26 imshow( "Display window", image ); // Show our image inside it.
27
28 waitKey(0); // Wait for a keystroke in the window
29 return 0;
30 }

应该包含在任何C++(或C,ObjC或相关语言(的教程中,例如GNU教程。

C++程序的main函数有两个参数,按照约定名为 argcargv ,这给了它用于启动程序的命令行参数。

argc是参数计数,argv是字符串数组。

程序本身是第一个参数,argv[0] ,所以argc总是至少为 1。

因此,当程序使用一个命令行参数运行时,argc 2。如果它没有参数或多个参数运行,则argc != 2将为真,因此将打印使用消息"用法:display_image ImageToLoadAndDisplay",告诉用户如何正确运行它。


例如,如果这样做:

$ display_image firstarg "second arg"

这些值将是:

argc: 3
argv[0]: "display_image"
argv[1]: "firstarg"
argv[2]: "second arg"

可能值得指出的是,代码在很多方面都很奇怪。使用消息开头的额外空间非常奇怪。"用法"通常都是小写的。您通常将实际的程序名称(argv[0](放在字符串中,而不是硬编码的规范名称中。使用消息通常转到cerr,而不是cout。约定是为用户错误的错误返回一个正数,通常为 2 表示无效参数,而不是 -1。您可以在源代码中找到更好的argc/argv处理示例,几乎可以在Unix命令行上使用任何工具(尽管其中大多数都比较复杂,通常使用getopt等库来解析文件参数中的选项等(。

  • argc = 争论计数。这用于确定运行程序时使用的命令行参数。
  • argv称为参数向量,它包含所有命令行参数的名称,包括程序的名称。
  • 在你运行的任何程序上,argc总是至少为1;这是因为程序本身包含在参数计数中。所以在您的程序 ARGC 必须是 2,其中包括: your_programanother_file.如果 argc 不是 2,这意味着它是等于 1 或大于 2,因为这不是程序需要,代码中止进一步执行