侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

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

Python  /  管理员 发布于 7年前   220

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

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

# -*- coding: utf-8 -*-# __author__="maple""""       ┏┓   ┏┓      ┏┛┻━━━┛┻┓      ┃   ☃   ┃      ┃ ┳┛ ┗┳ ┃      ┃   ┻   ┃      ┗━┓   ┏━┛        ┃   ┗━━━┓        ┃ 神兽保佑  ┣┓        ┃ 永无BUG!  ┏┛        ┗┓┓┏━┳┓┏┛         ┃┫┫ ┃┫┫         ┗┻┛ ┗┻┛"""import base64import cv2import timefrom io import BytesIOfrom tensorflow import kerasfrom PIL import Imagefrom pymongo import MongoClientimport tensorflow as tfimport face_recognitionimport 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_imageslables = []datas = []INPUT_NODE = 128LATER1_NODE = 200OUTPUT_NODE = 0TRAIN_DATA_SIZE = 0TEST_DATA_SIZE = 0def 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_ydef 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-opencv 双线性插值实例
    下一条:
    Python-openCV读RGB通道图实例
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • Laravel 11.15版本发布 - Eloquent Builder中添加的泛型(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客