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用下劃線替換了破折號。

相關文章
相關標籤/搜索