Python, argparse, and command line arguments

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.

Looking for the source code to this post?
Jump right to the downloads section.

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
usage: [-h] -i IMAGE -p PROTOTXT -m MODEL [-c CONFIDENCE] error: the following arguments are required: -i/–image, -p/–prototxt, -m/–model


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

Figure 1: My terminal screen is used to run a Python script with command line arguments.

First, let’s make a new script, naming it :

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):

Notice how I specified all three of:

  1. The executable ( python )
  2. Our Python script file ( )
  3. 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  script:

  1. 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).
  2. Step 2: Open a terminal and change directory to where the zip lives.
  3. Step 3: Unzip.
  4. Step 4: Change directory again, this time into the new directory that was just extracted.
  5. Step 5: Activate your virtual environment with the workon  command. Example: workon cv  or workon py3cv4 (depending on the name of your environment). If you are using my Pre-configured Raspbian .img, it is recommended to use the source  command with the script in the home folder. Example: source ~/  or source ~/ . For OpenVINO it is especially important to use the source  command as it loads a handful of environment variables in addition to activating your virtual environment.
  6. 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:

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.

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

Figure 2: Using the argparse Python package you can easily parse command line arguments in the terminal/command line.

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  and start coding:

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:

  1. Convert the image  to grayscale.
  2. Blur the grayscale image.
  3. Threshold the blurred  image.

We’re ready to find and draw shape contours:

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:

If you inspect your working directory, you’ll notice the output_01.png  image is now present:

Figure 3: Shapes have been counted with our Python + OpenCV script which takes in command line arguments.

Let’s execute the command again with different arguments:

Again, you’ll notice a new output file in your directory: output_02.png .

Figure 4: Three shapes have been detected with OpenCV and Python by simply changing the command line arguments.

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:

I’ve seen readers mistakenly try to update the argument parsing code to include the actual path to the input image:

Or in a list ditch effort, try to use the help  parameter to include the file path:

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:

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).

So, what’s next?

I hope this tutorial helped you get up to speed with command line arguments and how to use them. Chances are, if you’re reading this tutorial you may be a bit new to the Python programming language and the OpenCV library.

If so, that’s totally okay!

I was in the same boat as you when I first started working with Python years and years ago. I would spend hours trying new examples, running code, re-coding the entire script, re-running it, and trying to reproduce the results.

As you might imagine, I’m a big fan of learning by example, so a good next step would be to have some fun and read this blog post on detecting cats in images/videos. This tutorial is meant to be very hands-on and demonstrate how you can (quickly) build a Python + OpenCV application to detect the presence of cats in images. It also includes command line arguments so you can practice your skills from this post.

And if you’re really interested in leveling-up your computer vision skills, you should definitely check out my book, Practical Python and OpenCV + Case Studies. My book not only covers the basics of computer vision and image processing, but also teaches you how to solve real-world computer vision problems including face detection in images and video streamsobject tracking in video, and handwriting recognition.

Thousands of PyImageSearch readers have used Practical Python and OpenCV to learn both the fundamentals of the Python programming language and the OpenCV library at the same time. Each and every line of code in the book is thoroughly documented, ensuring you understand exactly what each piece of code is doing.

To learn more about my book, and how it can help you on your path to Python + OpenCV mastery, just click here.


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!


If you would like to download the code and images used in this post, please enter your email address in the form below. Not only will you get a .zip of the code, I’ll also send you 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! Sound good? If so, enter your email address and I’ll send you the code immediately!

, , ,

