如何修改Python KNN人脸识别代码,识别未注册人脸显示Unknown
解决KNN人脸识别显示“Unknown”的问题
原代码无法识别未注册人脸的核心问题是:没有设置置信度阈值,且判断逻辑无效(len(LABELS) >= 0永远成立)。以下是修改后的完整代码及关键改动说明:
修改后的代码
from sklearn.neighbors import KNeighborsClassifier import cv2 import pickle import numpy as np import os import csv import time from datetime import datetime video = cv2.VideoCapture(0) facedetect = cv2.CascadeClassifier('data/haarcascade_frontalface_default.xml') with open('data/names.pkl', 'rb') as w: LABELS = pickle.load(w) with open('data/faces_data.pkl', 'rb') as f: FACES = pickle.load(f) print('Shape of Faces matrix --> ', FACES.shape) # 初始化KNN分类器 knn = KNeighborsClassifier(n_neighbors=5) knn.fit(FACES, LABELS) imgBackground = None COL_NAMES = ['NAME', 'TIME'] # 设置置信度阈值,可根据实际场景调整 CONFIDENCE_THRESHOLD = 0.6 while True: ret, frame = video.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = facedetect.detectMultiScale(gray, 1.3, 5) for (x, y, w, h) in faces: crop_img = frame[y:y+h, x:x+w, :] resized_img = cv2.resize(crop_img, (50,50)).flatten().reshape(1,-1) # 获取预测结果及对应概率 output = knn.predict(resized_img) prob_scores = knn.predict_proba(resized_img) max_prob = np.max(prob_scores) ts = time.time() date = datetime.fromtimestamp(ts).strftime("%d-%m-%Y") timestamp = datetime.fromtimestamp(ts).strftime("%H:%M:%S") exist = os.path.isfile("Attendance/Attendance_" + date + ".csv") # 基于概率判断是否为未知人脸 if max_prob >= CONFIDENCE_THRESHOLD: recognized_name = output[0] else: recognized_name = "Unknown" attendance = [recognized_name, str(timestamp)] # 绘制人脸框和识别结果 cv2.rectangle(frame, (x,y), (x+w, y+h), (0,0,255), 1) cv2.rectangle(frame,(x,y),(x+w,y+h),(50,50,255),2) cv2.rectangle(frame,(x,y-40),(x+w,y),(50,50,255),-1) cv2.putText(frame, recognized_name, (x,y-15), cv2.FONT_HERSHEY_COMPLEX, 1, (255,255,255), 1) cv2.rectangle(frame, (x,y), (x+w, y+h), (50,50,255), 1) if imgBackground is not None and not imgBackground.empty(): imgBackground[162:162 + frame.shape[0], 55:55 + frame.shape[1]] = frame cv2.imshow("Frame", imgBackground) else: cv2.imshow("Frame", frame) k = cv2.waitKey(1) if k == ord('o'): if exist: with open("Attendance/Attendance_" + date + ".csv", "+a") as csvfile: writer = csv.writer(csvfile) writer.writerow(attendance) else: with open("Attendance/Attendance_" + date + ".csv", "+a") as csvfile: writer = csv.writer(csvfile) writer.writerow(COL_NAMES) writer.writerow(attendance) if k == ord('q'): break video.release() cv2.destroyAllWindows()
关键改动说明
- 添加
CONFIDENCE_THRESHOLD置信度阈值:通过predict_proba获取每个类别的预测概率,取最高概率与阈值对比,低于阈值则判定为未知人脸。 - 替换无效判断逻辑:移除
len(LABELS) >=0的无效判断,改为基于概率的有效判定逻辑。 - 更新显示文本:将
cv2.putText的显示内容从output[0]改为recognized_name,确保界面显示最终判定结果。 - 阈值可调:可根据实际场景调整
CONFIDENCE_THRESHOLD数值——误判较多时提高阈值,漏判较多时降低阈值。
内容的提问来源于stack exchange,提问作者Reungrit Saejiw
相关产品推荐
相关产品推荐

