Python必备基本技能——命令行参数args详解
生活随笔
收集整理的這篇文章主要介紹了
Python必备基本技能——命令行参数args详解
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Python必備基本技能——命令行參數args詳解
- 1. 效果圖
- 2. 源碼
- 2.1 簡單命令行參數
- 2.1 輪廓檢測源代碼
- 參考
這篇博客將介紹一項開發人員、工程師和計算機科學家必備的技能——命令行參數(原理及使用)。 依賴
pip install argparse
vars會將命令行參數解析成字典,argparse Python 庫在解析過程中用下劃線替換破折號(若命令行參數中有中劃線 “-” 需要用下劃線 “_” 解析。)
1. 效果圖
命令行參數有默認值,無默認值,必須,有中劃線-效果圖如下:
尋找輪廓效果圖如下:
2. 源碼
2.1 簡單命令行參數
# USAGE
# python simple_example.py -n Lucy --features-db feat.db
# python simple_example.py --name Lucy --features-db feat.db -i ml2.jpg# 導入必要的包
import argparse# 構建命令行參數及解析
# --image 名稱
ap = argparse.ArgumentParser() # 實例化對象
# -n 簡短
# --name 全稱
# required 必須與否,非必需,可給定默認值
# help 提示語,終端的附加信息# --features-db 命令行參數標志中有一個“-”(破折號),但在獲取參數包含的值時,需要使用“_”(下劃線),
# 這是因為argparse Python 庫在解析過程中用下劃線替換破折號。
ap.add_argument("-n", "--name", required=True,help="name of the user")
ap.add_argument("-f", "--features-db", required=True, help="Path to the features database")
ap.add_argument("-i", "--image", required=False, default="ml.jpg", help="Path to the image")# 在對象上將解析的命令行參數轉換為 Python 字典,其中字典的鍵是命令行參數的名稱,值是為命令行參數提供的字典的值。
args = vars(ap.parse_args())# 給用戶輸出一行友好的問好
print("Hi there {}, it's nice to meet you!".format(args["name"]))# 注意,這里有一個陷阱,入參: "--features-db",但解析時用_代替-;
print(args['features_db'])
print(args['image'])
2.1 輪廓檢測源代碼
輪廓的原始圖可以參考:使用Python,OpenCV進行涂鴉(繪制文字、線、圓、矩形、橢圓、多邊形輪廓、多邊形填充、箭頭)制作;
# USAGE
# python shape_counter.py --input arrow.png --output output_01.png# 導入必要的包
import argparse
import imutils
import cv2# 構建命令行參數及解析
# --input 輸入圖像路徑
# --output 輸出圖像路徑
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]
cv2.imshow("thresh",thresh)
cv2.waitKey(0)# 從圖像提取輪廓
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, (240, 32, 160), 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)
cv2.imshow(str(args["output"]),image)
cv2.waitKey(0)
參考
- https://www.pyimagesearch.com/2018/03/12/python-argparse-command-line-arguments/
總結
以上是生活随笔為你收集整理的Python必备基本技能——命令行参数args详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用Python,OpenCV进行涂鸦(
- 下一篇: OpenCV最经典的3种颜色空间(cv2