Python、argparse和命令行参数

(注:本文摘录自Adrian Rosebrock的教程文章经翻译整理而来)

1.什么是命令行参数?

命令行参数是在运行时赋予程序/脚本的标志。它们包含程序的其余信息,以即可以执行。
并不是全部程序都具备命令行参数,由于并不是全部程序都须要它们。在个人博客文章的Python脚本中普遍使用了命令行参数,甚至能够说,这个博客上98%的文章都使用了命令行参数。python

2.为何咱们使用命令行参数?

如前所述,命令行参数在运行时为程序提供了更多信息。
这使咱们能够在不更改代码的状况下即时为程序提供不一样的输入
能够类推命令行参数相似于函数参数,若是知道如何在各类编程语言中声明和调用函数,那么当发现如何使用命令行参数时,就会当即感到宾至如归。
鉴于这是计算机视觉和图像处理博客,所以在此处看到的许多参数都是图像路径或视频路径。
在深度学习的状况下,将看到模型路径或时间点计数做为命令行参数。
在本文中,咱们将经过两个脚本示例来学习Python argparse包。编程

3.Python argparse 库

首先,让咱们命名一个新脚本 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"]))

添加惟一的参数, -n或--name,必须同时指定速记(-n)和普通版本(--name),其中任一标志都可在命令行中使用。如以上所述,--name是必需的参数required=True。
--help是可选参数,终端输入:函数

python simple_example.py --help

打印出如下提示信息:学习

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

输入如下命令运行脚本:ui

python simple_example.py --name 哲少

打印出如下结果:this

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

只要名字没有空格,它就会在输出中正确显示。spa

4.使用Python解析命令行参数

第二个脚本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)

运行脚本:翻译

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

input_01.png
output_01.png
以不一样的参数再次运行脚本:

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

input_02.png
output_02.png
最后,要注意一个“陷阱”,有时在此博客上,个人命令行参数标志中带有“-”(破折号),例如--features-db 。抓取参数所包含的值时,您须要使用“ _”(下划线),这有点使人困惑而且有点麻烦,例如如下代码:

# 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...")

由于argparse库在解析过程当中,Python用下划线替换了破折号。

相关文章
相关标签/搜索