函数首先循环遍历已训练好的人脸模型。
对每个模型,执行多次扫描以提高准确性。
在每次扫描中,使用摄像头读取图像,并将其转换为灰度图像。
使用人脸识别器检测图像中的人脸。
对于每张检测到的人脸,通过分类器的预测函数获取标签和置信度。
如果置信度低于一定阈值(confidence),即可识别已训练的对象,则输出姓名和置信度信息。
根据不同的置信度范围,确定是否可以识别该人脸。
最后,根据平均识别结果决定是否认定为合法用户。如果有大部分扫描结果是可行的,则返回相应的标签;否则返回0表示无法识别。
def scan_face():
for i in range(Total_face_num):
i += 1
yml = str(i) + ".yml"
print("\n本次:" + yml)
recognizer.read(yml)
ave_poss = 0
for times in range(10):
times += 1
cur_poss = 0
global success
global img
global system_state_lock
while system_state_lock == 2:
print("\r刷脸被录入面容阻塞", end="")
pass
success, img = camera.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 识别人脸
faces = face_cascade.detectMultiScale(
gray,
scaleFactor=1.2,
minNeighbors=5,
minSize=(int(W_size), int(H_size))
)
for (x, y, w, h) in faces:
while system_state_lock == 2:
print("\r刷脸被录入面容阻塞", end="")
pass
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)# 这里调用Cv2中的rectangle函数 在人脸周围画一个矩形
# 调用分类器的预测函数,接收返回值标签和置信度
idnum, confidence = recognizer.predict(gray[y:y + h, x:x + w])
conf = confidence
if confidence < 100:
if idnum in id_dict:
user_name = id_dict[idnum]
else:
user_name = "Untagged user:" + str(idnum)
confidence = round(100 - confidence)
else: # 无法识别此对象,那么就开始训练
user_name = "unknown"
font = cv2.FONT_HERSHEY_SIMPLEX # 加载一个字体用于输出识别对象的信息
cv2.putText(img, str(user_name), (x + 5, y - 5), font, 1, (0, 0, 255), 1)
cv2.putText(img, str(confidence), (x + 5, y + h - 5), font, 1, (0, 0, 0), 1)
print("conf=" + str(conf), end="\t")
if 15 > conf > 0:
cur_poss = 1
elif 60 > conf > 35:
cur_poss = 1
else:
cur_poss = 0
k = cv2.waitKey(1)
if k == 27:
cv2.destroyAllWindows()
break
ave_poss += cur_poss
if ave_poss >= 5:
return i
return 0