各位用户为了找寻关于浅谈Python 命令行参数argparse写入图片路径操作的资料费劲了很多周折。这里教程网为您整理了关于浅谈Python 命令行参数argparse写入图片路径操作的相关资料,仅供查阅,以下为您介绍关于浅谈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行)。
让我们用两个参数执行命令:
附完整代码
? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37Codeblock
#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写入图片路径操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/lixiaoyu101/article/details/84139774