Face Recognition - dlib (Python version)

Dlib Introduction

       Dlib is a modern C ++ framework to address include machine learning algorithms and software development of complex real problem, which is widely used in academic and industrial research, including robotics, embedded devices, mobile phones and large-scale high-performance computing environments, DLib open Source makes the process easy to use, free. Its main features are: documentation full, high-quality code, machine learning algorithms, scientific computing algorithms, graph model inference algorithms, image processing, threads, network programming, graphical user interface, data compression and integration algorithm, can refer to the official website Description: http: //dlib.net
 

program

import sys
import os
import dlib
import glob
import numpy
from os import listdir

# 1. 人脸关键点检测器
predictor_path = "shape_predictor_5_face_landmarks.dat"

# 2. 人脸识别模型
face_rec_model_path = "dlib_face_recognition_resnet_model_v1.dat"

# 3. 候选人脸文件夹
faces_folder_path = "picture/known"

# 4. 需识别的人脸
img_path = "picture/unknown/1.jpg"


# 1. 加载人脸检测器: detector有两种选择,其中dlib.cnn_face_detection_model_v1使用的cnn进行检测
detector = dlib.get_frontal_face_detector()
# detector = dlib.cnn_face_detection_model_v1("mmod_human_face_detector.dat")

# 2. 加载人脸关键点检测器
sp = dlib.shape_predictor(predictor_path)

# 3. 加载人脸识别模型
facerec = dlib.face_recognition_model_v1(face_rec_model_path)

"""
    对文件夹下的每个人脸进行:
    1. 人脸检测
    2. 关键点检测
    3. 描述子提取
"""
# 候选人脸描述子list
descriptors = []

# 保存已知的人脸名字
known_face_names=[]

# win = dlib.image_window()

def getKnownFaceNamesAndDescriptors(path, names, descriptors):
    fileNameList = listdir(path)
    for fileName in fileNameList:
        filePath = path + "/" + fileName
        # filePath = os.path.join(faces_folder_path, fileName)
        index = fileName.rfind('.')
        names.append(fileName[:index])

        print("Processing file: {}".format(filePath))
        img = dlib.load_rgb_image(filePath)
        # win.clear_overlay()
        # win.set_image(img)

        # 1. 人脸检测
        dets = detector(img, 1)
        print("Number of faces detected: {}".format(len(dets)))

        # 处理我们找到的每个人脸
        for k, d in enumerate(dets):
            # 2. 关键点检测
            shape = sp(img, d)

            # 画出人脸区域和关键点
            # win.clear_overlay()
            # win.add_overlay(d)
            # win.add_overlay(shape)

            # 3. 描述子提取,128D向量
            face_descriptor = facerec.compute_face_descriptor(img, shape)

            # 转换为numpy array
            v = numpy.array(face_descriptor)
            descriptors.append(v)


def recognition(img):
    # 对需要识别的人脸进行同样处理: 人脸检测,关键点检测,描述子提取
    # img = dlib.load_rgb_image(img_path)
    dets = detector(img, 1)

    dist = []
    for k, d in enumerate(dets):
        shape = sp(img, d)
        face_descriptor = facerec.compute_face_descriptor(img, shape)
        d_test = numpy.array(face_descriptor)

        # 计算欧式距离
        for i in descriptors:
            dist_ = numpy.linalg.norm(i-d_test)
            dist.append(dist_)

    # 候选人和距离组成一个dict
    c_d = dict(zip(known_face_names, dist))

    cd_sorted = sorted(c_d.items(), key=lambda d:d[1])
    print("The preson is:",cd_sorted[0][0])
# dlib.hit_enter_to_continue()

if __name__ == "__main__":
    # 获取已知图片的名字和描述子
    getKnownFaceNamesAndDescriptors(faces_folder_path, known_face_names, descriptors)

    # 加载待识别的图像
    img = dlib.load_rgb_image(img_path)
    # 识别
    recognition(img)

Remark 

You can download the required files from the following path:

http://dlib.net/files/shape_predictor_5_face_landmarks.dat.bz2
http://dlib.net/files/dlib_face_recognition_resnet_model_v1.dat.bz2

Published 47 original articles · won praise 121 · views 680 000 +

Guess you like

Origin blog.csdn.net/guoyunfei123/article/details/99572791