65 Responses to Python, argparse, and command line arguments

  1. Mansoor Nasir March 12, 2018 at 10:54 am #

    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!

    • Adrian Rosebrock March 12, 2018 at 11:31 am #

      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”.

      • Rpb June 15, 2018 at 11:45 am #

        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):

        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

        • Adrian Rosebrock June 15, 2018 at 11:58 am #

          You need to change args.output_dir to args["data_dir"].

      • Trung Tin Tran August 5, 2019 at 4:24 am #

        thank you for your post very much. It is very useful for my study.

      • Jeffrey December 5, 2019 at 10:51 pm #

        Hello Sir,

        Do you have tutorials for windows?

  2. Ahmadreza March 12, 2018 at 11:39 am #

    I think it’s will be good if you explain findContours arguments and hierarchy.

    Can you please ?

    • Adrian Rosebrock March 12, 2018 at 3:10 pm #

      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.

  3. David Bonn March 12, 2018 at 12:13 pm #

    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.

    • Adrian Rosebrock March 12, 2018 at 3:12 pm #

      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!

  4. Đăng March 12, 2018 at 12:17 pm #

    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.

    • Adrian Rosebrock March 12, 2018 at 3:13 pm #

      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 🙂

  5. Cipri_tom March 12, 2018 at 3:46 pm #

    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.

    • Adrian Rosebrock March 12, 2018 at 4:15 pm #

      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?

  6. Tony March 12, 2018 at 5:23 pm #

    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?


    if args[“verbose”] > 1: # is extra verbosity needed?


    if args[“verbose”] > 5: # give them everything possible

    I hope these notes are helpful to someone.

    • Adrian Rosebrock March 12, 2018 at 6:00 pm #

      Excellent use cases, thanks so much for sharing Tony!

  7. Thanh March 12, 2018 at 9:22 pm #

    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?

    • Adrian Rosebrock March 13, 2018 at 6:36 am #

      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).

  8. Ian Walker March 12, 2018 at 11:57 pm #

    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 …

    • Adrian Rosebrock March 13, 2018 at 6:37 am #

      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)

      I think you might be interested in Gooey which does exactly that.

  9. CTVR March 13, 2018 at 2:17 am #

    Yesterday i found information about this article. Now, I see it from my email. Oh my god. Thank so much!

    • Adrian Rosebrock March 13, 2018 at 6:38 am #

      I’m glad you found it helpful! 🙂

  10. John W March 13, 2018 at 8:46 am #

    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.

  11. Rex Haw March 18, 2018 at 11:28 am #

    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.

    • Adrian Rosebrock March 19, 2018 at 5:10 pm #

      Awesome, thank you for sharing, Rex!

  12. Azizhan March 26, 2018 at 4:44 pm #

    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 “”, line 32, in
    import imutils
    ImportError: No module named ‘imutils’.

    I am using raspberry pi3.
    Thank you so much!

    • Adrian Rosebrock March 27, 2018 at 6:13 am #

      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:

  13. Guido April 6, 2018 at 1:25 pm #

    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?

    • Guido April 6, 2018 at 1:51 pm #

      Sorry Adrian,
      my mistake. I forgot to add “.csv” to the file path,

      • Adrian Rosebrock April 10, 2018 at 12:47 pm #

        Congrats on resolving the issue, Guido!

  14. Ahmad April 9, 2018 at 2:27 am #

    i installed imutils and when i execute the code give that error

    import imutils
    ImportError: No module named ‘imutils’.

    • Adrian Rosebrock April 10, 2018 at 12:14 pm #

      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.

  15. mohd parvez May 10, 2018 at 2:38 am #

    how use argparse command line arguments on jupyter notenook. plz can any one help me for this problem.

    • Adrian Rosebrock May 14, 2018 at 12:22 pm #

      I address this question in the very first comment on this post. See my reply to Mansoor Nasir on March 12, 2018.

  16. arun June 2, 2018 at 8:21 am #

    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

    • Adrian Rosebrock June 5, 2018 at 8:06 am #

      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.

  17. sizzle July 3, 2018 at 4:31 am #

    i am not done …how can i remove that error which u have presented

    • Adrian Rosebrock July 3, 2018 at 7:11 am #

      Which error are you referring to?

  18. Syed July 8, 2018 at 1:23 am #

    I am not able to install argparse due to dependencies.

    Can you give a walkaround for that?

    • Adrian Rosebrock July 10, 2018 at 8:39 am #

      The “argparse” library is already installed by default with Python. You do not need to install it yourself.

  19. Murray Wood July 10, 2018 at 3:58 am #

    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.

    • Adrian Rosebrock July 10, 2018 at 8:12 am #

      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.

  20. Daily Ponsel October 2, 2018 at 3:11 am #

    Yesterday i found information about this article. Now, I see it from my email. Thank so much!

    • Adrian Rosebrock October 8, 2018 at 10:39 am #

      I’m glad you found it helpful Daily! 🙂

  21. Jay October 11, 2018 at 11:39 am #

    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.

    • Adrian Rosebrock October 12, 2018 at 8:59 am #

      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 🙂

  22. Anant Soni October 11, 2018 at 12:59 pm #

    error: (-215) scn == 3 || scn == 4 in function cvtColor
    Hey how can i overcome this error.

    • Adrian Rosebrock October 12, 2018 at 8:57 am #

      Your path to your input image is incorrect and cv2.imread is returning “None”. Double-check your input pahth.

  23. Ehsan October 12, 2018 at 5:08 am #

    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
    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

    • Roma Vardiyani June 25, 2019 at 8:46 am #

      I am going through the same problem. Please help me out.

  24. Navjot October 24, 2018 at 11:03 pm #

    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

  25. Alfian November 9, 2018 at 3:37 pm #

    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


    • Adrian Rosebrock November 10, 2018 at 9:54 am #

      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.

  26. Saifullah Al Mujahid December 5, 2018 at 9:12 am #

    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

    • Adrian Rosebrock December 6, 2018 at 9:38 am #

      You need to upgrade your imutils version:

      $ pip install --upgrade imutils

      • Savvas September 14, 2019 at 3:51 pm #

        Thats weird, I’ve also upgrade imutils on the VE with no luck on grab_countours.

    • Savvas September 15, 2019 at 8:17 am #

      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 “” 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.

      • Adrian Rosebrock September 19, 2019 at 10:07 am #

        Ah yes, that would certainly cause an issue! Congrats on resolving the problem.

  27. zyx January 10, 2019 at 8:17 pm # error: the following arguments are required: -m/–model

    How can I solve it?

  28. praveen May 23, 2019 at 12:26 am #

    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.

    • Adrian Rosebrock May 23, 2019 at 9:28 am #

      Convert the argument parsing to a dictionary via this tutorial.

  29. Bilal Imran December 11, 2019 at 3:43 pm #

    Thanks Alot brother. This topic was really needed and at last i was able to understand this… Lots of respect from Pakistan <3

    • Adrian Rosebrock December 12, 2019 at 10:05 am #

      Thanks Bilal, I’m glad the tutorial helped!

