如何通过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 sys.path详细介绍
Oct 17 Python
讲解Python中if语句的嵌套用法
May 14 Python
python使用pymysql实现操作mysql
Sep 13 Python
Python进阶篇之字典操作总结
Nov 16 Python
python中redis的安装和使用
Dec 04 Python
python中numpy.zeros(np.zeros)的使用方法
Nov 07 Python
Linux下python制作名片示例
Jul 20 Python
python 删除字符串中连续多个空格并保留一个的方法
Dec 22 Python
Python requests模块安装及使用教程图解
Jun 30 Python
Python extract及contains方法代码实例
Sep 11 Python
使用Python+OpenCV进行卡类型及16位卡号数字的OCR功能
Aug 30 Python
python实现Nao机器人的单目测距
Sep 04 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的foreach中使用引用时需要注意的一个问题和解决方法
2014/05/29 PHP
PHP整合七牛实现上传文件
2015/07/03 PHP
基于php实现的php代码加密解密类完整实例
2016/10/12 PHP
[原创]PHP实现SQL语句格式化功能的方法
2017/07/28 PHP
对php 判断http还是https,以及获得当前url的方法详解
2019/01/15 PHP
PHP PDOStatement::fetchObject讲解
2019/02/01 PHP
Laravel5框架自定义错误页面配置操作示例
2019/04/17 PHP
JavaScript事件处理器中的event参数使用介绍
2013/05/24 Javascript
简介AngularJS的HTML DOM支持情况
2015/06/17 Javascript
Javascript实现的Map集合工具类完整实例
2015/07/31 Javascript
基于Jquery代码实现手风琴菜单
2015/11/19 Javascript
Bootstrap实现响应式导航栏效果
2015/12/28 Javascript
JavaScript File分段上传
2016/03/10 Javascript
JS实现队列与堆栈的方法
2016/04/21 Javascript
JSON中key动态设置及JSON.parse和JSON.stringify()的区别
2016/12/29 Javascript
JS实现复制功能
2017/03/01 Javascript
微信小程序联网请求的轮播图
2017/07/07 Javascript
200行代码实现blockchain 区块链实例详解
2018/03/14 Javascript
使用weixin-java-miniapp配置进行单个小程序的配置详解
2019/03/29 Javascript
ant design实现圈选功能
2019/12/17 Javascript
[00:12]2018DOTA2亚洲邀请赛 Somnus丶M出阵单挑
2018/04/06 DOTA
python中zip和unzip数据的方法
2015/05/27 Python
Python实现PS滤镜特效Marble Filter玻璃条纹扭曲效果示例
2018/01/29 Python
python实现简单的文字识别
2018/11/27 Python
Pyinstaller 打包exe教程及问题解决
2019/08/16 Python
Python time库基本使用方法分析
2019/12/13 Python
python多项式拟合之np.polyfit 和 np.polyld详解
2020/02/18 Python
django-csrf使用和禁用方式
2020/03/13 Python
520使用Python实现“我爱你”表白
2020/05/20 Python
HTML5利用约束验证API来检查表单的输入数据的代码实例
2016/12/20 HTML / CSS
英文版银行求职信
2013/10/09 职场文书
写自荐信要注意什么
2013/12/26 职场文书
如何写一份好的自荐信
2014/01/02 职场文书
2014标准社保办理委托书
2014/10/06 职场文书
nginx七层负载均衡配置详解
2022/07/15 Servers
Windows server 2003卸载和安装IIS的图文教程
2022/07/15 Servers