Card image cap
Python/ Feb 5, 2019 ()

Arguments Parser In Python

You most probably came across this issue when you deal with data inputs, where you want to test your code on a different image or input without changing the code everytime! 😕

Let's consider this simple example where we'll use OpenCV library to read and show an image using imread and imshow methods respectively:

# fileName: argparse.py
import cv2

image = cv2.imread("path/to/the/image.png")
cv2.imshow("image", image)
cv2.waitKey()

{success} Now, to run the code simply type in the terminal:

python argparse.py

However, if you want to change your input image, then you have to refer back to your code and change the image path again and again each time.

To avoid this, we will use argparse module in python to do so.

# fileName: argparse.py
import argparse
import cv2

argumentParser = argparse.ArgumentParser()
argumentParser.add_argument("--image", required=True, help="Path to image.")
arguments = vars(argumentParser.parse_args())

image = cv2.imread(arguments["image"])
cv2.imshow("image", image)
cv2.waitKey()

First, we import argparse module and cv2 library, then, we created an object argumentParser from ArgumentParser class. After that, we called the method add_argument which accepts three arguments:

  • The first one is the terminal alias.
  • The second one is the required option.
  • The last one is the help message.

Finally, we called vars() function to extract the assigned argument and put the result into python dictionary.

At the end, we replaced the hard-coded path with the path that sent from the terminal arguments["image"], i.e. to run the code:

python argparse.py --image data/images/image1.png

Now, if you want to change the image path, all you have to do is to change it from the terminal.

python argparse.py --image data/images/newImage.png

That's great!, but let's take it a step further and create a dedicated class to handle this functionality instead of remembering all this funky code :D


Instead of creating it from scratch, we will consume the one we created earlier on your github account: ArgumentsParser

Download or clone the repo and put the file ArgumentsParser.py in your project's directory.

To make usage of the class:

  • step 1: import the class
from ArgumentsParser import ArgumentsParser
  • step 2: Define your arguments
args = [
    {
        "name" : "image",
        "help" : "Path to image.",
        "required" : True
    }
]
  • step 3: create the object and call setup method
argumentsParser = ArgumentsParser()
data = argumentsParser.setup(args)

Putting everything together:

# fileName: argparse.py
from ArgumentsParser import ArgumentsParser
import cv2

args = [
    {
        "name" : "image",
        "help" : "Path to image.",
        "required" : True
    }
]

argumentsParser = ArgumentsParser()
arguments = argumentsParser.setup(args)

image = cv2.imread(arguments["image"])
cv2.imshow("image", image)
cv2.waitKey()
  • step 4: run from terminal:
python argparse.py --image data/images/image1.png

Finally, we will give you a quick excersie where you have to modify the existing ArgumentsParser class we wrote to have a dynamic getter, example: arguments.image instead of arguments["image"].

Good luck 😎