如何通过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的dict,set,list,tuple应用详解
Jul 24 Python
python内存管理分析
Apr 08 Python
Python入门之modf()方法的使用
May 15 Python
Python实现多线程抓取网页功能实例详解
Jun 08 Python
PyQt5每天必学之单行文本框
Apr 19 Python
python版opencv摄像头人脸实时检测方法
Aug 03 Python
Flask框架模板渲染操作简单示例
Jul 31 Python
Django学习之文件上传与下载
Oct 06 Python
Python3 sys.argv[ ]用法详解
Oct 24 Python
Django自定义用户表+自定义admin后台中的字段实例
Nov 18 Python
python3实现在二叉树中找出和为某一值的所有路径(推荐)
Dec 26 Python
MAC平台基于Python Appium环境搭建过程图解
Aug 13 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
FCKeditor添加自定义按钮
2008/03/27 PHP
在Windows XP下安装Apache+MySQL+PHP环境
2015/02/22 PHP
CodeIgniter开发实现支付宝接口调用的方法示例
2016/11/14 PHP
PHP实现提取多维数组指定一列的方法总结
2019/12/04 PHP
基于jquery自己写tab滑动门(通用版)
2012/10/30 Javascript
js 获取和设置css3 属性值的实现方法
2013/05/06 Javascript
js简单实现根据身份证号码识别性别年龄生日
2013/11/29 Javascript
jQuery网页选项卡插件rTabs用法实例分析
2015/08/26 Javascript
jquery实现华丽的可折角广告代码
2015/09/02 Javascript
JS实现自动固定顶部的悬浮菜单栏效果
2015/09/16 Javascript
node.js中express中间件body-parser的介绍与用法详解
2017/05/23 Javascript
JS 中LocalStorage和SessionStorage的使用
2017/08/17 Javascript
VueJS事件处理器v-on的使用方法
2017/09/27 Javascript
vue-awesome-swiper滑块插件使用方法详解
2017/11/27 Javascript
微信小程序checkbox组件使用详解
2018/01/31 Javascript
nodejs同步调用获取mysql数据时遇到的大坑
2019/03/02 NodeJs
nodejs实现获取本地文件夹下图片信息功能示例
2019/06/22 NodeJs
浅谈vuex中store的命名空间
2019/11/08 Javascript
Vue程序化的事件监听器(实例方案详解)
2020/01/07 Javascript
JavaScript实现移动端拖动元素
2020/11/24 Javascript
[02:44]重置世界,颠覆未来——DOTA2 7.23版本震撼上线
2019/12/01 DOTA
python局部赋值的规则
2013/03/07 Python
Python3.x版本中新的字符串格式化方法
2015/04/24 Python
Numpy数据类型转换astype,dtype的方法
2018/06/09 Python
Python访问MongoDB,并且转换成Dataframe的方法
2018/10/15 Python
Python 求数组局部最大值的实例
2019/11/26 Python
韩国11街:11STREET
2018/03/27 全球购物
优衣库美国官网:UNIQLO美国
2018/04/14 全球购物
领先的荷兰线上超市:荷兰之家Holland at Home(支持中文)
2021/01/21 全球购物
大专计算机个人求职的自我评价
2013/10/21 职场文书
机关单位动员会主持词
2014/03/20 职场文书
田径运动会开幕式及主持词
2014/03/28 职场文书
英语教研活动总结
2014/07/02 职场文书
2014年教师节活动总结
2014/08/29 职场文书
2015会计试用期工作总结
2014/12/12 职场文书
高中班主任寄语
2019/06/21 职场文书