为什么我收到此错误: TypeError: 'Namespace' object is not subscriptable

Ahm*_*ari 12 python

我面临 argparse 库的问题。

我有encodings.pickle 文件,并且我按照下面的代码来识别演员,但加载嵌入似乎不起作用。

这是代码:

ap = argparse.ArgumentParser()
ap.add_argument("-e", "--encodings", required=True,
                help="path to serialized db of facial encodings")
ap.add_argument("-i", "--image", required=True,
                help="path to input image")
ap.add_argument("-d", "--detection-method", type=str, default="cnn",
                help="face detection model to use: either `hog` or `cnn`")
ap.add_argument("-fnn", "--fast-nn", action="store_true")
args = parser.parse_args('')
print(args)

# load the known faces and embeddings
print("[INFO] loading encodings...")
data = pickle.loads(open(args["encodings"], "rb").read())
Run Code Online (Sandbox Code Playgroud)

源代码可以在这里找到。

H. *_*oss 7

您收到此错误是因为该parse_args()方法返回包含已解析参数的命名空间。

当打印该方法的结果时,您将看到创建的命名空间:Namespace(encodings='encoding', image='image', detection_method='cnn', fast_nn=False)

为了访问参数,您应该使用点符号(即args.encodingsargs.image

修改后的代码:

ap = argparse.ArgumentParser()
ap.add_argument("-e", "--encodings", required=True,
                help="path to serialized db of facial encodings")
ap.add_argument("-i", "--image", required=True,
                help="path to input image")
ap.add_argument("-d", "--detection-method", type=str, default="cnn",
                help="face detection model to use: either `hog` or `cnn`")
ap.add_argument("-fnn", "--fast-nn", action="store_true")
args = parser.parse_args()
print(args)

# load the known faces and embeddings
print("[INFO] loading encodings...")
data = pickle.loads(open(args.encodings, "rb").read())
Run Code Online (Sandbox Code Playgroud)