使用ArgParse,获取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)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
让我们将代码减少到MWVE:
使用此问题运行的
是
,您滥用了第二个参数,不是
flag
+描述,而是只有标志,然后将其用作密钥。您应该这样做:在上述代码中替换
python test.py -i input.jpg -o output.jpg
现在给出:您还可以设置在
args
明确,例如:它将给出
Let's reduce your code to a MWVE:
running this with
gives
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:Replacing that in above code and running with
python test.py -i input.jpg -o output.jpg
gives now:You can also set the name of the field used in
args
explicitly, e.g.:which will give
如果不存在参数,则只能获得
keyError
。当我收到此错误时,我有信心我拥有
键/参数
,因此我继续一次又一次地运行代码,而无需查看代码并继续重复获得KeyError。我检查了我的代码,事实证明我以某种方式删除了该特定的参数
错误。You'd only get
keyError
if the argument doesn't exist.When I received this error, I was confident that I had the
key/argument
so I kept on running my code again and again without reviewing the code and kept on getting keyError repeatedly. I checked my code and it turns out that I had somehow removed that particularargument
mistakenly.