浅谈Python 命令行参数argparse写入图片路径操作
什么是命令行参数?
命令行参数是在运行时给予程序/脚本的标志。它们包含我们程序的附加信息,以便它可以执行。
并非所有程序都有命令行参数,因为并非所有程序都需要它们。
为什么我们使用命令行参数?
如上所述,命令行参数在运行时为程序提供附加信息。
这允许我们在不改变代码的情况下动态地为我们的程序提供不同的输入 。
您可以绘制命令行参数类似于函数参数的类比。如果你知道如何在各种编程语言中声明和调用函数,那么当你发现如何使用命令行参数时,你会立刻感到宾至如归。
鉴于这是计算机视觉和图像处理博客,您在这里看到的很多参数都是图像路径或视频路径。
那么让我们创建一个名为shape_counter .py的新文件并开始编码:
在第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
以上这篇浅谈Python 命令行参数argparse写入图片路径操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持来客网。