王老头

导航

Python, argparse,命令行参数

今天我们要讨论一个基本的开发人员,工程师和计算机科学家的技能 - 命令行参数。

具体来说,我们将讨论:
    1. 什么是命令行参数
    2.我们为什么使用命令行参数
    3.如何用Python解析命令行参数

命令行参数是一项基本技能,您必须学会如何使用,特别是如果您尝试应用更先进的计算机视觉,图像处理或深度学习概念。

在今天的博客中,你会发现命令行参数比看起来更容易处理(即使你以前从未使用过)。

1.什么是命令行参数?
命令行参数是在运行时给予程序/脚本的标志。 它们包含我们程序的附加信息,以便它可以执行。

2.为什么我们使用命令行参数?

如前所述,命令行参数在运行时为程序提供附加信息。这使我们能够在不改变代码的情况下即时为我们的程序提供不同的输入。

先尝试一个简单的例子,命令为:simple_example.py:

 1 # import the necessary packages
 2 import argparse
 3  
 4 # construct the argument parse and parse the arguments
 5 ap = argparse.ArgumentParser()
 6 ap.add_argument("-n", "--name", required=True,
 7     help="name of the user")
 8 args = vars(ap.parse_args())
 9  
10 # display a friendly message to the user
11 print("Hi there {}, it's nice to meet you!".format(args["name"]))
如果您需要,第7行的帮助字符串将在终端中提供更多信息。 要查看命令使用帮助,您可以在终端中输入以下内容(直接在下面输出):
1 $ python simple_example.py --help
2 usage: simple_example.py [-h] -n NAME
3  
4 optional arguments:
5   -h, --help            show this help message and exit
6   -n NAME, --name NAME  name of the user

接下来,你可以尝试在ternimal中输入以下命令,便可以看到结果:

1 $ python simple_example.py --name Adrian
2 Hi there Adrian, it's nice to meet you!
3 $
4 $ python simple_example.py --name Stephanie
5 Hi there Stephanie, it's nice to meet you!
6 $
7 $ python simple_example.py --name YourNameHere
8 Hi there YourNameHere, it's nice to meet you!

注意:如果我执行步骤5而没有加上命令行参数(或不正确的参数),我会看到如显示的打印用法/错误信息。

1 $ python simple_example.py
2 usage: simple_example.py [-h] -n NAME
3 simple_example.py: error: argument -n/--name is required

接下来让我们创建一个名为shape_counter.py的新文件并开始编码:

 1 #1: Lines 1-20# import the necessary packages
 2 import argparse
 3 import imutils
 4 import cv2
 5  
 6 # construct the argument parser and parse the arguments
 7 ap = argparse.ArgumentParser()
 8 ap.add_argument("-i", "--input", required=True,
 9     help="path to input image")
10 ap.add_argument("-o", "--output", required=True,
11     help="path to output image")
12 args = vars(ap.parse_args())
13  
14 # load the input image from disk
15 image = cv2.imread(args["input"])
16  
17 # convert the image to grayscale, blur it, and threshold it
18 gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
19 blurred = cv2.GaussianBlur(gray, (5,5), 0)
20 thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1]
21 
22 # extract contours from the image
23 cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
24     cv2.CHAIN_APPROX_SIMPLE)
25 cnts = cnts[0] if imutils.is_cv2() else cnts[1]
26  
27 # loop over the contours and draw them on the input image
28 for c in cnts:
29     cv2.drawContours(image, [c], -1, (0, 0, 255), 2)
30  
31 # display the total number of shapes on the image
32 text = "I found {} total shapes".format(len(cnts))
33 cv2.putText(image, text, (10, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5,
34         (0, 0, 255), 2)
35  
36 # write the output image to disk
37 cv2.imwrite(args["output"], image)

我们在ternimal下用我们的两个参数执行命令:

1 $ python shape_counter.py --input input_01.png --output output_01.png

看到结果显示如下:

】: 我想与你分享另一个“需要注意的地方”。 有时在这个博客上,我的命令行参数标志在它们中有' - '(短划线),例如--features-db。 这有点令人困惑,并且当获取参数所包含的值时,您需要使用'_'(下划线)。

例如,我们输入下面的代码:

 1 # construct the argument parser and parse the arguments
 2 ap = argparse.ArgumentParser()
 3 ap.add_argument("-d", "--dataset", required=True, help="Path to the directory of indexed images")
 4 ap.add_argument("-f", "--features-db", required=True, help="Path to the features database")
 5 ap.add_argument("-c", "--codebook", required=True, help="Path to the codebook")
 6 ap.add_argument("-o", "--output", required=True, help="Path to output directory")
 7 args = vars(ap.parse_args())
 8  
 9 # load the codebook and open the features database
10 vocab = pickle.loads(open(args["codebook"], "rb").read())
11 featuresDB = h5py.File(args["features_db"], mode="r")
12 print("[INFO] starting distance computations...")

请注意突出显示的行,我已将参数定义为--features-db(带短划线),但我通过args [“features_db”](带有下划线)引用它。 这是因为argparse Python库在解析过程中用下划线替换破折号。

 

 

原文链接:https://www.pyimagesearch.com/2018/03/12/python-argparse-command-line-arguments/   有一段时间没看Adrian的博客了呢 : ).

posted on 2018-03-26 11:47  王老头  阅读(864)  评论(0)    收藏  举报