vc 命令行 命令行参数
An absolute crucial skill to have.
绝对关键的技能。
Why is using command line arguments so convenient? Because if we didn’t use command line arguments we would have to hardcode the path to our image, like this:
为什么使用命令行参数如此方便? 因为如果不使用命令行参数,我们将必须对图像的路径进行硬编码 ,如下所示:
image = cv2.imread(“path/to/your/image.jpg”)
While the above line of code is perfectly valid (provided that path/to/your/image.jpg exists), hardcoding paths to files tends to be bad practice. In real-world situations we either (1) supply command line arguments or (2) utilize some sort of configuration file that details paths to various files.
尽管上面的代码行是完全有效的(假设存在path / to / your / image.jpg),但硬编码文件路径往往是一种不好的做法。 在实际情况下,我们要么(1)提供命令行参数,要么(2)利用某种配置文件来详细描述各种文件的路径。
So while parsing command line arguments can add a few extra lines to your code, it is actually extremely beneficial because it ensures that we don’t have to update our source code whenever we want to load a new image.
因此,尽管解析命令行参数可以在您的代码中添加一些额外的行,但这实际上是非常有益的,因为它确保了我们在每次要加载新图像时都不必更新源代码。
Pretty cool, right?
很酷吧?
How it is done:
怎么做的:
Create a .py file and name it img_to_np.py, This tutorial we will focus on loading an image using command line argument, the img_to_np.py will load the image and show some basic information about the image.
创建一个.py文件并将其命名为img_to_np.py,本教程将重点介绍使用命令行参数加载图像,img_to_np.py将加载图像并显示有关该图像的一些基本信息。
# import the necessary packages
import argparse# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True, help="Path to the image")
args = vars(ap.parse_args())
The first two lines, we import the necessary libraries. we will use argparser library to handle parsing of our command line arguments
前两行,我们导入必要的库。 我们将使用argparser库来处理命令行参数的解析
The last four lines handle parsing the command line arguments. The only necessary argument is “ — image”: the path to our image on disk. Finally we pass the argument and store it in a dictonary args
最后四行处理解析命令行参数。 唯一必要的参数是“ -image ” :磁盘上映像的路径。 最后,我们传递参数并将其存储在字典参数中
At this point, we would already be surprised what the — -image switch is for ?
在这一点上,我们已经惊讶于图像开关的作用是什么?
The — image “switch” (“switch” is a synonym for “command line argument” and the terms can be used interchangeably) is a string that we specify at the command line. This switch tells our command_line.py script where the image we want to load lives on disk.
图像“开关”(“开关”是“命令行参数”的同义词,并且这些术语可以互换使用)是我们在命令行中指定的字符串。 此开关告诉我们的command_line.py脚本我们要加载的映像位于磁盘上。
# import the necessary packagesimport argparse
import cv2# construct the argument parser and parse the argumentsap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True, help="Path to the image")
args = vars(ap.parse_args())# load the image and show some basic information on it
image = cv2.imread(args["image"])
print("width: %d pixels" % (image.shape[1]))
print("height: %d pixels" % (image.shape[0]))
print("channels: %d" % (image.shape[2]))# show the image and wait for a keypress
cv2.imshow("Image", image)
cv2.waitKey(0)# save the image -- OpenCV handles converting filetypes
# automaticallycv2.imwrite("newimage.jpg", image)
Now that we have the path to the image (via the command line argument), we can load it off disk using the cv2.imread function . The cv2.imread function returns a NumPy array representing the image. Since, images are represented as NumPy arrays, we can simply use the shape attribute to examine the width, height, and the number of channels.
现在我们有了图像的路径(通过命令行参数),我们可以使用cv2.imread函数将其从磁盘加载。 cv2.imread函数返回表示图像的NumPy数组。 由于图像被表示为NumPy数组,因此我们可以简单地使用shape属性来检查宽度,高度和通道数。
The # show the image and wait for a keypress handle displaying the actual image on screen.The first parameter is a string, or the “name” of our window. The second parameter is a reference to the image we loaded off disk.
#显示图像,然后等待按键手柄在屏幕上显示实际图像。第一个参数是字符串,或我们窗口的“ 名称 ”。 第二个参数是对我们从磁盘加载的映像的引用。
Finally, a call to cv2.waitKey pauses the execution of the script until we press a key on our keyboard. Using a parameter of “0” indicates that any keypress will un-pause the execution.
最后,对cv2.waitKey的调用将暂停脚本的执行,直到我们按键盘上的某个键为止。 使用参数“ 0 ”表示任何按键都会取消暂停执行。
In the last line, All we are doing here is providing the path to the file (the first argument) and then the image we want to save (the second argument). It’s that simple. In this case we’ll just hardcode the path to newimage.jpg
在最后一行,我们要做的就是提供文件的路径(第一个参数),然后提供我们要保存的图像(第二个参数)。 就这么简单。 在这种情况下,我们将硬编码到newimage.jpg的路径
To run our script and display our image, we simply open up a terminal window and execute the following command:
要运行脚本并显示图像,我们只需打开一个终端窗口并执行以下命令:
$ python load_display_save.py — image example.jpg
Finally, note the contents of your directory. You’ll see a new file there: newimage.jpg :
最后,记下目录的内容。 您会在那里看到一个新文件:newimage.jpg:
OpenCV has automatically converted the PNG image to JPG for us! No further effort is needed on our part to convert between image formats.
OpenCV已自动为我们将PNG图像转换为JPG! 我们无需进一步努力就可以在图像格式之间进行转换。
Alright, What do we do, if the number of arguments increases. How do we handle such overwhelming task without having to pass each and every parameters in the command line argument ??
好吧,如果参数数量增加,我们该怎么办。 我们如何处理此类繁重的任务而不必在命令行参数中传递每个参数?
What if i tell you, there is a solution already available, that you can reuse.
如果我告诉您,已经有一个可以重用的解决方案了。
Wait till my next article on creating a json configuration file to store all customizable options.
等到我的下一篇关于创建json配置文件以存储所有可自定义选项的文章。
There are many benefits to using a JSON configuration file:
使用JSON配置文件有很多好处:
- First, we don’t need to explicitly define a never-ending list of command line arguments — all we need to supply is the path to our configuration file. 首先,我们不需要显式定义命令行参数的永无止境的列表-我们需要提供的只是配置文件的路径。
A configuration file allows us to consolidate all relevant parameters into a single location.
配置文件使我们可以将所有相关参数合并到一个位置 。
- This also ensures that we don’t forget which command line options were used for each Python script. All options will be defined within our configuration file. 这也确保我们不会忘记每个Python脚本使用了哪些命令行选项。 所有选项都将在我们的配置文件中定义。
翻译自: https://medium.com/analytics-vidhya/using-command-line-arguments-in-python-6c24f64a3a80
vc 命令行 命令行参数