dlib implementa el método de reconocimiento facial

descripción general

Este ejemplo demuestra cómo utilizar dlib como una herramienta de reconocimiento facial. dlib proporciona un método para mapear datos de imágenes faciales a un vector espacial de dimensión 128. Si dos imágenes provienen de la misma persona, la distancia entre los vectores espaciales mapeados por las dos imágenes está cerca, o lejos. Por lo tanto, es posible determinar si son la misma persona extrayendo imágenes y mapeándolas en un vector espacial de 128 dimensiones y luego midiendo si su distancia euclidiana (distancia euclidiana) es lo suficientemente pequeña.

Cuando el umbral de distancia del vector se establece en 0,6, en 2007, en competencia con otros métodos avanzados de reconocimiento facial, el modelo dlib tiene una tasa de precisión del 99,38 % en la prueba de referencia del conjunto de datos faciales LFW. Esta tasa de precisión significa que la herramienta dlib tendrá una precisión del 99,38 % para determinar si un par de fotos son de la misma persona.

implementación del método

Pasos de implementación

  1. Instanciar modelo de detección de rostros, modelo de detección de puntos clave de rostros, modelo de reconocimiento de rostros
  2. cargar un par de imágenes
  3. Obtenga el vector espacial mapeado por la imagen de la cara en la imagen respectivamente, es decir, el valor de la característica de la cara
  4. Calcule la distancia euclidiana del vector de características y juzgue si es la misma persona de acuerdo con el umbral

Código de muestra

import sys
import os
import dlib
import glob
import numpy as np

def find_euclidean_distance(source_representation, test_representation):
    """
    计算向量的欧氏距离
    """
    euclidean_distance = source_representation - test_representation
    euclidean_distance = np.sum(np.multiply(euclidean_distance, euclidean_distance))
    euclidean_distance = np.sqrt(euclidean_distance)
    return euclidean_distance

# 加载模型
face_detect_model_path = '../models/mmod_human_face_detector.dat'
face_shape_predictor_path = '../models/shape_predictor_5_face_landmarks.dat'
face_rec_model_path = '../models/dlib_face_recognition_resnet_model_v1.dat'
face_detector = dlib.cnn_face_detection_model_v1(face_detect_model_path)
face_shape_predictor = dlib.shape_predictor(face_shape_predictor_path)
face_recognition_model = dlib.face_recognition_model_v1(face_rec_model_path)

image_path = r'sample1.jpg'
image_cmp_path = r'sample12.jpg'
image=dlib.load_rgb_image(image_path)
image_cmp = dlib.load_rgb_image(image_cmp_path)

face_detections = face_detector(image, 1)
# 假定每张对比图片只有一张人脸
face_shape=face_shape_predictor(image, face_detections[0].rect)
# 获取人脸图片128维向量
face_descriptor = face_recognition_model.compute_face_descriptor(image,face_shape,10,0.35)
face_feature = np.array(face_descriptor)

# 获取对比人脸图片的128维向量
face_cmp_detections = face_detector(image_cmp, 1)
face_cmp_shape = face_shape_predictor(image_cmp, face_cmp_detections[0].rect)
face_cmp_descriptor = face_recognition_model.compute_face_descriptor(image_cmp, face_cmp_shape,10,0.35)
face_cmp_feature = np.array(face_cmp_descriptor)

# 获取向量欧式距离
distance = find_euclidean_distance(face_feature, face_cmp_feature)
print(distance)

