'using argparse, getting KeyError

import argparse
import imutils
import cv2 as cv

ap = argparse.ArgumentParser()

ap.add_argument("-i", "--input image", required=True, help='Input the Image')
ap.add_argument("-o", "--output image", required=True, help='Output the Image')

args = vars(ap.parse_args())

img = cv.imread(args["input"])

gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
gaussian = cv.GaussianBlur(gray, (5, 5), 0)

threshold = cv.threshold(gaussian, 60, 255, cv.THRESH_BINARY)[1]

contr = cv.findContours(threshold.copy(), cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
contr = imutils.grab_contours(contr)

for c in contr:
    cv.drawContours(img, [c], -1, (0, 0, 255), 2)

txt = 'Yes I Found {} the Shapes in Image'.format(len(contr))
textPut = cv.putText(img, txt, (10, 20), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)

cv.imshow(args["output"], img)


Solution 1:[1]

Let's reduce your code to a MWVE:

#test.py
import argparse

ap = argparse.ArgumentParser()

ap.add_argument("-i", "--input image", required=True, help='Input the Image')
ap.add_argument("-o", "--output image", required=True, help='Output the Image')

args = vars(ap.parse_args())
print(args)

running this with

python test.py -i input.jpg -o output.jpg

gives

{'input image': 'input.jpg', 'output image': 'output.jpg'}

The issue is that you misused the second argument, it is not a flag + description, but only the flag, which is then used as the key. You should do it like this:

ap.add_argument("-i", "--input", required=True, help='Input the Image')
ap.add_argument("-o", "--output", required=True, help='Output the Image')

Replacing that in above code and running with python test.py -i input.jpg -o output.jpg gives now:

{'input': 'input.jpg', 'output': 'output.jpg'}

You can also set the name of the field used in args explicitly, e.g.:

ap.add_argument("-i", "--input", required=True, help='Input the Image', dest="in")
ap.add_argument("-o", "--output", required=True, help='Output the Image', dest="out")

which will give

{'in': 'input.jpg', 'out': 'output.jpg'}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 FlyingTeller