美文网首页
基于 Face Recognition 实现人脸识别服务

基于 Face Recognition 实现人脸识别服务

作者: 星辰大海w | 来源:发表于2019-04-11 10:10 被阅读0次

概述

之前的文章所述,笔者的项目需求是:公司预先将员工的照片录入系统,此后员工访问系统时,可以由前端的照相设备采集面孔,使用人脸识别技术,找到员工对应的身份信息,实现 刷脸登录 的功能,此外,最好身份信息和照片都在系统内,尽量不使用互联网服务。

Face Recognition 库简介

经过前面Face Recognition 库的学习,实现了通过Python脚本实现命令行对2张人脸的比对与识别。再次说明, Face Recognition 库的主要接口API为:

  1. 人脸检测:face_recognition.face_locations(img, number_of_times_to_upsample=1, model="hog")
  2. 检测面部特征点: face_landmarks(face_image, face_locations=None, model="large")
  3. 给脸部编码:face_encodings(face_image, known_face_locations=None, num_jitters=1)
  4. 从编码中找出人的名字:compare_faces(known_face_encodings, face_encoding_to_check, tolerance=0.6)

Face Recognition 库简单来说就是:给定一张照片,它可以从中框出人脸,并将人脸提取为特征向量

人脸特征提取

人脸查找

关键在于怎么实现人脸的比对。如果仅仅是2张照片,库中给出的examples 是通过对特征向量求距离实现的。

2张照片比对

在这个过程中,根据照片求特征向量是较慢的,而向量距离是很快的,因为它只是执行了简单矩阵计算,这步很快。

那么如何实现已有100名员工的照片,传入一张新照片,查找他是谁呢?
我也Google了网上其他网友实现的基于Face Recognition 库的人脸查找,他们实现的方式大多扩展了一下2张照片比对的情形,比如face-recognition-service。它的逻辑就是:读取图片库中的100张照片,逐照片分析得出特征向量1-100,形成特征向量矩阵M,然后对新照片,得出特征向量A,计算矩阵M和A的距离,选距离小于阈值的那个向量,反求对应的人。

典型过程

人脸查找逻辑优化

前面的逻辑是可以的,唯一问题在于新增人脸后特征向量增加怎么处理。有的项目是再次执行预处理过程,求特征矩阵这步很耗时,求距离矩阵这步非常快速。

所以我将特征向量存入redis数据库,查找时,直接从数据库取出人名和他对应的特征向量,然后组成特征矩阵,计算相似度(距离矩阵)

逻辑优化

代码实现

本代码基于 Python3 ,使用的库有 flaskredisnumpy 以及 face_recognition

#!/usr/bin/python
# -*- coding: utf-8 -*-

from flask import Flask, Response, request, jsonify
import redis
import face_recognition
import numpy as np

app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False

pool = redis.ConnectionPool(host='127.0.0.1', port=6379)

# 首页
@app.route('/', methods=['GET'])
def index():
    return '''
    <!doctype html>
    <title>人脸服务</title>
    <a href="upload">人脸录入</a><br>
    <a href="search">人脸搜索</a>
    '''

# 人脸录入页
@app.route('/upload', methods=['GET'])
def uploadHtml():
    return '''
    <!doctype html>
    <title>人脸录入</title>
    <h1>人脸录入</h1>
    <form method="POST" action="upload" enctype="multipart/form-data">
      姓名:<input type="text" name="name"><br>
      <input type="file" name="file">
      <input type="submit" value="提交">
    </form>
    '''

# 人脸录入
@app.route('/upload', methods=['POST'])
def upload():
    if 'file' not in request.files:
        return jsonify({'code': 500, 'msg': '没有文件'})
    file = request.files['file']
    name = request.form['name']
    image = face_recognition.load_image_file(file)
    face_locations = face_recognition.face_locations(image)
    if len(face_locations) != 1:
        return jsonify({'code': 500, 'msg': '人脸数量有误'})
    face_encodings = face_recognition.face_encodings(image, face_locations)
    # 连数据库
    r = redis.Redis(connection_pool=pool)
    # 录入人名-对应特征向量
    r.set(name, face_encodings[0].tobytes())
    return jsonify({'code': 0, 'msg': '录入成功'})

# 人脸搜索页
@app.route('/search', methods=['GET'])
def searchHtml():
    return '''
    <!doctype html>
    <title>人脸搜索</title>
    <h1>人脸搜索</h1>
    <form method="POST" enctype="multipart/form-data">
      <input type="file" name="file">
      <input type="submit" value="提交">
    </form>
    '''

# 人脸搜索
@app.route('/search', methods=['POST'])
def search():
    if 'file' not in request.files:
        return jsonify({'code': 500, 'msg': '没有文件'})
    file = request.files['file']
    image = face_recognition.load_image_file(file)
    face_locations = face_recognition.face_locations(image)
    if len(face_locations) != 1:
        return jsonify({'code': 500, 'msg': '人脸数量有误'})
    face_encodings = face_recognition.face_encodings(image, face_locations)
    # 连数据库
    r = redis.Redis(connection_pool=pool)
    # 取出所有的人名和它对应的特征向量
    names = r.keys()
    faces = r.mget(names)
    # 组成矩阵,计算相似度(欧式距离)
    matches = face_recognition.compare_faces([np.frombuffer(x) for x in faces], face_encodings[0])
    return jsonify({'code': 0, 'names': [str(name, 'utf-8') for name, match in zip(names, matches) if match]})

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5001, debug=True)

测试

  1. 将代码保存为 face.py
  2. 通过命令启动代码 python3 face.py
  3. 通过浏览器访问 http://127.0.0.1:5001 就可以访问服务

相关文章

网友评论

      本文标题:基于 Face Recognition 实现人脸识别服务

      本文链接:https://www.haomeiwen.com/subject/aqnduqtx.html