无法使用Python中的OpenCV检测面部和眼睛

时间:2016-09-07 11:10:27

标签: python opencv face-detection nameerror eye-detection

此代码用于检测使用网络摄像头的面部和眼睛,但会出现此错误

import matplotlib
import matplotlib.pyplot as plt
import cv2
import sys
import numpy as np
import os

faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eyeCascade= cv2.CascadeClassifier('haarcascade_eye.xml')

video_capture = cv2.VideoCapture(0)

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

    faces = faceCascade.detectMultiScale(frame)

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

    eyes = eyeCascade.detectMultiScale(roi)
    for (ex,ey,ew,eh) in eyes:
        cv2.rectangle(roi,(ex,ey),(ex+ew,ey+eh), 255, 2)

    cv2.imshow('Video', frame)

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

video_capture.release()
cv2.destroyAllWindows()

但是当我使用此代码时,检测图像中的面部和眼睛,它正常工作,没有任何错误

float

1 个答案:

答案 0 :(得分:2)

我认为这只是缩进问题。

当你离开roi循环时,

faces超出了范围。

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

    # eyes detection runs for each face
    eyes = eyeCascade.detectMultiScale(roi)
    for (ex,ey,ew,eh) in eyes:
        cv2.rectangle(roi,(ex,ey),(ex+ew,ey+eh), 255, 2)