Before you leave a comment...

Hey, Adrian here, author of the PyImageSearch blog. I'd love to hear from you, but before you submit a comment, please follow these guidelines:

  1. If you have a question, read the comments first. You should also search this page (i.e., ctrl + f) for keywords related to your question. It's likely that I have already addressed your question in the comments.
  2. If you are copying and pasting code/terminal output, please don't. Reviewing another programmers’ code is a very time consuming and tedious task, and due to the volume of emails and contact requests I receive, I simply cannot do it.
  3. Be respectful of the space. I put a lot of my own personal time into creating these free weekly tutorials. On average, each tutorial takes me 15-20 hours to put together. I love offering these guides to you and I take pride in the content I create. Therefore, I will not approve comments that include large code blocks/terminal output as it destroys the formatting of the page. Kindly be respectful of this space.
  4. Be patient. I receive 200+ comments and emails per day. Due to spam, and my desire to personally answer as many questions as I can, I hand moderate all new comments (typically once per week). I try to answer as many questions as I can, but I'm only one person. Please don't be offended if I cannot get to your question
  5. Do you need priority support? Consider purchasing one of my books and courses. I place customer questions and emails in a separate, special priority queue and answer them first. If you are a customer of mine you will receive a guaranteed response from me. If there's any time left over, I focus on the community at large and attempt to answer as many of those questions as I possibly can.

Thank you for keeping these guidelines in mind before submitting your comment.

Leave a Reply