Error: the following arguments are required: -i/--image

Error: the following arguments are required: -i/--image

我对argparse的含义不是很了解。当我用这个代码测试时,它总是这个错误:

usage: test1.py [-h] -i IMAGE
test1.py: error: the following arguments are required: -i/--image

这是我的代码:

# (1) import the necessary packages
import argparse
import imutils
import cv2

# (2) construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True, help="path to the input image")
args = vars(ap.parse_args())

# (3) load the image, convert it to grayscale, blur it slightly,
# and threshold it
image = cv2.imread(args["image"])
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)    cv2.imwrite('C:\Users\Hoang Cao Chuyen\Downloads\shapes.png', gray)

blurred = cv2.GaussianBlur(gray, (5,5), 0)
cv2.imwrite('C:\Users\Hoang Cao Chuyen\Downloads\shapes.png', blurred)

thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1]
cv2.imwrite('C:\Users\Hoang Cao Chuyen\Downloads\shapes.png', thresh)

# find contours in the thresholded image
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if imutils.is_cv2() else cnts[1]

这行代码添加了一个必需的标志-i--image:

ap.add_argument("-i", "--image", required=True, help="path to the input image")

这意味着脚本希望您使用参数指定 -i--image 标志,如下所示:

python test1.py --image C:\path\to\image.png

如果您希望图像路径成为位置参数,您可以将该行代码更改为:

ap.add_argument("image", help="path to the input image")

然后你可以这样调用你的脚本:

python test1.py C:\path\to\image.png

相关文档:https://docs.python.org/3/library/argparse.html#name-or-flags