如何通过python实现人脸识别验证
更新时间:2020年4月27日 21:20 点击:1795
这篇文章主要介绍了如何通过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-opencv-画外接矩形框的实例代码,代码简单易懂,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-09-04
Python astype(np.float)函数使用方法解析
这篇文章主要介绍了Python astype(np.float)函数使用方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-06-08- 2022虎年新年即将来临,小编为大家带来了一个利用Python编写的虎年烟花特效,堪称全网最绚烂,文中的示例代码简洁易懂,感兴趣的同学可以动手试一试...2022-02-14
- 在本篇文章里小编给大家分享的是一篇关于python中numpy.empty()函数实例讲解内容,对此有兴趣的朋友们可以学习下。...2021-02-06
python-for x in range的用法(注意要点、细节)
这篇文章主要介绍了python-for x in range的用法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-05-10- 这篇文章主要介绍了Python 图片转数组,二进制互转操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-09
- 这篇文章主要介绍了Python中的imread()函数用法说明,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-16
- 这篇文章主要介绍了python如何实现b站直播自动发送弹幕,帮助大家更好的理解和学习使用python,感兴趣的朋友可以了解下...2021-02-20
python Matplotlib基础--如何添加文本和标注
这篇文章主要介绍了python Matplotlib基础--如何添加文本和标注,帮助大家更好的利用Matplotlib绘制图表,感兴趣的朋友可以了解下...2021-01-26- 这篇文章主要介绍了解决python 使用openpyxl读写大文件的坑,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-13
- 今天小编就为大家分享一篇python 计算方位角实例(根据两点的坐标计算),具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-04-27
- 这篇文章主要介绍了使用Python的pencolor函数实现渐变色功能,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-03-09
- 在本篇文章里小编给大家整理的是一篇关于python中使用np.delete()的实例方法,对此有兴趣的朋友们可以学习参考下。...2021-02-01
- 这篇文章主要为大家详细介绍了python实现双色球随机选号,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2020-05-02
Python getsizeof()和getsize()区分详解
这篇文章主要介绍了Python getsizeof()和getsize()区分详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-11-20- 这篇文章主要介绍了python自动化办公操作PPT的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-02-05
- 这篇文章主要介绍了解决python 两个时间戳相减出现结果错误的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-12
- 这篇文章主要为大家详细介绍了python实现学生通讯录管理系统,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-02-25
- 这篇文章主要介绍了PyTorch一小时掌握之迁移学习篇,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-09-08
- 这篇文章主要介绍了python进行相关性分析并绘制散点图,具有一定借鉴价值,需要的朋友可以参考下,希望能够给你带来帮助...2021-09-18