如何通过python实现人脸识别验证
作者:Maple_feng 发布时间:2021-10-30 18:52:56
标签:python,人脸,识别
这篇文章主要介绍了如何通过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()
来源:https://www.cnblogs.com/angelyan/p/12113773.html


猜你喜欢
- 1. python函数1.1 函数的作用函数是组织好的,可重复使用的,用来实现单一或相关联功能的代码段函数能提高应用的模块性和代码的重复利用
- 目录楔子paramikoSSHClient 的使用connect:实现远程服务器的连接与认证set_missing_host_key_pol
- 本文实例为大家分享了js实现五子棋游戏的具体代码,供大家参考,具体内容如下html:<body> <h2>五子棋游戏
- 今天群里有人问了个问题是这样的: 然后有群友是这样回答的 select name,sum(case when stype=4 t
- 本文实例讲述了javascript设计模式 – 单例模式。分享给大家供大家参考,具体如下:介绍:单例模式是结构最简单的设计模式。单例模式用于
- 在一个大型的项目中,不可避免会出现操作时间的业务,比如时间的格式化,比如时间的加减,我们一般会直接使用moment.js库来做,毕竟稳定可靠
- MySQL Shell import_table数据导入1. import_table介绍这一期我们介绍一款高效的数据导入工具,MySQL
- apache对php的支持是通过apache的mod_php5模块来支持的,这点与nginx不同。nginx是通过第三方的fastcgi处理
- 问题背景用户反馈说当与外部客户端进行 FTP 传输时,可以成功登录,但无法传输任何数据。总之 FTP 传输失败,需要来弄清楚到底发生了什么。
- 上一节除了介绍使用 Python 连接 es,还有最简单的 query() 方法,这一节介绍一下几种其他的查询方式。1、query() 方法
- 安装 Golang在 http://golang.org/dl/ 可以下载到 Golang。安装文档:http://golang.org/d
- 使用pip安装Django时报错,先是:C:\Users\admin>pip install django Collecting dj
- 准备工作右击新建的项目,选择Python File,新建一个Python文件,然后在开头import cv2导入cv2库。我们还要知道在Op
- mysql win10 解压缩下载 解压Mysql :版本 5.7.13 下载链接 (通过这个官网zip链接可以直接下载,不用再注册 Ora
- 1. 循环require在JavaScript中,模块之间可能出现相互引用的情况,例如现在有三个模块,他们之间的相互引用关系如下,大致的引用
- 前言接着上一篇:AI识别照片是谁,人脸识别face_recognition开源项目安装使用根据项目提供的demo代码,调整了一下功能,自己写
- 学习目标:学会使用windows系统安装MySQL数据库,供大家参考,具体内容如下1.打开浏览器输入SQL官网的下载地址:下载链接2.下载好
- javascript中声明函数的方法有两种:函数声明式和函数表达式.区别如下:1).以函数声明的方法定义的函数,函数名是必须的,而函数表达式
- 数据库设计范式目前数据库设计有五种范式 , 一般我们数据库只需要满足前三项即可第一范式 : 确保每列保持原子性什么是原子性? 意思就是不可再
- 一种有意思的数据结构-默克树(Merkle tree)默克树(Merkle tree)又叫hash树。程序员可以说自己不知道默克树,但是不能