我创建了一个面部识别和识别程序。它根据我给它的训练文件夹来识别面孔。但是,它还会显示未知面孔的名称(不在训练文件夹中的面孔)。我应该进行哪些更改,以使未知面孔不会显示错误的名称?
这是面部训练代码: 导入操作系统 导入cv2 将numpy导入为np 从PIL导入图片 进口泡菜
BASE_DIR = os.path.dirname(os.path.abspath(__file__ ))
image_dir = os.path.join(BASE_DIR, "images")
face_cascade = cv2.CascadeClassifier("D:\\Python\\Pycharm Projects\\face\\haarcascade_frontalface_default.xml")
recognizer = cv2.face.LBPHFaceRecognizer_create()
current_id = 0
label_ids ={}
x_train = []
y_labels = []
for root, dirs, files, in os.walk(image_dir):
for file in files:
if file.endswith("png") or file.endswith("jpg"):
path = os.path.join(root, file)
label = os.path.basename(os.path.dirname(path))
print(label, path)
if label in label_ids:
pass
else:
label_ids[label] = current_id
current_id +=1
id_= label_ids[label]
print(label_ids)
pil_image = Image.open(path).convert("L")
size = (550, 550)
final_image = pil_image.resize(size, Image.ANTIALIAS)
image_array = np.array(final_image, "uint8" )
print(image_array)
faces = face_cascade.detectMultiScale(image_array, scaleFactor=1.27, minNeighbors=5)
for (x, y, w, h) in faces:
roi = image_array[y:y+h, x:x+w]
x_train.append(roi)
y_labels.append(id_)
print(y_labels)
print(x_train)
with open("labels.pickle", 'wb') as f:
pickle.dump(label_ids, f)
recognizer.train(x_train, np.array(y_labels))
recognizer.save("trainer.yml ")
这是面部识别代码: 导入cv2 将numpy导入为np 进口泡菜
face_cascade = cv2.CascadeClassifier("D:\\Python\\Pycharm Projects\\face\\haarcascade_frontalface_default.xml")
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read("trainer.yml")
labels = {"person_name": 1}
with open("labels.pickle", 'rb') as f:
og_labels = pickle.load(f)
labels = {v:k for k, v in og_labels.items()}
cap = cv2.VideoCapture(0)
while True:
rect, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.27, minNeighbors=5)
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 3)
roi_gray = gray[y:y + h, x:x + h]
roi_color = frame[y:y + h, x:x + h]
id_, conf = recognizer.predict(roi_gray)
if conf>=10:
# print(labels[id_])
font = cv2.FONT_HERSHEY_SIMPLEX
name = labels[id_]
color = (255, 255, 255)
stroke = 2
cv2.putText(frame, name, (x, y), font, 1, color, stroke, cv2.LINE_AA)
img_item = "myImage.png"
cv2.imwrite(img_item, roi_gray)
cv2.imshow("frame", frame)
if cv2.waitKey(20) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()