【问题标题】:IndexError: list index out of range: sys.argv[1] out of rangeIndexError:列表索引超出范围:sys.argv[1] 超出范围
【发布时间】:2020-06-12 21:19:33
【问题描述】:

我正在尝试运行以下代码,但一直遇到错误,
“IndexError: list index out of range”

我知道这与 sys.argv[1]; 相关。我有一个基本的想法,这个函数是从命令行调用我的项目的第一行 - 当我尝试从 CMD 运行项目时,我遇到了同样的错误。

代码:

import cv2
import sys

cascadePath = sys.argv[1]
faceCascade = cv2.CascadeClassifier(cascadePath)

video_capture = cv2.VideoCapture(0)


while True:
    ret, frame = video_capture.read()

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    faces = faceCascade.detectMultiScale(
        gray,
        scaleFactor=1.1,
        minNeighbors=5,
        minSize=(30, 30),
        flags=cv2.CASCADE_SCALE_IMAGE
    )

    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)

    cv2.imshow('Video', frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

video_capture.release()
cv2.destroyAllWindows()

错误:

Traceback (most recent call last):
  File "C:/Users/Niku/PycharmProjects/FaceDetection/FaceDetection.py", line 4, in <module>
    cascadePath = sys.argv[1]
IndexError: list index out of range

任何见解或建议将不胜感激!

【问题讨论】:

  • 你是如何运行脚本的?
  • 你是如何调用你的程序的?
  • 另外,您可以通过将cascadePath = sys.argv[1] 临时替换为print(sys.argv) 来检查sys.argv 列表中的内容
  • @Sushanth - 我使用 PyCharm 作为 IDE;我已经尝试从我的 IDE 运行它,也尝试从 IDE 的终端运行并尝试从 CMD 启动。
  • @Ronald 我使用 PyCharm 作为 IDE;我已经尝试从我的 IDE 运行它,也尝试从 IDE 的终端运行并尝试从 CMD 启动。

标签: python command-line-arguments


【解决方案1】:

sys.argv[1] 此代码需要第一个命令行参数。如果缺少,那么您将遇到此错误。 示例:

some_script.py

import sys
sys.argv[1]

如果您不提供myfirst_agr(如下所示),那么它会抛出您所看到的索引错误。

some_script.py myfirst_agr

更多例子是here

【讨论】:

  • 感谢简单的分解和参考文档,非常有帮助!当使用 myfirst_arg 从 CMD 运行代码时,我遇到了另一个错误:faces = faceCascade.detectMultiScale( cv2.error: OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\objdetect\src\cascadedetect.cpp:1689: error: (-215:Assertion failed) !empty() in function 'cv::CascadeClassifier::detectMultiScale 任何见解将不胜感激。
  • @Karanvir.S.G,这是完全不同的问题。你可以为此提出另一个问题。
  • @Karanvir.S.G,如果回答对您有帮助,您能接受吗?
猜你喜欢
  • 2016-08-12
  • 1970-01-01
  • 2017-11-12
  • 2017-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多