PySimpleGUI 库
PySimpleGUI 是一个用于简化 GUI 编程的 Python 包,它封装了多种底层 GUI 框架(如 tkinter、Qt、WxPython 等),提供了简单易用的 API。PySimpleGUI 包含了大量的控件(也称为小部件或组件),这些控件可以快速构建用户界面。
安装
pip install pysimplegui -i https://pypi.tuna.tsinghua.edu.cn/simple
布局和窗口
import datetime
import osimport PySimpleGUI as sg
import cv2
import face_recognition
import numpy as np# 定义布局
layout = [[sg.Text('你好')],[sg.Button('关闭')]
]# 创建窗口
window = sg.Window('我的窗口', layout)# 事件循环
while True:event, values = window.read()# 点击X或退出按钮,关闭窗口if event in (None, "关闭"):break# 关闭窗口
window.close()
文本输入输出案例
layout = [[sg.Text('编号:', size=(10, 1)), sg.InputText()],[sg.Text(key='text')],[sg.Button('保存'), sg.Button('关闭')]
]# 创建窗口
window = sg.Window('我的窗口', layout)
# 事件循环
while True:# event 鼠标事件 value 接收的值event, values = window.read()# 获取编号id = values[0]if event == '保存':print(f'id = {id}')sg.popup(f'id={id}')# 更新文本window['text'].update('新的文本内容')breakif event == sg.WIN_CLOSED or event == '关闭':breakwindow.close()
视频处理
cap = cv2.VideoCapture(0)
if cap.isOpened() == False:print('没有开启摄像头')layout = [[sg.Button('关闭')],[sg.Image(key='video')],
]
window = sg.Window('视频处理', layout)while True:event, values = window.read(timeout=5)ret, frame = cap.read()if event in (None, "关闭"):breakif ret:imgType = cv2.imencode('.png', frame)[1].tobytes()print(imgType)window['video'].update(imgType)cap.release()
window.close()
图片上传
# 设置主题
sg.theme('LightBlue')layout = [[sg.Text('请选择一张图片:')],[sg.Input(key='-FILE-', enable_events=True),sg.FileBrowse(file_types=(('Image Files', '*.jpg;*.jpeg;*.png;*.jpeg;*.gif;'),))],[sg.Button('退出')],[sg.Image(key='-IMAGE-')]
]window = sg.Window('图片上传示例', layout)
while True:event, value = window.read()if event in (None, '退出'):breakelif event == '-FILE-':# 更新图片image_path = value['-FILE-']print(image_path)img = cv2.imread(image_path)if img is not None:imgType = cv2.imencode('.png', img)[1].tobytes()window['-IMAGE-'].update(data=imgType)#else:sg.popup('无法加载图片,请选择有效的图片文件。')window.close()
pymsql 库
PyMySQL
是一个用于连接 MySQL 数据库的纯 Python 实现。它允许 Python 程序与 MySQL 数据库进行交互,执行 SQL 查询,并处理结果集。
安装
pip install pymysql -i https://pypi.tuna.tsinghua.edu.cn/simple
添加数据
'''
ser='root'
password='123456'
database='user_info'
sql = "insert into user_list (user_id,user_name) value (%s,%s)"
sql_query = "select * from user_list where user_id = %s "
需要修改'''
# 添加人脸信息到数据库中
def add(user_id, user_name):# 创建数据库连接con = pymysql.Connect(host='localhost', user='root', password='123456', port=3306, database='user_info',charset='utf8')# 创建游标cur = con.cursor()# 定义sql语句变量sql = "insert into user_list (user_id,user_name) value (%s,%s)"# 定义sql语句变量sql_query = "select * from user_list where user_id = %s "# 执行sqlcur.execute(sql_query, user_id)# 返回查询的结果result = cur.fetchall()if len(result) == 0:# 执行sqlcur.execute(sql, (user_id, user_name))# 执行返回的插入数量num = cur.rowcount# 提交操作con.commit()cur.close()con.close()if num > 0:print(f"({user_id},{user_name})插入成功")return Trueelse:# print("插入失败")# return Falsereturn "插入失败"else:cur.close()con.close()return f'{user_id}已存在'# add('001', '张三')
# add('002', '李四')
# add('003', '王五')
# add('004', '赵六')
查询数据
def query(id):# 创建数据库连接con = pymysql.Connect(host='localhost', user='root', password='123456', port=3306, database='user_info',charset='utf8')# 创建游标cur = con.cursor()# 定义sql语句变量sql = "select * from user_list where user_id = %s "# 执行sqlcur.execute(sql, id)# 返回查询的结果result = cur.fetchall()# 提交操作con.commit()cur.close()con.close()if len(result) > 0:return result[0][1]else:return ('查无此人')# print(query('001'))
删除数据
def delete(id):# 创建数据库连接con = pymysql.Connect(host='localhost', user='root', password='123456', port=3306, database='user_info',charset='utf8')# 创建游标cur = con.cursor()# 定义sql语句变量sql = "delete from user_list where user_id= %s "sql_query = "select * from user_list where user_id = %s "# 执行sqlcur.execute(sql_query, id)# 返回查询的结果result = cur.fetchall()if len(result) == 0:print(f'{id}不存在')else:# 执行sqlcur.execute(sql, id)# 返回删除的数量num = cur.rowcount# 提交操作con.commit()cur.close()con.close()if num > 0:print('删除成功')return Trueelse:print('删除失败')return False# delete('002')
更新数据
def update(id, name):try:# 创建数据库连接con = pymysql.Connect(host='localhost', user='root', password='123456', port=3306, database='user_info', charset='utf8')# 创建游标with con.cursor() as cur:# 定义sql语句变量sql = "UPDATE user_list SET user_name = %s WHERE user_id = %s"# 执行sqlcur.execute(sql, (name, id))# 提交操作con.commit()# 返回删除的数量num = cur.rowcountif num > 0:print('修改成功')return Trueelse:print('修改失败')return Falseexcept pymysql.MySQLError as e:print(f"数据库错误: {e}")return Falsefinally:if con:con.close()# 示例调用
update(1, '新用户名')
综合应用
人脸采集
(1)准备工作:创建数据库和人脸数据表(user_id,user_name)
(2)存储人脸数据表,人脸图片保存在目录下
def faceGather():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, 300), size=(800, 500))# 开始录入人脸while True:event, values = window.read(timeout=5)ret, frame = cap.read()if event in (None, '退出'):breakif ret:img_encode = cv2.imencode('.png', frame)[1].tobytes()window['image'].update(img_encode)if event == '人脸采集':id = values[0]name = values[1]print(id, name)iss = cv2.imwrite(f'D:\\WorkSpace\\MyProject\\Opencv_learn\\face\\{id}.png', frame)if iss:if add(id, name):sg.popup('采集成功')else:sg.popup('采集失败')else:sg.popup('采集失败')cap.release()window.close()faceGather()
人脸识别
(1)根据视频帧与人脸图片比较,取出其id
(2)在数据库中查询id的对应信息
def faceRecognize():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, 300), size=(800, 500))# 开始录入人脸while True:event, values = window.read(timeout=5)ret, frame = cap.read()if event in (None, '退出'):breakif ret:img_encode = cv2.imencode('.png', frame)[1].tobytes()window['image'].update(img_encode)if event == '人脸识别':file_path = 'D:\\WorkSpace\\MyProject\\Opencv_learn\\face\\'img_list = os.listdir(file_path)face_list = face_recognition.face_locations(frame)if len(face_list) > 0:# print("检测到人脸")encode1 = face_recognition.face_encodings(frame)[0]# 准备数据result_list = []img_name = ''# 遍历人脸数据库for img_name in img_list:face = cv2.imread(file_path + img_name)encode2 = face_recognition.face_encodings(face)[0]result = np.linalg.norm(encode2 - encode1)# 取出idid = img_name.split('.')[0]result_list.append((id, result))min_id, min_result = min(result_list, key=lambda x: x[1])# 实现最优匹配if min_result < 0.4:re = query(min_id)# 打卡时间current_time = datetime.datetime.now()formatted_time = current_time.strftime("%Y-%m-%d %H:%M:%S")sg.popup(re, formatted_time, '打卡成功', )break# 遍历到最后一张图片还是没有满足result<0.4else:sg.popup("查无此人")else:sg.popup("没有检测到人脸")cap.release()window.close()faceRecognize()