人脸采集
1 准备工作:创建人脸表
2 完成人脸保存
import PySimpleGUI as sg
import cv2
import pymysql
#添加人脸信息到数据库中
def add(name,num):
# 创建数据库连接
con = pymysql.Connect(host="localhost", user="root", passwd="1234", database="demo01", charset="utf8");
# 创建游标
cr = con.cursor();
# 定义一个sql语句变量
sql = "insert into user_info (user_name,num) values(%s,%s)";
# 执行sql
cr.execute(sql,(name,num))
# 执行返回的插入数量
num = cr.rowcount;
if num > 0:
print("插入成功");
else:
print("插入失败");
# 提交操作
con.commit();
# 关闭连接
con.close();
def rendVideo():
# 读取视频
cap = cv2.VideoCapture(0)
#界面布局
layout =[
[sg.Text("编号:", size=(10, 1)), sg.InputText()],
[sg.Text("姓名:", size=(10, 1)), sg.InputText()],
[sg.Button("人脸采集", size=(10, 1)),sg.Button("退出", size=(10, 1))],
[sg.Image(key='image')],
]
window =sg.Window("视频播放",layout,location=(350,50),size=(800,500))
# 开始人脸录入
while cap.isOpened():
event, values = window.read(timeout=10)
ret,frame = cap.read()
if ret:
#把数据帧对象转换成bytes数据类型,更新窗口对象window信息
imgbyts = cv2.imencode('.png', frame)[1].tobytes()
window['image'].update(data=imgbyts)
#点击X和退出按钮,关闭窗口
if event in (None,"退出"):
break
if event in (None,"人脸采集"):
# 获取编号
id = values[0]
name = values[1]
print(id,name)
# 保存人脸
iss = cv2.imwrite(f"D:\\faceImages\\{id}.png", frame)
if iss == True:
add(name,id)
print("收集人脸成功")
else:
print("收集人脸失败")
#关闭窗口
window.close()
cap.release()
if __name__ =="__main__":
rendVideo()
人脸识别
import PySimpleGUI as sg
import cv2
import pymysql
import os
import face_recognition
import numpy as np
#查询人脸库
def query(id):
# 创建数据库连接
con = pymysql.Connect(host="localhost", user="root", passwd="1234", database="demo01", charset="utf8");
# 创建游标
cr = con.cursor();
# 定义一个sql语句变量
sql = "select * from user_info where num = %s ";
# 执行sql
cr.execute(sql,id)
# 执行查询
num = cr.fetchall()
print(num)
if len(num) > 0:
return num[0][1]
else:
return "无"
# 提交操作
con.commit();
# 关闭连接
con.close();
def rendVideo():
# 读取视频
cap = cv2.VideoCapture(0)
#界面布局
layout =[
[sg.Button("人脸识别", size=(10, 1)),sg.Button("退出", size=(10, 1))],
[sg.Image(key='image')],
]
window =sg.Window("视频播放",layout,location=(350,50),size=(800,500))
# 开始人脸录入
while cap.isOpened():
event, values = window.read(timeout=10)
ret,frame = cap.read()
if ret:
#把数据帧对象转换成bytes数据类型,更新窗口对象window信息
imgbyts = cv2.imencode('.png', frame)[1].tobytes()
window['image'].update(data=imgbyts)
#点击X和退出按钮,关闭窗口
if event in (None,"退出"):
break
if event in (None,"人脸识别"):
path = os.listdir("D:\\faceImages")
#print(path)
for i in path:
# 获取人脸特征
img = cv2.imread(f"D:\\faceImages\\{i}")
en1 = face_recognition.face_encodings(img)[0]
en2 = face_recognition.face_encodings(frame)[0]
iss = np.linalg.norm(en1 - en2)
#print(iss)
num = i.split(".")[0]
# print(num)
if iss < 0.5:
rs = query(num)
sg.popup(f"此人是{rs}")
break
else:
sg.popup(f"查无此人")
#关闭窗口
window.close()
cap.release()
if __name__ =="__main__":
rendVideo()