Unable to detect face and eye with OpenCV in Python
<p>This code is to detect face and eyes using webcam but getting this error</p>

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

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

<pre><code>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) &amp; 0xFF == ord('q'):
        break

video_capture.release()
cv2.destroyAllWindows()
</code></pre>

<p>I think it is just a problem of indentation.</p>

<p><code>roi</code> is out of scope when you go out of the <code>faces</code> loop.</p>

<pre><code>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)
</code></pre>

python opencv face-detection nameerror eye-detection