淺談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 packagesimport argparseimport imutilsimport cv2 # construct the argument parser and parse the argumentsap = 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 diskimage = cv2.imread(args['input']) # convert the image to grayscale, blur it, and threshold itgray = 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 imagecnts = 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 imagefor c in cnts:cv2.drawContours(image, [c], -1, (0, 0, 255), 2) # display the total number of shapes on the imagetext = '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 diskcv2.imwrite(args['output'], image)$ python shape_counter.py --input input_01.png --output output_01.png
以上這篇淺談Python 命令行參數argparse寫入圖片路徑操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章:
