如何通过python实现人脸识别验证


Posted in Python onJanuary 17, 2020

这篇文章主要介绍了如何通过python实现人脸识别验证,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

直接上代码,此案例是根据https://github.com/caibojian/face_login修改的,识别率不怎么好,有时挡了半个脸还是成功的

# -*- coding: utf-8 -*-
# __author__="maple"
"""
       ┏┓   ┏┓
      ┏┛┻━━━┛┻┓
      ┃   ☃   ┃
      ┃ ┳┛ ┗┳ ┃
      ┃   ┻   ┃
      ┗━┓   ┏━┛
        ┃   ┗━━━┓
        ┃ 神兽保佑  ┣┓
        ┃ 永无BUG!  ┏┛
        ┗┓┓┏━┳┓┏┛
         ┃┫┫ ┃┫┫
         ┗┻┛ ┗┻┛
"""
import base64
import cv2
import time
from io import BytesIO
from tensorflow import keras
from PIL import Image
from pymongo import MongoClient
import tensorflow as tf
import face_recognition
import numpy as np
#mongodb连接
conn = MongoClient('mongodb://root:123@localhost:27017/')
db = conn.myface #连接mydb数据库,没有则自动创建
user_face = db.user_face #使用test_set集合,没有则自动创建
face_images = db.face_images


lables = []
datas = []
INPUT_NODE = 128
LATER1_NODE = 200
OUTPUT_NODE = 0
TRAIN_DATA_SIZE = 0
TEST_DATA_SIZE = 0


def generateds():
  get_out_put_node()
  train_x, train_y, test_x, test_y = np.array(datas),np.array(lables),np.array(datas),np.array(lables)
  return train_x, train_y, test_x, test_y

def get_out_put_node():
  for item in face_images.find():
    lables.append(item['user_id'])
    datas.append(item['face_encoding'])
  OUTPUT_NODE = len(set(lables))
  TRAIN_DATA_SIZE = len(lables)
  TEST_DATA_SIZE = len(lables)
  return OUTPUT_NODE, TRAIN_DATA_SIZE, TEST_DATA_SIZE

# 验证脸部信息
def predict_image(image):
  model = tf.keras.models.load_model('face_model.h5',compile=False)
  face_encode = face_recognition.face_encodings(image)
  result = []
  for j in range(len(face_encode)):
    predictions1 = model.predict(np.array(face_encode[j]).reshape(1, 128))
    print(predictions1)
    if np.max(predictions1[0]) > 0.90:
      print(np.argmax(predictions1[0]).dtype)
      pred_user = user_face.find_one({'id': int(np.argmax(predictions1[0]))})
      print('第%d张脸是%s' % (j+1, pred_user['user_name']))
      result.append(pred_user['user_name'])
  return result

# 保存脸部信息
def save_face(pic_path,uid):
  image = face_recognition.load_image_file(pic_path)
  face_encode = face_recognition.face_encodings(image)
  print(face_encode[0].shape)
  if(len(face_encode) == 1):
    face_image = {
      'user_id': uid,
      'face_encoding':face_encode[0].tolist()
    }
    face_images.insert_one(face_image)

# 训练脸部信息
def train_face():
  train_x, train_y, test_x, test_y = generateds()
  dataset = tf.data.Dataset.from_tensor_slices((train_x, train_y))
  dataset = dataset.batch(32)
  dataset = dataset.repeat()
  OUTPUT_NODE, TRAIN_DATA_SIZE, TEST_DATA_SIZE = get_out_put_node()
  model = keras.Sequential([
    keras.layers.Dense(128, activation=tf.nn.relu),
    keras.layers.Dense(128, activation=tf.nn.relu),
    keras.layers.Dense(OUTPUT_NODE, activation=tf.nn.softmax)
  ])

  model.compile(optimizer=tf.compat.v1.train.AdamOptimizer(),
        loss='sparse_categorical_crossentropy',
        metrics=['accuracy'])
  steps_per_epoch = 30
  if steps_per_epoch > len(train_x):
    steps_per_epoch = len(train_x)
  model.fit(dataset, epochs=10, steps_per_epoch=steps_per_epoch)

  model.save('face_model.h5')



def register_face(user):
  if user_face.find({"user_name": user}).count() > 0:
    print("用户已存在")
    return
  video_capture=cv2.VideoCapture(0)
  # 在MongoDB中使用sort()方法对数据进行排序,sort()方法可以通过参数指定排序的字段,并使用 1 和 -1 来指定排序的方式,其中 1 为升序,-1为降序。
  finds = user_face.find().sort([("id", -1)]).limit(1)
  uid = 0
  if finds.count() > 0:
    uid = finds[0]['id'] + 1
  print(uid)
  user_info = {
    'id': uid,
    'user_name': user,
    'create_time': time.time(),
    'update_time': time.time()
  }
  user_face.insert_one(user_info)

  while 1:
    # 获取一帧视频
    ret, frame = video_capture.read()
    # 窗口显示
    cv2.imshow('Video',frame)
    # 调整角度后连续拍5张图片
    if cv2.waitKey(1) & 0xFF == ord('q'):
      for i in range(1,6):
        cv2.imwrite('Myface{}.jpg'.format(i), frame)
        with open('Myface{}.jpg'.format(i),"rb")as f:
          img=f.read()
          img_data = BytesIO(img)
          im = Image.open(img_data)
          im = im.convert('RGB')
          imgArray = np.array(im)
          faces = face_recognition.face_locations(imgArray)
          save_face('Myface{}.jpg'.format(i),uid)
      break

  train_face()
  video_capture.release()
  cv2.destroyAllWindows()


def rec_face():
  video_capture = cv2.VideoCapture(0)
  while 1:
    # 获取一帧视频
    ret, frame = video_capture.read()
    # 窗口显示
    cv2.imshow('Video',frame)
    # 验证人脸的5照片
    if cv2.waitKey(1) & 0xFF == ord('q'):
      for i in range(1,6):
        cv2.imwrite('recface{}.jpg'.format(i), frame)
      break

  res = []
  for i in range(1, 6):
    with open('recface{}.jpg'.format(i),"rb")as f:
      img=f.read()
      img_data = BytesIO(img)
      im = Image.open(img_data)
      im = im.convert('RGB')
      imgArray = np.array(im)
      predict = predict_image(imgArray)
      if predict:
        res.extend(predict)

  b = set(res) # {2, 3}
  if len(b) == 1 and len(res) >= 3:
    print(" 验证成功")
  else:
    print(" 验证失败")

if __name__ == '__main__':
  register_face("maple")
  rec_face()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
使用Python抓取模板之家的CSS模板
Mar 16 Python
python搭建微信公众平台
Feb 09 Python
Python自动化测试ConfigParser模块读写配置文件
Aug 15 Python
Python爬虫:通过关键字爬取百度图片
Feb 17 Python
python如何重载模块实例解析
Jan 25 Python
Python实现Kmeans聚类算法
Jun 10 Python
Django用户认证系统 组与权限解析
Aug 02 Python
Django框架 Pagination分页实现代码实例
Sep 04 Python
如何安装2019Pycharm最新版本(详细教程)
Sep 26 Python
Python基于Tensor FLow的图像处理操作详解
Jan 15 Python
Keras自动下载的数据集/模型存放位置介绍
Jun 19 Python
Pytorch 扩展Tensor维度、压缩Tensor维度的方法
Sep 09 Python
Python-openCV读RGB通道图实例
Jan 17 #Python
OpenCV python sklearn随机超参数搜索的实现
Jan 17 #Python
python numpy 矩阵堆叠实例
Jan 17 #Python
Python利用Scrapy框架爬取豆瓣电影示例
Jan 17 #Python
Python下利用BeautifulSoup解析HTML的实现
Jan 17 #Python
pytorch forward两个参数实例
Jan 17 #Python
Python实现CNN的多通道输入实例
Jan 17 #Python
You might like
用Flash图形化数据(二)
2006/10/09 PHP
PHP 5.0 Pear安装方法
2006/12/06 PHP
gd库图片下载类实现下载网页所有图片的php代码
2012/08/20 PHP
PHP面向对象程序设计组合模式与装饰模式详解
2016/12/02 PHP
利用PHP获取汉字首字母并且分组排序详解
2017/10/22 PHP
Draggable Elements 元素拖拽功能实现代码
2011/03/30 Javascript
html超链接打开窗口大小的方法
2013/03/05 Javascript
jQuery实现单击按钮遮罩弹出对话框(仿天猫的删除对话框)
2014/04/10 Javascript
Jquery图片延迟加载插件jquery.lazyload.js的使用方法
2014/05/21 Javascript
javascript处理a标签超链接默认事件的方法
2015/06/29 Javascript
BootStrap Progressbar 实现大文件上传的进度条的实例代码
2016/06/27 Javascript
JavaScript使用键盘输入控制实现数字验证功能
2016/08/19 Javascript
Bootstrap和Java分页实例第一篇
2016/12/23 Javascript
jquery实现自定义图片裁剪功能【推荐】
2017/03/08 Javascript
bootstrapvalidator之API学习教程
2017/06/29 Javascript
jQuery实现动态添加节点与遍历节点功能示例
2017/11/09 jQuery
jquery3和layui冲突导致使用layui.layer.full弹出全屏iframe窗口时高度152px问题
2019/05/12 jQuery
[13:39]2014 DOTA2华西杯精英邀请赛 5 25 NewBee VS DK第一场
2014/05/26 DOTA
[01:44]Ti10举办地公布
2019/08/25 DOTA
Python中对元组和列表按条件进行排序的方法示例
2015/11/10 Python
Python中的异常处理相关语句基础学习笔记
2016/07/11 Python
用python处理图片实现图像中的像素访问
2018/05/04 Python
python绘制直线的方法
2018/06/30 Python
记录Python脚本的运行日志的方法
2019/06/05 Python
Django 请求Request的具体使用方法
2019/11/11 Python
详解python 破解网站反爬虫的两种简单方法
2020/02/09 Python
详解Python调用系统命令的六种方法
2021/01/28 Python
后勤人员自我评价怎么写
2013/09/19 职场文书
档案室主任岗位职责
2014/02/12 职场文书
2015年助理工程师工作总结
2015/04/03 职场文书
2015年初三班主任工作总结
2015/05/21 职场文书
借条如何写
2015/05/26 职场文书
开学典礼致辞
2015/07/29 职场文书
诚实守信主题班会
2015/08/13 职场文书
2016习总书记系列重要讲话心得体会
2016/01/15 职场文书
一篇文章带你了解Python和Java的正则表达式对比
2021/09/15 Python