[英]Error while writing code for face recognition using haarcascade classifier
import cv2
import numpy as np
#Init camera
cap = cv2.VideoCapture(0)
#Face Detection using haarcascade File
face_cascade = cv2.CascadeClassifier('Anaconda3\Lib\site-packages\cv2\data\haarcascade_frontalface_alt.xml')
skip = 0
face_data = []
#dataset_path = ('./Face Recognition Data')
while True:
ret,frame = cap.read()
if ret == False:
continue
faces = face_cascade.detectMultiScale(frame,1.3,5)
#The next line of code is written to only store the largest face in the window frame
faces = sorted(faces,key = lambda f: f[2]*f[3])
#start sorting from the last face since the last face is the largest in terms of area(w*h)
for face in faces[-1:] :
x,y,w,h = face
cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,255),2)
#extract the required face or the region of the interest
#Refers to adding an extra 10 pixels on all the sides of the required extracted face
offset = 10
#By default face slicing is done in (y,x) manner
face_section = frame[y-offset:y+h+offset,x-offset:x+w+offset]
face_section = cv2.resize(face_section,(100,100))
if skip%10==0 : #Store every 10th frame
face_data.append(face_section)
print(len(face_data)) #number of faces captured so far
cv2.imshow("Video Frame",frame)
cv2.imshow("Face section frame",face_section)
key_pressed = cv2.waitKey(1) & 0xFF
if key_pressed == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
After running the program, it says that face_section variable is not defined.运行程序后,它说没有定义 face_section 变量。 Please help
请帮忙
You have more than one face_section
.你有不止一个
face_section
。 If you need them outside of your for loop you may do like this:如果您在 for 循环之外需要它们,您可以这样做:
face_section_list = [] # Define a new empty list!
#start sorting from the last face since the last face is the largest in terms of area(w*h)
for face in faces[-1:] :
x,y,w,h = face
cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,255),2)
#extract the required face or the region of the interest
#Refers to adding an extra 10 pixels on all the sides of the required extracted face
offset = 10
#By default face slicing is done in (y,x) manner
face_section = frame[y-offset:y+h+offset,x-offset:x+w+offset]
face_section = cv2.resize(face_section,(100,100))
face_section_list.append(face_section) # Append EVERY face!
if skip%10==0 : #Store every 10th frame
face_data.append(face_section)
print(len(face_data)) #number of faces captured so far
And then outside, print every face in order (or do whatever you need to do):然后在外面,按顺序打印每张脸(或做任何你需要做的事情):
for im in face_section_list:
cv2.imshow("Face section frame",im)
cv2.waitKey(0) # Zero means "wait until a key is pressed"
I've wrote a lot of code for face detection and recognition that you may find helpful, have a look .我写了很多用于人脸检测和识别的代码,您可能会发现它们有帮助,请查看。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.