【问题标题】:Syntax for ap.add_argument()ap.add_argument() 的语法
【发布时间】:2025-12-17 21:25:02
【问题描述】:

我是 OpenCV 的新手。我正在使用 anaconda spyder 控制台编写 Python 代码。我在这里采取了代码形式 (https://www.pyimagesearch.com/2014/08/25/4-point-opencv-getperspective-transform-example/) 让我印象深刻的代码是:

# USAGE
# python transform_example.py --image images/example_01.png --coords "[(73, 239), (356, 117), (475, 265), (187, 443)]"
# python transform_example.py --image images/example_02.png --coords "[(101, 185), (393, 151), (479, 323), (187, 441)]"
# python transform_example.py --image images/example_03.png --coords "[(63, 242), (291, 110), (361, 252), (78, 386)]"

# import the necessary packages
from pyimagesearch.transform import four_point_transform
import numpy as np
import argparse
import cv2

# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", help = "path to the image file")
ap.add_argument("-c", "--coords",
    help = "comma seperated list of source points")
args = vars(ap.parse_args())

# load the image and grab the source coordinates (i.e. the list of
# of (x, y) points)
# NOTE: using the 'eval' function is bad form, but for this example
# let's just roll with it -- in future posts I'll show you how to
# automatically determine the coordinates without pre-supplying them
image = cv2.imread(args["image"])
pts = np.array(eval(args["coords"]), dtype = "float32")

# apply the four point tranform to obtain a "birds eye view" of
# the image
warped = four_point_transform(image, pts)

# show the original and warped images
cv2.imshow("Original", image)
cv2.imshow("Warped", warped)
cv2.waitKey(0)

在第 1 行。 13 - 17 有人能准确说出发生了什么。我知道我需要获取图像,获取纸张的坐标(这些行是为此目的)但我无法获取图像文件。

【问题讨论】:

  • 你必须在终端上运行代码python filename.py image_path coordinates
  • 当我尝试:python transform_example.py images/example_01.png "[(73, 239), (356, 117), (475, 265), (187, 443)]" 它给了我的错误“无效语法”
  • 参数需要以选项名称为前缀。试试python transform_example.py --image images/example_01.png --coords "[(73, 239), (356, 117), (475, 265), (187, 443)]"。更多关于 argparse 的信息:docs.python.org/3/library/argparse.html

标签: python python-2.7 opencv


【解决方案1】:

在提供的链接中,使用可选参数解析参数,即参数必须以add_argument()中提到的字符串开头。

所以在你的情况下,你有:

ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", help = "path to the image file")
ap.add_argument("-c", "--coords", help = "comma seperated list of source points")
args = vars(ap.parse_args())

通知"--image""--coords"。这些是可选参数,必须在终端中执行代码之前提及这些字符串。

所以在终端上输入这个:

python transform_example.py --image images/example_01.png --coords "[(73, 239), (356, 117), (475, 265), (187, 443)]"

有关参数解析及其各种方式的更多详细信息,请参阅THIS PAGE

【讨论】: