如何通过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实现系统状态监测和故障转移实例方法
Nov 18 Python
Python安装第三方库及常见问题处理方法汇总
Sep 13 Python
Python制作Windows系统服务
Mar 25 Python
Python中循环引用(import)失败的解决方法
Apr 22 Python
python3+requests接口自动化session操作方法
Oct 13 Python
pyqt5 tablewidget 利用线程动态刷新数据的方法
Jun 17 Python
python3 自动识别usb连接状态,即对usb重连的判断方法
Jul 03 Python
Python实现一个数组除以一个数的例子
Jul 20 Python
Python导入模块包原理及相关注意事项
Mar 25 Python
新手学python应该下哪个版本
Jun 11 Python
Django mysqlclient安装和使用详解
Sep 17 Python
Django实现WebSocket在线聊天室功能(channels库)
Sep 25 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
php连接odbc数据源并保存与查询数据的方法
2014/12/24 PHP
Yii2中如何使用modal弹窗(基本使用)
2016/05/30 PHP
浅谈PHP正则中的捕获组与非捕获组
2016/07/18 PHP
PHP表单验证内容是否为空的实现代码
2016/11/14 PHP
javascript document.referrer 用法
2009/04/30 Javascript
jQuery创建自己的插件(自定义插件)的方法
2010/06/10 Javascript
js传中文参数controller里获取参数乱码问题解决方法
2014/01/03 Javascript
JavaScript中的object转换函数toString()与valueOf()介绍
2014/12/31 Javascript
nodejs中使用多线程编程的方法实例
2015/03/24 NodeJs
js实现的简洁网页滑动tab菜单效果代码
2015/08/24 Javascript
Javascript实现前端简单的路由实例
2016/09/11 Javascript
js仿微信公众平台打标签功能
2017/04/08 Javascript
vue省市区三联动下拉选择组件的实现
2017/04/28 Javascript
Bootstrap 表单验证formValidation 实现表单动态验证功能
2017/05/17 Javascript
ionic2懒加载配置详解
2017/09/01 Javascript
对vue.js中this.$emit的深入理解
2018/02/23 Javascript
jQuery实现获取选中复选框的值实例详解
2018/06/28 jQuery
webpack 从指定入口文件中提取公共文件的方法
2018/11/13 Javascript
JS+html5实现异步上传图片显示上传文件进度条功能示例
2019/11/09 Javascript
JS Html转义和反转义(html编码和解码)的实现与使用方法总结
2020/03/10 Javascript
在pycharm中python切换解释器失败的解决方法
2018/10/29 Python
Python代码太长换行的实现
2019/07/05 Python
Anaconda+Pycharm环境下的PyTorch配置方法
2020/03/13 Python
关于tf.matmul() 和tf.multiply() 的区别说明
2020/06/18 Python
关于python中导入文件到list的问题
2020/10/31 Python
python实现登录与注册系统
2020/11/30 Python
英国著名音像制品和图书游戏购物网站:Zavvi
2016/08/04 全球购物
Vans(范斯)德国官网:美国南加州的原创极限运动潮牌
2017/05/02 全球购物
PHP如何自定义函数
2016/09/16 面试题
文件中有一组整数,要求排序后输出到另一个文件中
2012/01/04 面试题
监理资料员岗位职责
2014/01/03 职场文书
高中美术教学反思
2014/01/19 职场文书
《三袋麦子》教学反思
2014/03/02 职场文书
小学生家长寄语
2014/04/02 职场文书
2015年营销工作总结范文
2015/04/23 职场文书
Java 死锁解决方案
2022/05/11 Java/Android