深度学习人脸识别
采用深度学习的模型实现人脸识别
测试图picture1
picture2
识别图test
模型:
shape_predictor_68_face_landmarks.dat
dlib_face_recognition_resnet_model_v1.dat模型
##代码
import numpy as np
import cv2
import dlib
import matplotlib.pyplot as plt
def show_image(image,title):
img_RGB=image[:,:,::-1]
plt.title(title)
plt.imshow(img_RGB)
plt.axis("off")
def compare_faces(face_encoding,test_encoding):
return list(np.linalg.norm(np.array(face_encoding)-np.array(test_encoding),axis=1))
def encoder_face(image,detector,predictor,encoder,upsample=1,jet=1):
faces=detector(image,upsample)
faces_keypoints=[predictor(image,face) for face in faces]
return [np.array(encoder.compute_face_descriptor(image,face_keypoint,jet))for face_keypoint in faces_keypoints]
def compare_faces_order(face_encoding,test_encoding,names):
distance=list(np.linalg.norm(np.array(face_encoding)-np.array(test_encoding),axis=1))
return zip(*sorted(zip(distance,names)))
def plot_rectangle(image,faces,name):
for face in faces:
cv2.putText(image, name, (face.left(), face.top()-30), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 255), 2)
cv2.rectangle(image,(face.left(),face.top()),(face.right(),face.bottom()),(255,0,0),4)
return image
def main():
img1=cv2.imread("picture1.jpg")
img2=cv2.imread("picture2.jpg")
test=cv2.imread("test.jpg")
img1=img1[:,:,::-1]
img2=img2[:,:,::-1]
test=test[:,:,::-1]
img_names=["picture1","picture2"]
detector=dlib.get_frontal_face_detector()
predictor=dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
encoder=dlib.face_recognition_model_v1("dlib_face_recognition_resnet_model_v1.dat")
img1_128=encoder_face(img1,detector,predictor,encoder)[0]
img2_128=encoder_face(img2,detector,predictor,encoder)[0]
test_128=encoder_face(test,detector,predictor,encoder)[0]
zong=[img1_128,img2_128]
distance=compare_faces(zong,test_128)
print(distance)
distance,name=compare_faces_order(zong,test_128,img_names)
print(name)
img = cv2.imread("test.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
detector = dlib.get_frontal_face_detector()
dets_result = detector(gray, 1)
img_result = plot_rectangle(img.copy(), dets_result,name[0])
plt.figure(figsize=(9, 6))
show_image(img_result,"result")
plt.show()
if __name__ == '__main__':
main()