opencv保姆级讲解-guI和pymsql实现人脸识别打卡(6)
PySimpleGUI 库
PySimpleGUI 是一个用于简化 GUI 编程的 Python 包,它封装了多种底层 GUI 框架(如 tkinter、Qt、WxPython 等),提供了简单易用的 API。PySimpleGUI 包含了大量的控件(也称为小部件或组件),这些控件可以帮助你快速构建用户界面
安装
pip install pysimplegui
布局和窗口
import PySimpleGUI as sg# 定义布局
layout = [[sg.Text('你好')],[sg.Button('关闭')]
]
# 创建窗口
window = sg.Window('我的窗口', layout)
# 事件循环
while True:event, values = window.read()# 点击X和退出按钮,关闭窗口if event in (None, "关闭"):break
# 关闭窗口
window.close()
文本输入输出案例
import PySimpleGUI as sg# 定义布局
layout = [[sg.Text("编号:", size=(10, 1)), sg.InputText()],[sg.Text(key="text")],[sg.Button('保存'),sg.Button('关闭')]
]
# 创建窗口
window = sg.Window('我的窗口', layout)
# 事件循环
while True:event, values = window.read()# 获取编号id = values[0]if event == '保存':print(f'id={id}')sg.popup(f'id={id}')# 更新文本window['text'].update('新的文本内容')if event == sg.WIN_CLOSED or event == '关闭':break
# 关闭窗口
window.close()
视频处理
import PySimpleGUI as sg
import cv2def rendVideo():# 读取视频cap = cv2.VideoCapture(0)#界面布局layout =[[sg.Button("退出", size=(10, 1))],[sg.Image(key='image')],]#创建一个window对象#location 视频位置#size 视频大小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#关闭窗口window.close()cap.release()
if __name__ =="__main__":rendVideo()
图片上传
import PySimpleGUI as sgdef main():# 设置主题sg.theme('LightBlue')# 布局定义layout = [[sg.Text('请选择一张图片:')],[sg.Input(key='-FILE-', enable_events=True), sg.FileBrowse(file_types=(("Image Files", "*.png;*.jpg;*.jpeg;*.gif"),))],[sg.Button('退出')],[sg.Image(key='-IMAGE-')]]# 创建窗口window = sg.Window('图片上传示例', layout)while True:event, values = window.read()# 处理事件if event in (sg.WINDOW_CLOSED, '退出'):breakelif event == '-FILE-':# 更新图片image_path = values['-FILE-']print(image_path)if image_path:window['-IMAGE-'].update(filename=image_path)window.close()
if __name__ == '__main__':main()
pymsql 库
PyMySQL
是一个用于连接 MySQL 数据库的纯 Python 实现。它允许 Python 程序与 MySQL 数据库进行交互,执行 SQL 查询,并处理结果集
安装
pip install pymysql
数据添加
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)";# 执行sqlcr.execute(sql,(name,num))# 执行返回的插入数量num = cr.rowcount;if num > 0:print("插入成功");else:print("插入失败");# 提交操作con.commit();# 关闭连接con.close();
数据查询
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 ";# 执行sqlcr.execute(sql,id)# 执行返回的插入数量num = cr.fetchall()print(num)if len(num) > 0:return num[0][1]else:return "无"# 提交操作con.commit();# 关闭连接con.close();
人脸采集
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)";# 执行sqlcr.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,"退出"):breakif 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 ";# 执行sqlcr.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,"退出"):breakif 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}")breakelse:sg.popup(f"查无此人")#关闭窗口window.close()cap.release()
if __name__ =="__main__":rendVideo()