主流程代码,通过sqlite3保存人脸数据和信息,然后通过遍历数据库与之对比找出识别者信息,若识别不到,则会提示添加人脸信息至数据库。
#导入数据库驱动
import sqlite3
from testCamera import getFaceID,imgToBase64,reconized,getModelFace,saveFaceData
import time
def checkAll():
#连接到数据库
#数据库文件是“face.db”
#如果数据库不存在的话,将会自动创建一个 数据库
conn = sqlite3.connect("face.db")
#创建一个游标 curson
cursor = conn.cursor()
#查询所有记录:
sql = "select * from person_info"
cursor.execute(sql)
#获取查询结果:
values = cursor.fetchall()
getModelFace.getModel()
flag=False
for i in values:
if(reconized.face_check(reconized.get_token(),i[2])):
print("您是"+i[1])
flag=True
break
return flag
#关闭游标:
cursor.close()
#提交事物
conn.commit()
#关闭连接
conn.close()
if __name__ == '__main__':
time1=time.time();
if(checkAll()):
time2 = time.time();
useTime = time2 - time1;
print("识别耗时" + str(useTime) + "秒")
else:
print("人脸库无您的信息,请录入")
saveFaceData.save()
getModelFace.py主要是用于对比时获取人脸与库中Face_ID对比
import cv2
import numpy as np
def getModel():
#人脸特征配置xml
face_cascade = cv2.CascadeClassifier(
"D:\Python\haarcascade_frontalface_default.xml")
# eye_cascade = cv2.CascadeClassifier("D:\Python\haarcascade_eye.xml")
#获取笔记本电脑自带摄像头权限
cap = cv2.VideoCapture(0)
#直到获取到人脸拍下照片才退出拍照循环
while True:
ret, img = cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.1, 5)
if len(faces) > 0:
cv2.imwrite("model.jpg",img)
break
人脸特征识别配置文件haarcascade_frontalface_default.xml可通过我的云盘分享获取。
云盘分享
提取码:w5ql
getFaceID.py主要是保存库内无Face_ID的人脸信息
import cv2
import numpy as np
def getFaceImg():
face_cascade = cv2.CascadeClassifier(
"D:\Python\haarcascade_frontalface_default.xml")
eye_cascade = cv2.CascadeClassifier("D:\Python\haarcascade_eye.xml")
cap = cv2.VideoCapture(0)
while True:
ret, img = cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.1, 5)
if len(faces) > 0:
cv2.imwrite("face_id.jpg",img)
break
return True;
imgToBase64.py通过python的base64库将图片转成base64码存入sqlite3数据库
import base64
def ImgToBase64(imgPath):
with open(imgPath, 'rb') as f:
base64_data = base64.b64encode(f.read())
s = base64_data.decode()
return s
saveFaceData.py将人脸图片转化的base64码作为Face_id存入数据库,并录入人名,可按需增加其他信息。
#导入数据库驱动
import sqlite3
from testCamera import getFaceID,imgToBase64
import time
def save():
#连接到数据库
#数据库文件是“face.db”
#如果数据库不存在的话,将会自动创建一个 数据库
conn = sqlite3.connect("face.db")
#创建一个游标 curson
cursor = conn.cursor()
#执行一条语句,创建 person_info表
#sql = "create table person_info (id varchar(20) primary key, name varchar(30), face_id varchar(300))"
#cursor.execute(sql)
#通过获取图片转BASE64存入sqlite3数据库
print("请看着摄像头!!!")
time.sleep(5)
if(getFaceID.getFaceImg()):
face_id = imgToBase64.ImgToBase64('face_id.jpg')
print("请输入您的姓名:")
name = input()
sql = "insert into person_info(name, face_id) values(\'"+name+"\',\'"+face_id+"\')"
print(sql)
cursor.execute(sql)
print("信息录入成功")
cursor.execute("delete from person_info where name = '郭志强'")
print("delete successful")
#关闭游标:
cursor.close()
#提交事物
conn.commit()
#关闭连接
conn.close()
if __name__ == '__main__':
save();
reconized.py分两个方法,先通过注册百度平台账号建立应用获取百度官网获取的AK(client_id)以及百度官网获取的SK(client_secret)来获取请求的token,再调用百度的人脸识别API请求人脸对比后的返回json数据。
# encoding:utf-8
import urllib.request
import json
import base64
import ast
import urllib
import re,time
from testCamera import getModelFace
def face_check(access_token,face_id):
'''
调用百度人脸对比API
'''
request_url = "https://aip.baidubce.com/rest/2.0/face/v3/match"
filename1 = 'model.jpg'
# filename2 = 'image2.jpg'
f = open(filename1, 'rb')
# f2 = open(filename2, 'rb')
img_test1 = base64.b64encode(f.read())
# img_test2 = base64.b64encode(f2.read())
params = json.dumps(
[{"image": '' + str(img_test1, 'utf-8') + '', "image_type": "BASE64", "face_type": "LIVE",
"quality_control": "LOW"},
{"image": '' + face_id + '', "image_type": "BASE64", "face_type": "IDCARD",
"quality_control": "LOW"}])
# params=urlencode(params)
#access_token = '24.e354ec977f6a1b97c69e9933ebcf402f.2592000.1573884178.282335-17544795'
request_url = request_url + "?access_token=" + access_token
request = urllib.request.Request(url=request_url, data=params.encode("utf-8"))
request.add_header('Content-Type', 'application/json')
response = urllib.request.urlopen(request)
content = response.read()
content = content.decode("utf-8")
content = ast.literal_eval(content)
#print(content['result']['score'])
if(content['result']['score']>=80):
return True
else:
return False
def get_token():
'''
获取百度token
'''
# client_id 为百度官网获取的AK, client_secret 为百度官网获取的SK
host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=***********&client_secret=************'
request = urllib.request.Request(host)
request.add_header('Content-Type', 'application/json; charset=UTF-8')
response = urllib.request.urlopen(request)
content = response.read()
if (content):
#print(content)
p1 = re.compile(r'"access_token":"(.*?)","scope":"', re.S) # 最小匹配
result = re.findall(p1, str(content)).__str__()
return result[2:-2]
if __name__ == '__main__':
getModelFace.getModel()
token = get_token()
face_check(token)
关于注册百度官网获取AK和SK,参考人脸对比官方API 戳这儿