pythonopencvnameerror

How can a variable be not defined when it's literally defined above?


haar_cascade=cv.CascadeClassifier(r'C:\Users\User\Desktop\Project-III\faces.xml')
people = ['ABC', 'XYZ','PQR']

file = open(r'C:\Users\User\Desktop\face.txt', 'a')

capture = cv.VideoCapture(1)
while True:
    isTrue,frame=capture.read()
    haar_cascade=cv.CascadeClassifier('faces.xml')

    for (x,y,w,h) in faces_rect:
        faces_roi=gray[y:y+h, x:x+h]
        label, confidence = face_recognizer.predict(faces_roi)
        print(f'Label={people[label]} with a confidence of {confidence}')
        

    file.write(people[label])
    file.write(str(confidence))
    file.write(str(datetime.datetime.now()))
    file.write("\n")

    if cv.waitKey(20) & 0xFF==ord('d'):
        break

cv.imshow('Detected faces', frame)
file.close()
cv.waitKey(0)

I get:

Exception has occurred: NameError
name 'label' is not defined
  File "C:\Users\Parth\Desktop\Project-III\face_recog_video_PROTOTYPE.py", line 41, in <module>
    file.write(people[label])
                      ^^^^^
NameError: name 'label' is not defined

How can label be not defined when it's literally defined above?

The code was running perfectly fine few minutes ago.


Solution

  • 
        for (x,y,w,h) in faces_rect:
            faces_roi=gray[y:y+h, x:x+h]
            label, confidence = face_recognizer.predict(faces_roi)
            print(f'Label={people[label]} with a confidence of {confidence}')
            for i in range (0,cnt):
              cv.putText(frame, str(people[label]),(i*400,40), cv.FONT_HERSHEY_COMPLEX, 1.0, (0,255,0), thickness=2)
            cv.rectangle(frame,(x,y), (x+w, y+h), (0,255,0), thickness=2)
            cv.imshow('video',frame)
    
        file.write(people[label])
        file.write(str(confidence))
        file.write(str(datetime.datetime.now()))
        file.write("\n")
    

    label is defined inside the for loop, it could be that there are no faces_rect and label ends up not being defined.

    Add print statements and check.

    Maybe you wanted to indent the last part of the code?

    
        for (x,y,w,h) in faces_rect:
            faces_roi=gray[y:y+h, x:x+h]
            label, confidence = face_recognizer.predict(faces_roi)
            print(f'Label={people[label]} with a confidence of {confidence}')
            for i in range (0,cnt):
              cv.putText(frame, str(people[label]),(i*400,40), cv.FONT_HERSHEY_COMPLEX, 1.0, (0,255,0), thickness=2)
            cv.rectangle(frame,(x,y), (x+w, y+h), (0,255,0), thickness=2)
            cv.imshow('video',frame)
    
            file.write(people[label])
            file.write(str(confidence))
            file.write(str(datetime.datetime.now()))
            file.write("\n")