Python 使用haarcascade分类器编写人脸识别代码时出错
运行程序后,它表示未定义face_section变量。Python 使用haarcascade分类器编写人脸识别代码时出错,python,opencv,Python,Opencv,运行程序后,它表示未定义face_section变量。 请帮助您有多个face\u部分。如果在for循环之外需要它们,可以这样做: 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\da
请帮助您有多个
face\u部分
。如果在for循环之外需要它们,可以这样做:
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()
然后在外面,按顺序打印每张脸(或者做任何你需要做的事情):
我已经编写了很多人脸检测和识别代码,您可能会发现这些代码很有用。在
for
循环中定义了face\u部分
变量。如果你得到一个错误,说变量没有定义,那么循环可能没有工作/做你期望的事情,但是如何改变for循环以获得期望的结果?我从来没有使用过cv2库,所以我不能像这样判断出什么是错误的。但这就是编程,编写一些代码,然后调查它是否符合预期。这里的第一步可能是向循环中添加一个print
调用,或者打印faces
的长度,以查看faces
列表是否为空,循环是否首先没有被调用
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
for im in face_section_list:
cv2.imshow("Face section frame",im)
cv2.waitKey(0) # Zero means "wait until a key is pressed"