Iam having trouble with Python command “ cascPath = sys.argv[1] ” i get error IndexError: list index out of range

Iam having trouble with Python command “ cascPath = sys.argv[1] ” i get error IndexError: list index out of range

我正在使用 Raspberry Pi 3 Model B,安装了 Raspbian、opencv 2.x 和 Python 3。

我想访问我的 USB 网络摄像头并用它拍照。我发现了大量代码,但 none 都没有用。我找到了一个更好的,但是当我 运行 命令

cascPath = sys.argv[1]

我收到错误

Traceback (most recent call last):

File "/home/pi/test.py", line 4, in

cascPath = sys.argv[1]

IndexError: list index out of range

我只需要访问我的网络摄像头来拍照。

我正在使用以下代码:

import cv2

import sys

cascPath = sys.argv[1]

faceCascade = cv2.CascadeClassifier(cascPath)

video_capture = cv2.VideoCapture(0)

while True:

    # Capture frame-by-frame
    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.cv.CV_HAAR_SCALE_IMAGE
    )

    # Draw a rectangle around the faces
    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)

    # Display the resulting frame
    cv2.imshow('Video', frame)

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

#When everything is done, release the capture
video_capture.release()

此代码尝试识别图像上的人脸,sys.argv[1] 期望您 运行 脚本包含 XML 文件的路径以帮助识别人脸。

如果您不想识别人脸,那么您只需要将此代码显示在来自摄像头的监视器视频上。

import cv2

import sys

video_capture = cv2.VideoCapture(0)

while True:

    # Capture frame-by-frame
    ret, frame = video_capture.read()

    # Display the resulting frame
    cv2.imshow('Video', frame)

    # exit if you press key `q`
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

#When everything is done, release the capture
video_capture.release()

或者用这个来保存图像

import cv2

video_capture = cv2.VideoCapture(0)

# Capture frame
ret, frame = video_capture.read()

# Write frame in file
cv2.imwrite('image.jpg', frame)

# When everything is done, release the capture
video_capture.release()