Python人脸识别代码出现UnboundLocalError报错求助
UnboundLocalError: local variable "ID" referenced before assignment Issue Let's break down why you're hitting this error and fix it step by step:
Root Cause
The error stems from Python's variable scoping rules. In your identify function, you have lines that assign values to Id (Id = str(b) and Id = "Unknown"). When Python sees an assignment to a variable inside a function, it automatically treats that variable as a local variable for the entire function scope.
But you try to check if(Id == a and conf<65) before assigning any value to the local Id—hence the error: you're referencing a local variable that hasn't been initialized yet.
Solution 1: Use Global Variables
Since Id and conf are defined outside the identify function, you need to explicitly tell Python you want to use the global versions of these variables inside the function. Add a global declaration at the start of the function:
def identify(number): global Id, conf # Declare we're using the global variables sht = gc.open("Test") wks3 = sht.worksheet("NAMES") b = wks3.acell('B'+str(number)).value a = wks3.acell('A'+str(number)).value if(Id == a and conf<65): print(Id, conf) Id = str(b) Time = time.ctime() hour(number) elif(conf>64): print(conf) Id = "Unknown"
Also, fix the syntax error in your prediction line—you're missing a closing parenthesis:
Id, conf = recognizer.predict(gray[y:y+h,x:x+w]) # Added closing )
Solution 2: Pass Variables as Parameters (Better Practice)
While global variables work, it's cleaner to avoid them by passing Id and conf as arguments to the identify function. This makes your code more modular and easier to debug:
def identify(number, current_id, current_conf): sht = gc.open("Test") wks3 = sht.worksheet("NAMES") b = wks3.acell('B'+str(number)).value a = wks3.acell('A'+str(number)).value updated_id = current_id if(current_id == a and current_conf < 65): print(current_id, current_conf) updated_id = str(b) Time = time.ctime() hour(number) elif(current_conf > 64): print(current_conf) updated_id = "Unknown" return updated_id # Call the function like this: Id, conf = recognizer.predict(gray[y:y+h,x:x+w]) for m in range(2,100): Id = identify(m, Id, conf)
This approach avoids relying on global state, which is generally considered better practice for maintainable code.
内容的提问来源于stack exchange,提问作者Michael O' Driscoll




