聪明的人脸识别2——Keras 利用Retinaface+Facenet搭建人脸识别平台

学习前言

我又死了我又死了我又死了!
在这里插入图片描述

什么是Retinface和Facenet

1、Retinface

Retinaface是来自insightFace的又一力作,基于one-stage的人脸检测网络。
同时开源了代码与数据集,在widerface上有非常好的表现。
在这里插入图片描述

2、Facenet

谷歌人脸识别算法,发表于 CVPR 2015,利用相同人脸在不同角度等姿态的照片下有高内聚性,不同人脸有低耦合性,提出使用 cnn + triplet mining 方法,在 LFW 数据集上准确度达到 99.63%。

通过 CNN 将人脸映射到欧式空间的特征向量上,实质上:不同图片人脸特征的距离较大;通过相同个体的人脸的距离,总是小于不同个体的人脸这一先验知识训练网络。

测试时只需要计算人脸特征EMBEDDING,然后计算距离使用阈值即可判定两张人脸照片是否属于相同的个体。
在这里插入图片描述
简单来讲,在使用阶段,facenet即是:
1、输入一张人脸图片
2、通过深度卷积网络提取特征
3、L2标准化
4、得到一个长度为128特征向量。

整体实现代码

https://github.com/bubbliiiing/facenet-retinaface-keras

Retinaface原理和Facenet原理可以参考我的另外两篇博客。
睿智的目标检测40——Keras搭建Retinaface人脸检测与关键点定位平台

神经网络学习小记录54——Keras 搭建自己的Facenet人脸识别平台

实现流程

整体的代码摆放如下:
在这里插入图片描述

一、数据库的初始化

在这里插入图片描述
face_dataset里面装的是想要识别的人脸,在图片中看到的obama_1.jpg指的就是obama的第一张人脸图片,可以配置多张图片都指向obama,如obama_2.jpg、obama_3.jpg,需要注意的是,face_dataset里面每张图片都只能包含一张人脸,即目标人脸。

数据库中每一张图片对应一个人的人脸,图片名字中“_”靠左的部分就是这个人的名字。

数据库初始化指的是人脸数据库的初始化

想要实现人脸识别,首先要知道自己需要识别哪些人脸,在这一步中,我们会讲识到的人脸进行编码并放入数据库中。

数据库的初始化具体执行的过程就是

1、遍历数据库中所有的图片。
2、利用Retinaface检测每个图片中的人脸位置。
3、将人脸截取下来。
4、将获取到的人脸进行对齐。
5、利用Facenet将人脸进行编码。
6、将所有人脸编码的结果放在一个列表中。
7、保存成npy的形式。

第6步得到的列表就是已知的所有人脸的特征列表,在之后获得的实时图片中的人脸都需要与已知人脸进行比对,这样我们才能知道谁是谁
实现代码如下:

#-------------------------------------#
#       调用摄像头检测
#-------------------------------------#
from retinaface import Retinaface
from PIL import Image
import os
import cv2
import time
import numpy as np

retinaface = Retinaface()

list_dir = os.listdir("face_dataset")
image_paths = []
names = []
for name in list_dir:
    image_paths.append("face_dataset/"+name)
    names.append(name.split("_")[0])
    
retinaface.encode_face_dataset(image_paths,names)

二、检测图片的处理

1、人脸的截取与对齐

在这里插入图片描述

利用Retinaface我们可以获得一张图片中人脸的位置,但是我们截取下来的人脸是这样的:
在这里插入图片描述
我们可以很明显的看出来人脸是歪着的,我们如果人脸可以正过来,那么将对人脸的特征提取非常有好处。
在这里插入图片描述
下面这张图看着就正多了。

常见的对齐方法有很多,在本篇博客里我们使用双眼坐标进行旋正。

利用双眼坐标进行旋正需要用到两个参数,如图所示分别是:
1、眼睛连线相对于水平线的倾斜角。
2、图片的中心。

在这里插入图片描述
利用这两个参数我们可以知道需要图片需要旋转的角度是多少,图片旋转的中心是什么

代码实现如下,其中landmark是五个人脸特征点的位置:

