如何通过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缩进区别分析
Feb 15 Python
python机器人行走步数问题的解决
Jan 29 Python
python如何为创建大量实例节省内存
Mar 20 Python
Python3正则匹配re.split,re.finditer及re.findall函数用法详解
Jun 11 Python
用Python shell简化开发
Aug 08 Python
Python supervisor强大的进程管理工具的使用
Apr 24 Python
python3实现斐波那契数列(4种方法)
Jul 15 Python
django重新生成数据库中的某张表方法
Aug 28 Python
Pytorch自己加载单通道图片用作数据集训练的实例
Jan 18 Python
django序列化时使用外键的真实值操作
Jul 15 Python
Django xadmin安装及使用详解
Oct 26 Python
Python实现Word文档转换Markdown的示例
Dec 22 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
Codeigniter(CI)框架分页函数及相关知识
2014/11/03 PHP
php将html转为图片的实现方法
2017/05/19 PHP
PHP验证类的封装与使用方法详解
2019/01/10 PHP
Laravel实现批量更新多条数据
2020/04/06 PHP
javascript学习随笔(使用window和frame)的技巧
2007/03/08 Javascript
jQuery中nextAll()方法用法实例
2015/01/07 Javascript
你所不了解的javascript操作DOM的细节知识点(一)
2015/06/17 Javascript
Javascript编写俄罗斯方块思路及实例
2015/07/07 Javascript
详解javascript传统方法实现异步校验
2016/01/22 Javascript
js删除Array数组中指定元素的两种方法
2016/08/03 Javascript
微信公众号  提示:Unauthorized API function 问题解决方法
2016/12/05 Javascript
JavaScript中的toString()和toLocaleString()方法的区别
2017/02/15 Javascript
简单实现AngularJS轮播图效果
2020/04/10 Javascript
ES5 ES6中Array对象去除重复项的方法总结
2017/04/27 Javascript
Angular(5.2->6.1)升级小结
2018/12/27 Javascript
在Vue中使用icon 字体图标的方法
2019/06/14 Javascript
微信自定义分享链接信息(标题,图片和内容)实现过程详解
2019/09/04 Javascript
javascript全局自定义鼠标右键菜单
2020/12/08 Javascript
[59:35]DOTA2-DPC中国联赛定级赛 Aster vs DLG BO3第一场 1月8日
2021/03/11 DOTA
用Python的urllib库提交WEB表单
2009/02/24 Python
Python PyQt5实现的简易计算器功能示例
2017/08/23 Python
python爬虫_微信公众号推送信息爬取的实例
2017/10/23 Python
详解Python 协程的详细用法使用和例子
2018/06/15 Python
python十进制和二进制的转换方法(含浮点数)
2018/07/07 Python
Flask框架 CSRF 保护实现方法详解
2019/10/30 Python
详解Python中的编码问题(encoding与decode、str与bytes)
2020/09/30 Python
介绍一下sql server的安全性
2014/08/10 面试题
2015年环保局工作总结
2015/05/22 职场文书
建国大业观后感
2015/06/01 职场文书
入党介绍人意见2015
2015/06/01 职场文书
英文投诉信格式
2015/07/03 职场文书
教师病假条范文
2015/08/17 职场文书
windows下快速安装nginx并配置开机自启动的方法
2021/05/11 Servers
浅谈MySql整型索引和字符串索引失效或隐式转换问题
2021/11/20 MySQL
Vue全局事件总线你了解吗
2022/02/24 Vue.js
Windows Server 2012配置DNS服务器的方法
2022/04/29 Servers