Search code examples
pythonlocal-variables

Getting an error accessing variables defined in a loop: cannot access local variable 'x' where it is not associated with a value


My code:

import numpy as np import cv2

cap = cv2.VideoCapture(0) face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml')

def eye_detector(): while True: ret, frame = cap.read()   

 gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    for (x, y, w, h) in faces:
      roi_gray = gray[y:y + w, x:x + w]
      roi_color = frame[y:y + h, x:x + w]
      eyes = eye_cascade.detectMultiScale(roi_gray, 1.3, 5 )
      
      for (ex, ey, ew, eh) in eyes:
          cv2.rectangle(roi_color, (ex, ey), (ex + ew, ey + eh), (0, 255, 0), 5)
    
    cv2.imshow('frame', frame)    
    if cv2.waitKey(1)==ord('q'):
        break

    elif x == 210 or y== 140:
        cv2.destroyWindow("frame")
        continue

    elif ey == 30 or ex == 50:
        cv2.destroyWindow("frame")
        continue
    
cap.release()
cv2.destroyAllWindows()


import project1_module1 
import project1_module2 
project1_module2.eye_detector() 

The error I get:

"cannot access local variable 'x' where it is not associated with a value"

I tried to redefine value inside the if() and for() loop but it didn't work. My expected result is that the camera has turned on and ended when the x, y, ex, and my values have scanned those values (lines 26-32 in project1_module2.py). But the error had occurred. (The code written above is project1_module2.py)


Solution

  • All the variables you defined in the for loops control statements (x, y, w, h as well as, ex, ey, ew, eh in the inner loop) are only initialized if the loop executes at least one time.

    In the case of the outer loop - if faces is empty because no faces were detected, x, y, w, h will not be defined.

    Same goes to ex, ey, ew, eh in the inner loop if no eyes were detected (even if if there were any faces).

    The meaning of the error you get is that you attempt to check the value of x although it was never initialized, probably because no faces were detected in the image.

    You will get the same error for checking y (and also for checking ey and ex if your code will get to execute it).

    You can solve it in 2 ways:

    1. Change your conditions to first check that the respective collection is not empty. There are several ways to check if a list is empty in Python, one of them being using len:
      if len(faces) > 0 and (x == 210 or y == 140) :
      and respectively:
      if len(eyes) > 0 and (ey == 30 or ex == 50) :
      Note that this will work because and is short circuited and so if e.g. faces is empty the conditions for x and y will not be evaluated.
    2. Initialize x,y etc. to some default value like -1 before the loops. This will ensure there are intialized even if the loops don't execute.

    I personally prefer the first option.