#-------------------------------------#
#   人脸对齐
#-------------------------------------#
def Alignment_1(img,landmark):

    if landmark.shape[0]==68:
        x = landmark[36,0] - landmark[45,0]
        y = landmark[36,1] - landmark[45,1]
    elif landmark.shape[0]==5:
        x = landmark[0,0] - landmark[1,0]
        y = landmark[0,1] - landmark[1,1]
    # 眼睛连线相对于水平线的倾斜角
    if x==0:
        angle = 0
    else: 
        # 计算它的弧度制
        angle = math.atan(y/x)*180/math.pi

    center = (img.shape[1]//2, img.shape[0]//2)
    
    RotationMatrix = cv2.getRotationMatrix2D(center, angle, 1)
    # 仿射函数
    new_img = cv2.warpAffine(img,RotationMatrix,(img.shape[1],img.shape[0])) 

    RotationMatrix = np.array(RotationMatrix)
    new_landmark = []
    for i in range(landmark.shape[0]):
        pts = []    
        pts.append(RotationMatrix[0,0]*landmark[i,0]+RotationMatrix[0,1]*landmark[i,1]+RotationMatrix[0,2])
        pts.append(RotationMatrix[1,0]*landmark[i,0]+RotationMatrix[1,1]*landmark[i,1]+RotationMatrix[1,2])
        new_landmark.append(pts)

    new_landmark = np.array(new_landmark)

    return new_img, new_landmark


#---------------------------------------------------#
#   检测图片
#---------------------------------------------------#
def detect_image(self, image):
    image = np.array(image, np.float32)
    old_image = np.array(image.copy(), np.uint8)
    #---------------------------------------------------#
    #   Retinaface检测部分-开始
    #---------------------------------------------------#
    # 数据的预处理
    im_height, im_width, _ = np.shape(image)

    scale = [np.shape(image)[1], np.shape(image)[0], np.shape(image)[1], np.shape(image)[0]]
    scale_for_landmarks = [np.shape(image)[1], np.shape(image)[0], np.shape(image)[1], np.shape(image)[0],
                                        np.shape(image)[1], np.shape(image)[0], np.shape(image)[1], np.shape(image)[0],
                                        np.shape(image)[1], np.shape(image)[0]]

    if self.letterbox_image:
        image = letterbox_image(image,[self.retinaface_input_shape[1], self.retinaface_input_shape[0]])
        anchors = self.anchors
    else:
        anchors = Anchors(self.cfg, image_size=(im_height, im_width)).get_anchors()

    #---------------------------------------------------#
    #   图片预处理,归一化
    #---------------------------------------------------#
    photo = np.expand_dims(preprocess_input(image),0)

    #---------------------------------------------------#
    #   将处理完的图片传入Retinaface网络当中进行预测
    #---------------------------------------------------#
    preds = self.retinaface.predict(photo)

    #---------------------------------------------------#
    #   Retinaface网络的解码,最终我们会获得预测框
    #   将预测结果进行解码和非极大抑制
    #---------------------------------------------------#
    results = self.bbox_util.detection_out(preds,anchors,confidence_threshold=self.confidence)

    #---------------------------------------------------#
    #   如果没有预测框则返回原图
    #---------------------------------------------------#
    if len(results)<=0:
        return old_image

    results = np.array(results)
    if self.letterbox_image:
        results = retinaface_correct_boxes(results, np.array((self.retinaface_input_shape[0], self.retinaface_input_shape[1])), np.array([im_height, im_width]))
    
    #---------------------------------------------------#
    #   4人脸框置信度
    #   :4是框的坐标
    #   5:是人脸关键点的坐标
    #---------------------------------------------------#
    results[:,:4] = results[:,:4]*scale
    results[:,5:] = results[:,5:]*scale_for_landmarks
    #---------------------------------------------------#
    #   Retinaface检测部分-结束
    #---------------------------------------------------#

2、利用Facenet对矫正后的人脸进行编码

在这里插入图片描述

Facenet是一个人脸特征获取的模型,将第1步获得的对齐人脸传入Facenet模型就可以得到每个人脸的特征向量。

将所有特征向量保存在一个列表中,在第3步进行比对。

#-----------------------------------------------#
#   Facenet编码部分-开始
#-----------------------------------------------#
face_encodings = []
for result in results:
    #----------------------#
    #   图像截取,人脸矫正
    #----------------------#
    crop_img = np.array(old_image)[int(result[1]):int(result[3]), int(result[0]):int(result[2])]
    landmark = np.reshape(result[5:],(5,2)) - np.array([int(result[0]),int(result[1])])
    crop_img,_ = Alignment_1(crop_img,landmark)

    #----------------------#
    #   人脸编码
    #----------------------#
    # 不失真的resize,然后进行归一化
    crop_img = np.array(letterbox_image(np.uint8(crop_img),(self.facenet_input_shape[1],self.facenet_input_shape[0])))/255
    crop_img = np.expand_dims(crop_img,0)
    # 利用图像算取长度为128的特征向量
    face_encoding = self.facenet.predict(crop_img)[0]
    face_encodings.append(face_encoding)
#-----------------------------------------------#
#   Facenet编码部分-结束
#-----------------------------------------------#

3、将实时图片中的人脸特征与数据库中的进行比对

在这里插入图片描述

这个比对过程需要循环实现,具体对实时图片中的每一个人脸进行循环:
1、获取实时图片中的每一个人脸特征。
2、将每一个人脸特征和数据库中所有的人脸进行比较,计算距离。如果距离小于门限值,则认为其具有一定的相似度。
3、获得每一张人脸在数据库中最相似的人脸的序号。
4、判断这个序号对应的人脸距离是否小于门限,是则认为人脸识别成功,他就是这个人。

实现代码如下:

#-----------------------------------------------#
#   人脸特征比对-开始
#-----------------------------------------------#
face_names = []
for face_encoding in face_encodings:
    # 取出一张脸并与数据库中所有的人脸进行对比,计算得分
    matches, face_distances = compare_faces(self.known_face_encodings, face_encoding, tolerance = self.facenet_threhold)
    name = "Unknown"
    # 找到已知最贴近当前人脸的人脸序号
    best_match_index = np.argmin(face_distances)
    if matches[best_match_index]:
        name = self.known_face_names[best_match_index]
    face_names.append(name)
#-----------------------------------------------#
#   人脸特征比对-结束
#-----------------------------------------------#

4、图片绘制

这一部分只是检测结果绘制在图片上,由绘制代码组成。

for i, b in enumerate(results):
    text = "{:.4f}".format(b[4])
    b = list(map(int, b))
    cv2.rectangle(old_image, (b[0], b[1]), (b[2], b[3]), (0, 0, 255), 2)
    cx = b[0]
    cy = b[1] + 12
    cv2.putText(old_image, text, (cx, cy),
                cv2.FONT_HERSHEY_DUPLEX, 0.5, (255, 255, 255))

    # landms
    cv2.circle(old_image, (b[5], b[6]), 1, (0, 0, 255), 4)
    cv2.circle(old_image, (b[7], b[8]), 1, (0, 255, 255), 4)
    cv2.circle(old_image, (b[9], b[10]), 1, (255, 0, 255), 4)
    cv2.circle(old_image, (b[11], b[12]), 1, (0, 255, 0), 4)
    cv2.circle(old_image, (b[13], b[14]), 1, (255, 0, 0), 4)
    
    name = face_names[i]
    font = cv2.FONT_HERSHEY_SIMPLEX
    cv2.putText(old_image, name, (b[0] , b[3] - 15), font, 0.75, (255, 255, 255), 2) 

使用Retinaface+Facenet进行人脸识别:

在GITHUB上下载好库后将库解压。
在这里插入图片描述
下载对应的权重,README中会有下载连接,百度网盘下载或者GITHUB下载均可。
在这里插入图片描述
在retinaface.py里面,根据自身需求修改retinaface_model_path、retinaface_backbone、facenet_model_path、facenet_backbone四个参数。
在这里插入图片描述
运行encoding.py进行人脸数据集编码。
在这里插入图片描述
运行predict.py进行人脸图片的预测。
在这里插入图片描述

  • 35
    点赞
  • 139
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 45
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 45
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Bubbliiiing

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值