1.加载已知身份人脸数据
#载入已经人脸数据
def load_known_faces(dirname):
for img in fnmatch.filter(os.listdir(dirname), '*.jpg'):
print('load image:',img)
image = facer.load_image_file(dirname + img)
en_img = facer.face_encodings(image)
if len(en_img) > 0:
known_face_encodings.append(en_img[0])
known_face_names.append(img[:-4])
在这里,使用了几个公众人物的图像作为载入数据:
Andrew:
范冰冰(程序中使用fanbb代替)
def detect_and_authorization(know_faces_dir,image_for_testing):
#加载已经身份的人脸数据
load_known_faces(know_faces_dir)
#加载测试人脸数据
test_img = facer.load_image_file(image_for_testing)
test_img = cv2.cvtColor(test_img,cv2.COLOR_BGR2RGB)
cv2.imshow('test_img',test_img)
#检测脸部数据
faces = facer.face_locations(test_img)
encod_faces = facer.face_encodings(test_img, faces)
#把测试脸部数据与已经加载的人脸数据比较,从实现身份识别
for (top, right, bottom, left), encod_face in zip(faces, encod_faces):
#比较脸部数据
matches = facer.compare_faces(known_face_encodings, encod_face)
#通过比较结果获取身份名称
if True in matches:
foundindex = matches.index(True)
name = known_face_names[foundindex]
else:
name = "Unknown"
#绘制身份名称
cv2.rectangle(test_img, (left, top), (right, bottom), (0, 255, 0), 2)
cv2.rectangle(test_img, (left, bottom - 35), (right, bottom), (0, 255, 0), cv2.FILLED)
cv2.putText(test_img, name, (left + 6, bottom - 6), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1.0, (255, 255, 255), 1)
cv2.imshow("Face ID", test_img)
cv2.waitKey(0)
cv2.destroyAllWindows()