Today we are going to discuss a fundamental developer, engineer, and computer scientist skill — command line arguments.
Specifically, we’ll be discussing:
- What are command line arguments
- Why we use command line arguments
- How to parse command line arguments with Python
Command line arguments are an elementary skill that you must learn how to use, especially if you are trying to apply more advanced computer vision, image processing, or deep learning concepts.
If you are new to command line arguments or do not know how to use them that’s okay! But you still need to take the time to educate yourself on how to use them — this post will help you do exactly that.
By the end of today’s post you will have a strong understanding of command line arguments, how they work, and how to use them.
Python, argparse, and command line arguments
Each day I receive 3-5 emails or comments from PyImageSearch readers who are struggling with command line arguments.
In fact, just an hour before I decided to write this blog post, I received the following email from Arjun:
Hey Adrian, I just downloaded the source code to your deep learning face detection blog post, but when I execute it I get the following error:
$ python detect_faces.py
usage: detect_faces.py [-h] -i IMAGE -p PROTOTXT -m MODEL [-c CONFIDENCE]
detect_faces.py: error: the following arguments are required: -i/–image, -p/–prototxt, -m/–modelHelp!
Arjun is far from alone in struggling with this error.
Many other readers run into similar problems when working with command line arguments — but the honest truth is that nearly all of these errors can be avoided by taking the time to educate yourself on command line arguments.
Inside the rest of today’s post you’ll learn that command line arguments are a lot easier to work with than they seem (even if you have never used them before).
You’ll find that you do not have to modify a single line of code to work with them. And by the end of the post you’ll be able to work with command line arguments like a pro.
Let’s get started.
What are command line arguments?
Command line arguments are flags given to a program/script at runtime. They contain additional information for our program so that it can execute.
Not all programs have command line arguments as not all programs need them. That being said, on this blog we make extensive use of command line arguments in our Python scripts and I’d even go so far to say that 98% of the articles on this blog make use of them.
Why do we use command line arguments?
As stated, command line arguments give additional information to a program at runtime.
This allows us to give our program different input on the fly without changing the code.
You can draw the analogy that a command line argument is similar to a function parameter. If you know how functions are declared and called in various programming languages, then you’ll immediately feel at home when you discover how to use command line arguments.
Given that this is computer vision and image processing blog, a lot of the arguments you’ll see here are image paths or video paths.
In the case of deep learning, for which this blog is also known, you’ll see model paths or epoch counts as command line arguments.
In the remainder of today’s post we will learn about the Python argparse package via two script examples.
I’ll also be showing how PyCharm users can run a script without ever leaving PyCharm if they so choose.
The argparse Python library
First, let’s make a new script, naming it simple_example.py
:
# import the necessary packages import argparse # construct the argument parse and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-n", "--name", required=True, help="name of the user") args = vars(ap.parse_args()) # display a friendly message to the user print("Hi there {}, it's nice to meet you!".format(args["name"]))
First, we need the argparse
package, so we go ahead and import it on Line 2.
On Line 5 we instantiate the ArgumentParser
object as ap
.
Then on Lines 6 and 7 we add our only argument, --name
. We must specify both shorthand (-n
) and longhand versions (--name
) where either flag could be used in the command line. This is a required argument as is noted by required=True
.
The help
string from Line 7 will give additional information in the terminal if you need it. To view the command usage help you may enter the following in the terminal (output directly below):
$ python simple_example.py --help usage: simple_example.py [-h] -n NAME optional arguments: -h, --help show this help message and exit -n NAME, --name NAME name of the user
Notice how I specified all three of:
- The executable (
python
) - Our Python script file (
simple_example.py
) - And an argument (
--help
) in order to print the usage.
Line 8 of the script instructs Python and the argparse
library to parse the command line arguments. I also call vars
on the object to turn the parsed command line arguments into a Python dictionary where the key to the dictionary is the name of the command line argument and the value is value of the dictionary supplied for the command line argument. To see this in action I would suggest inserting a print(args)
statement into the code.
While optional, I prefer converting the arguments object to a dictionary so I can execute the script via my command line or in a Jupyter Notebook. When using a Jupyter Notebook I can simply delete the command line arguments parsing code and insert a dictionary named args
with any hardcoded values.
Now you’re probably wondering: How can I access the value from the command line argument argument?
That’s simple, and there’s an example on Line 11 of the script.
In the format string, we specify args["name"]
. As you’ll see shortly, we’ll print our name to the screen dynamically with this command line argument.
Here are the steps we need to take in order to execute our simple_example.py
script:
- Step 1: Download the zip accompanying this blog post from the “Downloads” section into a location on your machine of your choosing (I would suggest the Desktop for sake of simplicity).
- Step 2: Open a terminal and change directory to where the zip lives.
- Step 3: Unzip.
- Step 4: Change directory again, this time into the new directory that was just extracted.
- Step 5: Activate your virtual environment with the
workon
command. Example:workon cv
orworkon py3cv4
(depending on the name of your environment). If you are using my Pre-configured Raspbian .img, it is recommended to use thesource
command with the script in the home folder. Example:source ~/start_py3cv4.sh
orsource ~/start_openvino.sh
. For OpenVINO it is especially important to use thesource
command as it loads a handful of environment variables in addition to activating your virtual environment. - Step 6: Execute the program (with command line arguments) and view the output.
On this blog, I show commands and their arguments in a “shell” codeblock. The $
at the beginning of the prompt is your queue that this is a terminal command and you should enter the command after the $
character along with your preferred arguments similar to or exactly as written.
I’ve taken care of Step 1 by downloading the code to this lesson to my Desktop in my PyImageSearch directory for easy access.
From there, I entered the following commands and generated the accompanying output:
$ cd ~/Desktop/PyImageSearch $ $ unzip command-line-arguments.zip ... $ $ cd command-line-arguments $ pwd /Users/adrianrosebrock/Desktop $ $ python simple_example.py --name Adrian Hi there Adrian, it's nice to meet you! $ $ python simple_example.py --name Stephanie Hi there Stephanie, it's nice to meet you! $ $ python simple_example.py --name YourNameHere Hi there YourNameHere, it's nice to meet you!
Let’s walk through what I’ve demonstrated in the terminal above while referring to Steps 2-5.
Step 2:
I changed directory to where I downloaded the zip for this lesson (Line 1).
I pressed the enter/return button on Line 2 to make the output easier to read. This is optional.
Step 3:
I unzipped the .zip file associated with this lesson (Line 3).
The ...
on Line 4 signifies that there was output from the unzipping process but I am not showing it here. Note that output doesn’t have a preceding $
.
Step 4:
Next I need to change directory into the folder that I just unzipped (Line 6).
Just to be sure I’m where I need to be, I print my working directory on Line 7 with the output being shown on Line 8.
Step 5:
I execute the command with argument on Line 10. I’m specifying my name after the --name
flag. As long as my name doesn’t have any spaces, it will be displayed properly in the output.
The output is displayed on Line 11. Notice how the script dynamically shows my name exactly as I entered it in the command. Command line arguments are powerful and allow you to test your program with different input without changing a line of code.
Lines 13-17 demonstrate two additional examples that my script with no code changes will print a given name. Try it yourself with your own name…or maybe that of your nemesis.
Note: If I execute Step 5 without command line arguments (or with incorrect ones), I’ll see usage/error information printed as is shown.
$ python simple_example.py usage: simple_example.py [-h] -n NAME simple_example.py: error: argument -n/--name is required
This simple example helped us to grasp the concept of command line arguments; however it is not very useful to print a sentence containing our name.
In the next section I’ll provide a more practical example of using command line arguments
Parsing command line arguments with Python
In this next example we’ll be counting shapes in any given input image while annotating an output image that gets written to disk.
We’ll be making use of command line arguments again to specify the input image path and the output image path.
The image processing technicals will be light for this explanation — after all we’re just making this example for the purposes of command line arguments.
So let’s create a new file called shape_counter.py
and start coding:
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]
We import argparse
on Line 2 — this is the package that will help us parse and access our command line arguments.
Then, on Lines 7-12 we parse two command line arguments. The code is very readable on these lines and you can see how to format an argument.
Let’s take the --input
argument as an example.
On Line 7 we instantiate the ArgumentParser
object as ap
.
Then on Lines 8 and 9 we add our --input
argument. We must specify shorthand and longhand versions (-i
and --input
) where either flag could be used in the command line. This is a required argument as is noted by required=True
. The help
string will give additional information in the terminal as I demonstrated above.
Similarly, on Lines 10 and 11, we specify our --output
argument which is also required.
From there we load the image using the path. Remember, the input image path is contained in args["input"]
, so that is the parameter to cv2.imread
.
Simple, right?
The rest of the lines are image processing specific, so if you’ve landed on this blog without any OpenCV or image processing skills, you might want to poke around in the archives for further explanations on these concepts.
On Lines 18-20 we complete three operations:
- Convert the
image
to grayscale. - Blur the grayscale image.
- Threshold the
blurred
image.
We’re ready to find and draw shape contours:
# extract contours from the image cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = imutils.grab_contours(cnts) # 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)
On Lines 23-25 we’re finding shape contours in the thresh
image.
From there, we draw the contours on the input image (Lines 28 and 29).
To learn more about contours, please see Finding Shapes in Images using Python and OpenCV and the contours tag archives. I also discuss contours and other image processing fundamentals in my book, Practical Python and OpenCV + Case Studies.
Then we assemble and put text on the image (Lines 32-34). The text contains the total number of shapes.
Lastly, we make use of our --output
image path argument to write the image to disk with cv2.imwrite
(Line 37).
Let’s execute the command with our two arguments:
$ python shape_counter.py --input input_01.png --output output_01.png
If you inspect your working directory, you’ll notice the output_01.png
image is now present:
Let’s execute the command again with different arguments:
$ python shape_counter.py --input input_02.png --output output_02.png
Again, you’ll notice a new output file in your directory: output_02.png
.
Now, take a step back. and consider what we have done from a command line arguments perspective.
What we did here is use one script with no changes and provided it different arguments. The --input
argument contained the path/filename of the input image and likewise with --output
.
The concept is extremely simple and I hope this has cleared up how to use command line arguments. Before we wrap up this post, let’s take a look at what not to do.
How to not parse command line arguments
Every now and then I see readers who attempt to modify the code itself to accept command line arguments.
A great example of how not to parse command line arguments can be seen by starting with our command line arguments on Lines 6-12 from the previous section:
# 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())
I’ve seen readers mistakenly try to update the argument parsing code to include the actual path to the input image:
# construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-i", "C:\example\input_image.png", required=True, help="path to input image") ap.add_argument("-o", "C:\example\output_image.png", required=True, help="path to output image") args = vars(ap.parse_args())
Or in a list ditch effort, try to use the help
parameter to include the file path:
# construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-i", "--input", required=True, help="/home/pi/my_input.png") ap.add_argument("-o", "--output", required=True, help="/home/pi/output_image.png") args = vars(ap.parse_args())
Keep in mind that the code itself does not need to be updated.
Take a second to open up your terminal, navigate to where your code lives, and then execute the script, making sure to provide the command line arguments.
I want to share another “gotcha” with you. Sometimes on this blog, my command line argument flags have a ‘-‘ (dash) in them such as --features-db
. It’s a little bit confusing and a bit of a nuissance that when grabbing the value contained by the argument, you need to use a ‘_’ (underscore).
This is demonstrated in this excerpt from the PyImageSearch Gurus course Content Based Image Retrieval Module:
# construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-d", "--dataset", required=True, help="Path to the directory of indexed images") ap.add_argument("-f", "--features-db", required=True, help="Path to the features database") ap.add_argument("-c", "--codebook", required=True, help="Path to the codebook") ap.add_argument("-o", "--output", required=True, help="Path to output directory") args = vars(ap.parse_args()) # load the codebook and open the features database vocab = pickle.loads(open(args["codebook"], "rb").read()) featuresDB = h5py.File(args["features_db"], mode="r") print("[INFO] starting distance computations...")
Notice on the highlighted lines that I’ve defined the argument as --features-db
(with a dash), but I reference it by args["features_db"]
(with an underscore). This is because the argparse
Python library replaces dashes with underscores during the parsing.
You can do it!
Command line arguments may take some practice or getting used to if you are new to working in a terminal — but I have faith in you!
Don’t get discouraged.
Take your time.
And keep practicing.
Before you know it, you’ll have mastered command line arguments — take the time now to invest in your education and this valuable skill!
Setting your command line arguments via an IDE
From time to time I receive emails and blog comments asking how to run Python scripts from within their IDE.
About 90% of the time the question is similar to:
Hi Adrian,
Help! I can’t get the code to run.
How can I run the code from your blog post with PyCharm?
PyCharm and other IDEs are great tools that are packed with features. I love PyCharm and I use it daily.
While it’s possible to run a script with command line arguments in an IDE, I do not advise it.
You really need to get comfortable with the command line when you’re doing development. It actually saves time to use the terminal rather than to click around the GUI of your IDE and set up the arguments.
In an effort to serve the community, I’m providing two screencasts that were captured by David Hoffman — you’ll hear my familiar voice as I recorded the voiceover to explain the steps.
Step 1 is to grab the code to this tutorial (or another one on this blog if you are so inclined) via the “Downloads” section.
As you’ll see in the video, David downloaded the code into a folder residing on his desktop. Once you’ve put the download somewhere convenient for you, press play and follow along:
David and I took it a step further to demonstrate that you can select a virtual environment for your PyCharm run configuration.
The second example in this blog post requires that you have OpenCV installed.
Since David was a student of the PyImageSearch Gurus course, he used his gurus
virtual environment. You can select an environment on your own system that you’ve set up with OpenCV. If you don’t have such an environment, you should follow my OpenCV installation instructions.
To watch the more advanced PyCharm + Run Configuration which uses command line arguments, click play below.
As you can see, both examples are relatively easy. PyCharm provides a convenient way to test code without using your terminal. I’m still partial to using the terminal as I’ve always got it open anyway for the many tasks that PyCharm can’t handle.
Did your virtual environment not show up in PyCharm?
Don’t worry!
You might just need to browse to the ~/.virtualenvs
folder and select your interpreter (all from within the PyCharm Run Configuration screen).
What's next? I recommend PyImageSearch University.
30+ total classes • 39h 44m video • Last updated: 12/2021
★★★★★ 4.84 (128 Ratings) • 3,000+ Students Enrolled
I strongly believe that if you had the right teacher you could master computer vision and deep learning.
Do you think learning computer vision and deep learning has to be time-consuming, overwhelming, and complicated? Or has to involve complex mathematics and equations? Or requires a degree in computer science?
That’s not the case.
All you need to master computer vision and deep learning is for someone to explain things to you in simple, intuitive terms. And that’s exactly what I do. My mission is to change education and how complex Artificial Intelligence topics are taught.
If you're serious about learning computer vision, your next stop should be PyImageSearch University, the most comprehensive computer vision, deep learning, and OpenCV course online today. Here you’ll learn how to successfully and confidently apply computer vision to your work, research, and projects. Join me in computer vision mastery.
Inside PyImageSearch University you'll find:
- ✓ 30+ courses on essential computer vision, deep learning, and OpenCV topics
- ✓ 30+ Certificates of Completion
- ✓ 39h 44m on-demand video
- ✓ Brand new courses released every month, ensuring you can keep up with state-of-the-art techniques
- ✓ Pre-configured Jupyter Notebooks in Google Colab
- ✓ Run all code examples in your web browser — works on Windows, macOS, and Linux (no dev environment configuration required!)
- ✓ Access to centralized code repos for all 500+ tutorials on PyImageSearch
- ✓ Easy one-click downloads for code, datasets, pre-trained models, etc.
- ✓ Access on mobile, laptop, desktop, etc.
Summary
In today’s blog post you learned how to utilize command line arguments using the Python programming language.
You also learned how to utilize the argparse
library for parsing command line arguments.
At this point you should now understand the fundamentals of command line arguments and the role they play in software, programs, and scripts.
As you saw, when used correctly, you do not have to modify any code to work with command line arguments — just open up a terminal, navigate to your Python script, and execute it!
Additionally, if you are new to the Python programming language and want to level up your Python coding skills, I have put together a list of my favorite resources to learn Python as a guest post on the SimpleProgrammer blog — be sure to give it a look.
If you enjoyed today’s blog post be sure enter your email address in the form below to be notified when future blog posts are published!
Download the Source Code and FREE 17-page Resource Guide
Enter your email address below to get a .zip of the code and a FREE 17-page Resource Guide on Computer Vision, OpenCV, and Deep Learning. Inside you'll find my hand-picked tutorials, books, courses, and libraries to help you master CV and DL!
I usually comment out the args part and assign permanent absolute path links before even testing the code. Because I know i am going to get stuck at some point where the problem will not be with the code but with some path that i am suppose to give with one back slash… no no.. with “\\”(because it Windows).. and still no luck…
But now… i hope i get a hang of it. Thank you for this very useful post!
You can absolutely hardcode paths if you wish. If you’re using a Jupyter Notebook this is also advisable. For any other readers interesting in trying this approach I would suggest taking this code:
And replacing it with:
This will replace the command line arguments with a hardcoded dictionary. The downside is that you will need to (1) ensure your keys to the dictionary matchup throughout the code and (2) you will need to edit the code whenever you want to change the file paths (which pretty much gets us back to why we are using command line arguments in the first place).
Also, if you are using Windows or want the code to be cross-platform with file paths, make sure you use “os.path.sep.join”.
Hi Adrian, nice tutorial you compose here.
I have a follow up question regarding hard-cording the argparse.
The original lines are as follow,
parser.add_argument(“–data_dir”, type=str, default=”/data/somefolder”)
args = parser.parse_args()
Intended function
if not os.path.exists(args.output_dir):
os.makedirs(args.output_dir)
Following your suggestion on hardcode path, I can simplified the code into the following
args = {“data_dir”: “/data//somefolder”}
However, making this changes make the code run with error. May I know what I am missing.
Thanks in advance
You need to change
args.output_dir
toargs["data_dir"]
.thank you for your post very much. It is very useful for my study.
Hello Sir,
Do you have tutorials for windows?
Sorry, no. I do not support Windows on the PyImageSearch blog.
I think it’s will be good if you explain findContours arguments and hierarchy.
Can you please ?
I’ve explained the cv2.findContours function in a good many PyImageSearch posts. Here’s a link to all posts that mention the function. It’s a good many as I frequently use the function in posts. I would suggest starting there. The OpenCV docs has a good explanation of the hierarchy as well.
I sometimes use sys.argv when the arguments are really simple: e.g. if I need exactly two arguments for my script.
argparse is actually really powerful and using it for simple cases seems, to me, like swatting mosquitoes with a sheet of plywood. I especially like its ability to expand arguments from a file into the command line.
I used to use sys.argv as well but I found that the code would become too hard to maintain. At first you think you only need one argument. Then it turns out you need another. And another. And another. It snowballs. I prefer to use argparse out of the gate. It gives me the flexibility of extendible code from a command line perspective.
I think the other issue to address is that if you already know how to use sys.argv you can likely transition over to argparse without any real issue. If you don’t have experience with command line arguments in general I think you would struggle either way. I use argparse here on PyImageSearch which is why I went with it instead of sys.argv. I hope that makes sense and thank you for the comment!
Hi Adrian,
I have just read your email, and then go to this blog post.
I see this topic is very useful. I will try to learn how to adapt with this style of coding.
In fact, I didn’t face some problems with Argument Parser since I comment out these part.
And change your code by my way. I had filled out all input path directly. ^^”
Anyway, I really appreciate your help and your sharing. For a beginner like me, I can’t go around this huge world without some guideline from some experts like you.
If you prefer to hardcode arguments and file paths, that’s totally acceptable. However, I would encourage you, as well as other readers, to learn how to use the command line arguments as you’ll find them to be quite powerful 🙂
Hey! Thanks for posting such nice examples! I’ve been a long time reader of your blog. Now I may have something to contribute back. Do you know Docopt? I find it much friendlier to use than argparse, although the latter has kind of become a standard.
Many thanks again!
P. S. Why is this comment box so laggy? The letters appear seconds after I type them on the phone.
I haven’t heard of/used Docopt before, I’ll check it out. For this particular post, and PyImageSearch in general, I wanted to keep as much of the Python-based functionality actually inside the standard Python distribution. We require enough external libraries (NumPy, SciPy, OpenCV) that I didn’t want to add another library on top of it all so I use argparse in the posts. That said, I totally agree there are better command line argument libraries (click, for example, is my favorite).
As for the comment box, I’m not sure why that would be. Perhaps it’s the browser on your phone?
As usual, an excellent post.
Here are two additional examples of useful argparse idoms taken from some of my code, that illustrate a couple useful features.
First is the boolean setting, useful for options that are normally false, but you want to occasionally turn on. Using a boolean option is preferable to using an option that you pass in a “1” to to enable. For example,
parser.add_argument(“-t”, “–test”, help=”turn on test mode”, action=”store_true”)
Since you create a dictionary from the output of ap.parse_args(), use it like this:
if args[“test”]: # was -t/–test used?
(If you had used the output of ap.parse_args() directly, the code would look like this:
args = ap.parse_args()
if args.text: # was -t/–test used?
)
The other example is often used in a similar fashion, but lets you use it multiple times to provide more than one level of that option.
parser.add_argument(“-v”, “–verbose”, help=”Verbose mode, may be specified multiple times for additional verbosity”, action=”count”, default=0)
Use it like this:
if args[“verbose”]: # was -v/–verbose used?
or
if args[“verbose”] > 1: # is extra verbosity needed?
or
if args[“verbose”] > 5: # give them everything possible
I hope these notes are helpful to someone.
Excellent use cases, thanks so much for sharing Tony!
A very useful article as always Adrian, one thing I must to say that OOP in Python is too creepy for me, maybe some OOP tutorial in near future?
OOP in Python can be a bit tricky depending on what you are doing. We don’t use too much OOP programming here, other than defining classes and methods inside them. We don’t do much in terms of inheritance which is where OOP gets tricky with Python. I would recommend you take a look at the list of resources I recommend to learn Python here as well as Dan Bader’s blog which includes many Python tutorials (his book is also really good).
wow, just this morning I was pondering a way to wrapper commands and command line options (maybe via TCL/TK) either in a gui (graphical) or a text based gui (like sidekick [an olde TSR program for DOS] there that ages me!) the idea being reflection back from the help and man pages into a much better and forgiving way of configuring commands. With trenchant examples of phased intensity. The current (and has been so for 50 years) way of man pages calls to mind a passive aggressive crypto-sadistic neckbeard (of any sex) with a trunk full of BDSM porgs under their desk, squealing in unrelenting agony; you can never be smart enough to work out just wtf is going on. This is what powershell was meant to be, sort of a modern riff on DCL, a very consistent command language indeed. Alas the aforementioned dread neckbeards of unices of yore skull dragged it through the laboratories on the island of Dr Moreau, hitting all the ugly on way through… In actual fact, I think I shall return to a pet project of mine (no porg abuse intended) – the best IDE I ever used was ms Word, just the ability to use styles alone was worth it. And it got me away from the ridiculous old ASCII spaghetti paradigm that has cursed terminals and compilers since before dot …
I think you might be interested in Gooey which does exactly that.
Yesterday i found information about this article. Now, I see it from my email. Oh my god. Thank so much!
I’m glad you found it helpful! 🙂
Very nice article. I have a minimal knowledge of Python compared to R but a goal is to boost my knowledge of Python and deep dive into the world of machine learning with Python. However, I just need to pull myself away from R. In other words, I need to diversify my knowledge of machine learning with other languages.
Greetings. As always your articles are amazing! I was experimenting with Pycharm and found that it’s possible to enter command line arguments within Pycharm’s Terminal window. I used the simple name example you provided and ran the code via Pycharm’s Terminal window (directory of .py code:/ python –name somename) and it worked like a “charm.” I was also able to make new changes to the code and run the code via Terminal and the output with changes was instant. This method seemed a little faster without having to go in the configuration menu and changing the parameters. Hope this makes sense and once again thank you for your excellent articles and sharing you knowledge with all of us.
Awesome, thank you for sharing, Rex!
Hi Adrian
Im quite new in Python. I installed already imutils with sudo pip install imutils code. But I’m taking this kind of Error;
Traceback (most recent call last):
File “shape_counter.py”, line 32, in
import imutils
ImportError: No module named ‘imutils’.
I am using raspberry pi3.
Thank you so much!
Are you using a Python virtual environment as we typically do here on the PyImageSearch blog? If so, you need to:
1. Access the Python virtual environment
2. Install “imutils” via “pip”
Using “sudo” will install the package into the system Python virtual environment which you do not want. Try this instead:
Hello Adrian,
I am trying to run a python script from the command line following your tutorial. My script load an image, perform some opencv methods and then write a csv file with some lines of text. The issue is that I am receiving an error:
[Errno 13] Permission denied: ‘D:\\aaa’
I am running the python script from the command line and from my conda environment. If I run the script (without the argparse) from Spyder everything works just fine. I guess there is a problem with permission to write a file ina directory. I am in Windows. Can you tell me how to solve this?
Sorry Adrian,
my mistake. I forgot to add “.csv” to the file path,
SOrry
Congrats on resolving the issue, Guido!
i installed imutils and when i execute the code give that error
import imutils
ImportError: No module named ‘imutils’.
Are you using Python virtual environments? If so, make sure you install it into the proper virtual environment:
You should also double-check that imutils was installed using the
pip freeze
command.how use argparse command line arguments on jupyter notenook. plz can any one help me for this problem.
I address this question in the very first comment on this post. See my reply to Mansoor Nasir on March 12, 2018.
I tried the same code and without any error I ran it still for different shapes inside an image I am getting counts as only 1 as it is bounding the rectangular boundary of the image
Hey Arun — it sounds like you were not able segment the background from your foreground. Use the “cv2.imshow” function to visualize “thresh”, the thresholded image.
i am not done …how can i remove that error which u have presented
Which error are you referring to?
Hi,
I am not able to install argparse due to dependencies.
Can you give a walkaround for that?
The “argparse” library is already installed by default with Python. You do not need to install it yourself.
Hello Adrian,
I have been forced into using Jupyter on Microsoft’s Azure system. Jupyter won’t accept parsing of the command line, and anyway in this system, there isn’t an accessible command line. I was trying to find some way of incorporating the command line into the file prior to the execution of the argparse? Using Azure is like using batch processing like in the 1970’s. The power of the artificial intelligence packages are amazing however. I would like to be able to submit code that is intact rather than modify code for each execution.
Have you any ideas.
I should add that even for code I am writing, I have adopted your design of program and like it, having become familiar with it.
Hey Murray — see the very first comment on this post where I discuss how I would replace the argument parsing code with a simple Python dictionary.
Yesterday i found information about this article. Now, I see it from my email. Thank so much!
I’m glad you found it helpful Daily! 🙂
How can I give the path to model file after –model like –model C:\Users\… or after –prototxt C:\Users\… on the command line?
I know its kind of a silly question because I can just copy those files in the same directory and just write –model file_name but still can we pass path after the argument on cli.
Hey there Jay, this tutorial actually covers exactly how to supply command line arguments. You would open up a prompt, navigate to your script, and then supply the command line arguments to the script. Go through the exercises in this blog post and execute them on your own machine. Get a little bit of practice using these examples and I’m sure you’ll be up to speed in no time 🙂
error: (-215) scn == 3 || scn == 4 in function cvtColor
Hey how can i overcome this error.
Your path to your input image is incorrect and cv2.imread is returning “None”. Double-check your input pahth.
i know this post is mainly about argparse and the code about work well with this library but i this experiment i have problem mainly with two line of code
line 15 – image = cv2.imread(args[“input”]), to check this one specific line, i change it to
image=cv2.imread(“D:\Nova\command-line-arguments\input_01.png”)
and i found that imread can’t change the pic to arraye
line 37 – cv2.imwrite(args[“output”], image), once i change the image file, i work with new image but at last point that it should write it again with some text on it, return with a false comment without trackback error
has any body else same experience and what was your solution.
thank you so much
I am going through the same problem. Please help me out.
Thank you for this tutorial. I am using Pycharm and was struggling with the same problem. Your post solved half of my problem but half is as it is. which is how to pass predefined weights as the argument which is the in .DAT format. Any help would be appreciated.
Thank you
Hello sir, Im just starting learn your tutorial and code
Can you help me, how I can use command line arguments for argparse if I use anaconda(spyder) in windows10?
Because I try to use command with anaconda prompt and didnt work
Thanks.
I personally don’t use Sypder, but since it’s an IDE, you can likely set the command line arguments via the IDE. I demonstrate how to do sow ith PyCharm here.. Either way, I recommend you become familiar with the command line and execute the code via the command line.
Hello Adrian, Thanks for this nice tutorial. I have recently started to follow your post in this blog. While implementing this tutorial i have this following error:
AttributeError: module ‘imutils’ has no attribute ‘grab_contours’
could you give me some direction about solving this error?
p.s: I have installed imutils inside virtual environment without sudo command
You need to upgrade your imutils version:
$ pip install --upgrade imutils
Thats weird, I’ve also upgrade imutils on the VE with no luck on grab_countours.
Don’t know how useful this would be as it looks very naive but just in case anyone cares:
I was going crazy having the latest imutils (0.5.3) and yet I couldn’t use grab_contours.
The problem seems to be that I also had a project file called “imutils.py” so PyCharm was looking for the grab_contours on this one instead of the package. A simple refactoring of my own file did the trick.
Ah yes, that would certainly cause an issue! Congrats on resolving the problem.
segnet_train.py: error: the following arguments are required: -m/–model
How can I solve it?
Your error can be resolved by reading this tutorial on command line arguments and how they work.
Hi Adrian
I’m trying to implement the code in Google Colab. I have been trying to resolve the systemexit : 2 error, which occurs when an argument is required.
I have implemented the same code which you used to explain this blog on argument parser. kindly help me resolve this issue.
Convert the argument parsing to a dictionary via this tutorial.
Thanks Alot brother. This topic was really needed and at last i was able to understand this… Lots of respect from Pakistan <3
Thanks Bilal, I’m glad the tutorial helped!
This tutorial is great for beginners! Thanks a lot.
Besides, I’d like to share something which may be helpful to ROS users. I discovered this problem when going through your blog.
If you have installed ROS (a well-known Robot Operating System originated from Stanford), it is highly likely that you will encounter some issues when you are trying to run the programs successfully, because ROS has automatically created the PATH of its own OpenCV version.
Here is an example of error message after you tried to “import cv2″(For ROS Kinetic):
ImportError: /opt/ros/kinetic/lib/python2.7/dist-packages/cv2.so: undefined symbol: PyCObject_Type
To solve this, we need to insert these codes before import cv2:
import sys
sys.path.remove(‘/opt/ros/kinetic/lib/python2.7/dist-packages’)
I don’t know whether anyone else has posted this. ROS is definitely a powerful tool for people who work in the field of Robotics, but always causes some annoying problems…I hope more beginners like me can notice this solution.
(I’m an Asian student and maybe my English is not so well…but thank you again for your attention)
Thanks for sharing!
hello sir,
at the line 20 of the code above
thresh = cv2.threshold(blurres,60,255,cv2.THRESH_BINARY)[1]
what does that [1] actually mean, without it placing there i’m getting an error. but after putting it there the error is gone, please help.
The “cv2.threshold” function returns a 2-tuple of:
1. The threshold value used (very useful if performing automatic thresholding using Otsu’s method)
2. The thresholded image itself
As next steps, I would suggest you read Practical Python and OpenCV so you can learn the fundamentals of the OpenCV library.