Python:關於命令列引數argparse寫入圖片路徑
什麼是命令列引數?
命令列引數是在執行時給予程式/指令碼的標誌。它們包含我們程式的附加資訊,以便它可以執行。
並非所有程式都有命令列引數,因為並非所有程式都需要它們。
為什麼我們使用命令列引數?
如上所述,命令列引數在執行時為程式提供附加資訊。
這允許我們在不改變程式碼的情況下動態地為我們的程式提供不同的輸入 。
您可以繪製命令列引數類似於函式引數的類比。如果你知道如何在各種程式語言中宣告和呼叫函式,那麼當你發現如何使用命令列引數時,你會立刻感到賓至如歸。
鑑於這是計算機視覺和影象處理部落格,您在這裡看到的很多引數都是影象路徑或視訊路徑。
那麼讓我們建立一個名為shape_counter .py的新檔案並開始編碼:
我們在第2行匯入 argparse - 這是幫助我們解析和訪問命令列引數的包。
然後,在第7-12行,我們解析兩個命令列引數。程式碼在這些行上非常易讀,您可以看到如何格式化引數。
我們以 -input 引數為例。
在第7行,我們將ArgumentParser 物件例項化為 ap 。
然後在第8行和第9行我們新增我們的 - input 引數。我們必須指定速記和長版本( - i 和 - input ),其中任何一個標誌都可以在命令列中使用。這是必需的引數,如 required = True所示。如上所示, 幫助字串將在終端中提供附加資訊。
類似地,在第10行和第11行,我們指定了 -input 引數,這也是必需的。
從那裡我們使用路徑載入影象。請記住,輸入影象路徑包含在 args [ “input” ]中 ,因此這是cv2的引數 imread 。
簡單吧?
其餘的行是特定於影象處理的——
在第18-20行,我們完成了三項操作:
將影象轉換 為灰度。
模糊灰度影象。
閾值模糊影象。
我們準備找到並繪製形狀輪廓:
在第23-25行,我們在閾值影象中找到形狀輪廓 。
從那裡,我們在輸入影象上繪製輪廓(第28和29行)。
然後我們在影象上組裝並放置文字(第32-34行)。文字包含形狀的總數。
最後,我們利用我們的 -input 影象路徑引數將影象寫入到磁碟中的 cv2.imwrite (第37行)。
讓我們用兩個引數執行命令:
附完整程式碼
Codeblock #1: Lines 1-20# import the necessary packages
import argparse
import imutils
import cv2
# construct the argument parser and parse the arguments
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())
# load the input image from disk
image = cv2.imread(args["input"])
# convert the image to grayscale, blur it, and threshold it
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5,5), 0)
thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1]
# extract contours from the image
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if imutils.is_cv2() else cnts[1]
# loop over the contours and draw them on the input image
for c in cnts:
cv2.drawContours(image, [c], -1, (0, 0, 255), 2)
# display the total number of shapes on the image
text = "I found {} total shapes".format(len(cnts))
cv2.putText(image, text, (10, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5,
(0, 0, 255), 2)
# write the output image to disk
cv2.imwrite(args["output"], image)
$ python shape_counter.py --input input_01.png --output output_01.png