Para obtener el método de vector de cara, puede continuar agregando parámetros de la siguiente manera:
face_descriptor = face_recognition_model.compute_face_descriptor(img, shape, 100, 0.25)

  • En la prueba del conjunto de datos LFW, si no se pasa el parámetro 100, la tasa correcta es 99,13 %, y si se pasa el parámetro 100, la tasa correcta es 99,38 %.Sin embargo, pasar el parámetro 100 hace que la velocidad de ejecución de este método se ralentiza un 100%, por lo que puede elegir según sus necesidades. Explique más el tercer parámetro. El tercer parámetro se usa para decirle a la función cuántas veces debe realizar la extracción de caras (jitter/remuestreo). Cuando se establece en 100, extraerá 100 imágenes de caras ligeramente modificadas y tomará el valor promedio. Luego mapea a un vector espacial, este valor se puede establecer más pequeño, como 10, entonces la velocidad de ejecución será 10 veces más lenta en lugar de 100 veces, pero la tasa correcta sigue siendo 99.3%.

  • El cuarto valor de parámetro padding (0,25) es el margen interior del gráfico de la cara. Si se establece padding en 0, se cortará a lo largo del área de la cara. Cuanto mayor sea el valor de padding, la imagen cortada se extenderá hacia afuera. El padding se establece en Cuando es 0,5 , el ancho de la imagen se convierte en el doble del original, cuando el relleno se establece en 1, es tres veces, y así sucesivamente.

método sobrecargado

Otra forma de obtener el vector de características de la cara (pasar directamente la imagen de la cara alineada):

# 获取人脸对齐图片,必须是默认的尺寸(150*150)
face_chip = dlib.get_face_chip(img, shape)

# 获取特征向量
face_feature_from_prealigned_image = face_recognition_model.compute_face_descriptor(face_chip)

Resumen de métodos sobrecargados:

1. compute_face_descriptor(self, img: numpy.ndarray[(rows,cols,3),uint8], face: dlib.full_object_detection, num_jitters: int=0, padding: float=0.25) -> dlib.vector

    Takes an image and a full_object_detection that references a face in that image and converts it into a 128D face descriptor. 
    If num_jitters>1 then each face will be randomly jittered slightly num_jitters times, each run through the 128D projection, and the average used as the face descriptor.
    Optionally allows to override default padding of 0.25 around the face.

2. compute_face_descriptor(self, img: numpy.ndarray[(rows,cols,3),uint8], num_jitters: int=0) -> dlib.vector

    Takes an aligned face image of size 150x150 and converts it into a 128D face descriptor.
    Note that the alignment should be done in the same way dlib.get_face_chip does it.
    If num_jitters>1 then image will be randomly jittered slightly num_jitters times, each run through the 128D projection, 
    and the average used as the face descriptor. 

3. compute_face_descriptor(self, img: numpy.ndarray[(rows,cols,3),uint8], faces: dlib.full_object_detections, num_jitters: int=0, padding: float=0.25) -> dlib.vectors

    Takes an image and an array of full_object_detections that reference faces in that image and converts them into 128D face descriptors.  
    If num_jitters>1 then each face will be randomly jittered slightly num_jitters times, each run through the 128D projection, 
    and the average used as the face descriptor. Optionally allows to override default padding of 0.25 around the face.

4. compute_face_descriptor(self, batch_img: List[numpy.ndarray[(rows,cols,3),uint8]], batch_faces: List[dlib.full_object_detections], num_jitters: int=0, padding: float=0.25) -> dlib.vectorss

    Takes an array of images and an array of arrays of full_object_detections. `batch_faces[i]` must be an array of full_object_detections corresponding to the image `batch_img[i]`, referencing faces in that image. 
    Every face will be converted into 128D face descriptors.  
	If num_jitters>1 then each face will be randomly jittered slightly num_jitters times, each run through the 128D projection, and the average used as the face descriptor. 
    Optionally allows to override default padding of 0.25 around the face.

5. compute_face_descriptor(self, batch_img: List[numpy.ndarray[(rows,cols,3),uint8]], num_jitters: int=0) -> dlib.vectors

    Takes an array of aligned images of faces of size 150_x_150.Note that the alignment should be done in the same way dlib.get_face_chip does it.Every face will be converted into 128D face descriptors.  
    If num_jitters>1 then each face will be randomly jittered slightly num_jitters times, each run through the 128D projection, and the average used as the face descriptor.

Supongo que te gusta

Origin blog.csdn.net/LJX_ahut/article/details/124970025
Recomendado
Clasificación