Unable to detect face and eye with OpenCV in Python

浪尽此生 提交于 2019-12-25 09:16:00

问题


This code is to detect face and eyes using webcam but getting this error

Traceback (most recent call last):  
  File "D:/Acads/7.1 Sem/BTP/FaceDetect-master/6.py", line 28, in <module>  
    eyes = eyeCascade.detectMultiScale(roi)  
NameError: name 'roi' is not defined

but when i use this code do detect faces and eyes in a image its working properly without any error

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()

回答1:


I think it is just a problem of indentation.

roi is out of scope when you go out of the faces loop.

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)


来源:https://stackoverflow.com/questions/39368307/unable-to-detect-face-and-eye-with-opencv-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!