NameError : face_section not defined

import cv2
import numpy as np

cap = cv2.VideoCapture(0)
skip = 0
face_data =[]
dataset_path ="./data/"

face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades+“haarcascade_frontalface_alt.xml”)

while True:
ret,frame = cap.read()
gray_frame = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)

if ret == False:
    continue

faces = face_cascade.detectMultiScale(frame,1.3,5)
faces = sorted(faces,key=lambda f:f[2]*f[3])
for face in faces[-1:]:
    x,y,w,h = face
    cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,255),2)
    offset = 10
    face_section = frame[y-offset:y+h+offset,x-offset:x+w+offset]
    face_section= cv2.resize(face_section,(100,100))
    skip = skip + 1
    if skip % 10 == 0:
        face_data.append(face_section)
        print(len(face_data))
cv2.imshow("Frame",frame)
cv2.imshow("Face Section",face_section)

key_pressed = cv2.waitKey(1) & 0xFF
if key_pressed == ord('q'):
    break

cap.release()
cv2.destroyAllWindows()

Sir the above program is not getting executed with the error that the face sedtion is not defined

and when I remove “cv2.imshow('face Section”,face_section) " from the program it get executed but the program is not getting terminated successfully, Every time i have to restart the command prompt,after each execution.

please Help

hey @naman_kr_301 ,

This might be because you are declaring face section inside your for loop. So face section will only be declared of there are some faces detected and hence , when there are no faces detected , means no for loop and no declaration of face selection variable hence it gives error.

It is because you are running an infinite loop which can be breaked like this. For this you need to add a break command or something.

I hope this would have cleared your doubt.
Thank You and Happy Learning :slightly_smiling_face:.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.