Python, argparse and command-line parameters

1. What is the command-line arguments?

Command line parameters are given to mark the program / script at runtime. They contain additional information about the program, so that you can perform.
Not all programs have a command-line argument, because not all programs need them. In the Python script my blog article makes extensive use of command-line arguments can even be said that 98% of the blog articles are using the command-line parameters.

2. Why do we use the command-line arguments?

As described above, in the run-time command line parameters provides more information about the program.
This allows us the immediate availability of different inputs for a program without changing the code .
By analogy similar arguments command-line parameters, if you know how to declare and call a function, then when discovered how to use the command-line parameters, you will immediately feel at home in a variety of programming languages.
Since this is a computer vision and image processing blog, so here are a number of parameters to see a video image path or paths.
In the case where the depth of learning, or the model path will see time point count as command line arguments.
In this article, we will learn Python argparse package by two scripts.

3.Python argparse library

First, let us name a new script simple_example.py:

# 导入argparse包
import argparse

# 构造参数并解析参数
ap = argparse.ArgumentParser()
ap.add_argument("-n", "--name", required=True,
    help="name of the user")
args = vars(ap.parse_args())

# 打印交互信息
print("Hi there {}, it's nice to meet you!".format(args["name"]))

Add a unique parameter, -n or -name, shorthand must be specified (-n) and a regular version (-name), either sign can be used on the command line. As described above, -name is a required parameter required = True.
-Help is an optional parameter, an input terminal:

python simple_example.py --help

Print out the following message:

 usage: simple_example.py [-h] -n NAME

    optional arguments:
      -h, --help            show this help message and exit
      -n NAME, --name NAME  name of the user

Enter the following command to run the script:

python simple_example.py --name 哲少

Print out the following results:

 Hi there 哲少, it's nice to meet you!

As long as there is no space name, it will display correctly in the output.

4. Python parse command line parameters

The second script shape_counter.py:

# USAGE
# python shape_counter.py --input input_01.png --output output_01.png
# python shape_counter.py --input input_02.png --output output_02.png

# 导入必要的软件包
import argparse
import imutils
import cv2

# 构造参数并解析参数
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--input", required=True,
    help="path to input image")
ap.add_argument("-o", "--output", required=True,
    help="path to output image")
args = vars(ap.parse_args())

# 从磁盘加载图像
image = cv2.imread(args["input"])

# 将图像转换为灰度图像、高斯平滑、阈值求取并二值化
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5,5), 0)
thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1]

# 从图像中提取轮廓
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
    cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)

# 在输入的图像上循环绘制轮廓
for c in cnts:
    cv2.drawContours(image, [c], -1, (0, 0, 255), 2)

# 显示图像中形状的总数
text = "I found {} total shapes".format(len(cnts))
cv2.putText(image, text, (10, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5,
        (0, 0, 255), 2)

# 保存输出图像到硬盘
cv2.imwrite(args["output"], image)

Run the script:

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

Here Insert Picture Description
Here Insert Picture Description
With different parameters to run the script again:

 python shape_counter.py --input input_02.png --output output_02.png

Here Insert Picture Description
Here Insert Picture Description
Finally, note that a "trap", sometimes on this blog, my command line parameter flag with the "-" (dash), for example -features-db. When the value of the parameter contains crawl, you need to use "_" (underscore), this is a bit confusing and a bit of trouble, for example, the following code:

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

Because argparse library during parsing, Python replace the dash with an underscore.

Released seven original articles · won praise 8 · views 128

Guess you like

Origin blog.csdn.net/qq_42878057/article/details/104772120