欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 名人名企 > opencv-day5-基于guI和pymsql进行的人脸识别案例

opencv-day5-基于guI和pymsql进行的人脸识别案例

2025/4/19 17:23:11 来源:https://blog.csdn.net/keep_keeprogress/article/details/143578598  浏览:    关键词:opencv-day5-基于guI和pymsql进行的人脸识别案例

PySimpleGUI 库

PySimpleGUI 是一个用于简化 GUI 编程的 Python 包,它封装了多种底层 GUI 框架(如 tkinter、Qt、WxPython 等),提供了简单易用的 API。PySimpleGUI 包含了大量的控件(也称为小部件或组件),这些控件可以快速构建用户界面

安装

pip install pysimplegui

pip install PySimpleGUI==4.60.5

#5.0之后的版本收费,如果要卸载当前的版本用:pip uninstall 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.Button("关闭"),sg.Button("人脸采集")]
]
#创建窗口
window=sg.Window("我的窗口",layout)
​
while True:#读取窗口信息,返回窗口的数据和鼠标事件event,value=window.read()# if event in(None,"关闭"):#     print("你点了关闭按钮")#     sg.popup("你点了关闭按钮")#     # 提示if event == "关闭":print("你点了关闭按钮")# 提示sg.popup("你点了关闭按钮")breakif event in("人脸采集",):print("你点了人脸采集按钮")#提示sg.popup("你点了人脸采集按钮")
#资源释放,关闭窗口
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
​
#创建一个布局组件
layout=[[sg.Text("编号:",size=(10,1)),sg.InputText(key="id")],[sg.Text("姓名:",size=(10,1)),sg.InputText(key="name")],[sg.Text(key="msg")],[sg.Button("关闭"),sg.Button("保存")]
]
#创建窗口
window=sg.Window("我的第一个窗口",layout)
​
while True:#读取窗口信息,返回窗口的数据和鼠标事件event,value=window.read()#value是信息,event是事件# if event in(None,"关闭"):#     print("你点了关闭按钮")#     sg.popup("你点了关闭按钮")#     # 提示if event == "关闭":# print("你点了关闭按钮")# 提示sg.popup("你点了关闭按钮")breakif event in("保存",):#获取编号id=value["id"]name=value["name"]window["msg"].update(f"id:{id},姓名:{name}")#提示print(f"id:{id},姓名:{name}")sg.popup(f"id:{id},姓名:{name}")
​#print("你点了人脸采集按钮")
​
​
#资源释放,关闭窗口
window.close()

视频处理

import PySimpleGUI as sg
import cv2
​
def 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 cv2
import PySimpleGUI as sg
#开启摄像头
def demo():cap = cv2.VideoCapture(0)if cap.isOpened() == False:print("没有开启摄像头")return#创建layoutlayout=[[sg.Button("关闭"), sg.Button("保存")],[sg.Image(key="video")]
​]#创建窗口window=sg.Window("视频处理",layout)while True:# 读取数据和事件event,value=window.read(timeout=10)#读取数据帧ret,frame=cap.read()#print(event)#事件执行的逻辑先后顺序,点×表示没有任何事件if event in(None,"关闭"):breakif ret:
​imgType=cv2.imencode(".png",frame)[1].tobytes()print(imgType)window["video"].update(imgType)
​#释放资源cap.release()window.close()
​
demo()

图片上传

import PySimpleGUI as sg
​
def 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()
import cv2
import PySimpleGUI as sg
​
def demo():#创建layoutlayout=[[sg.Button("关闭"), sg.Button("上传")],[sg.Input(key='-FILE-',enable_events=True),sg.FileBrowse(file_types=(("Image Files","*.png;*.jpg;*.jpeg;*.gif"),))],[sg.Image(key="video")]]#创建窗口window=sg.Window("文件处理",layout)while True:# 读取数据和事件event,value=window.read()if event in(None,"关闭"):breakif event=="上传":# 图片路径不能用中文path = value['-FILE-']print(path)#读取路径,转换成图片矩阵img = cv2.imread(path)imgType = cv2.imencode(".png", img)[1].tobytes()window["video"].update(imgType)
​#释放资源window.close()
​
demo()

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();
#数据库增删改查操作
​​​​​​​import pymysql
#新增
def add(name,num):# 创建数据库连接con=pymysql.connect(host="localhost",#数据库地址user="root",#用户名passwd="123456",#密码port=3306,#端口database="demo91",#数据库名charset="utf8"#中文编码)#创建游标对象,包含了增删改查的函数cur=con.cursor()#定义sqlsql="insert into user_info(user_name,user_num) value(%s,%s)"##sql = "update  user_info set user_name=%s where user_id=%s)"#运行sql(增删改查sql的函数)cur.execute(sql, (name,num))#执行增删改sql的函数,返回一个受影响行数的数值,=0表示执行失败num=cur.rowcountif num>0:print("新增成功")else:print("新增失败")#提交con.commit()#释放资源cur.close()con.close()
​
def update(name,id):# 创建数据库连接con = pymysql.connect(host="localhost",  # 数据库地址user="root",  # 用户名passwd="123456",  # 密码port=3306,  # 端口database="demo91",  # 数据库名charset="utf8"  # 中文编码)
​# 创建游标对象,包含了增删改查的函数cur = con.cursor()# 定义sql#更新sql = "update  user_info set user_name=%s where user_id=%s"# 运行sql(增删改查sql的函数)cur.execute(sql, (name, id))# 执行增删改sql的函数,返回一个受影响行数的数值,=0表示执行失败num = cur.rowcountif num > 0:print("更新成功")else:print("更新失败")# 提交con.commit()# 释放资源cur.close()con.close()
​
def select(num):# 创建数据库连接con = pymysql.connect(host="localhost",  # 数据库地址user="root",  # 用户名passwd="123456",  # 密码port=3306,  # 端口database="demo91",  # 数据库名charset="utf8"  # 中文编码)
​# 创建游标对象,包含了增删改查的函数cur = con.cursor()# 定义sql#更新sql = "select * from user_info where user_num=%s"# 运行sql(增删改查sql的函数)cur.execute(sql, (num,))# 执行查询sql的函数rs=cur.fetchall()print(rs)# 释放资源cur.close()con.close()
​if len(rs)>0:print(rs[0][1])return rs[0][1]else:return print("查无此人")
​
​
def delNum(id):# 创建数据库连接con = pymysql.connect(host="localhost",  # 数据库地址user="root",  # 用户名passwd="123456",  # 密码port=3306,  # 端口database="demo91",  # 数据库名charset="utf8"  # 中文编码)
​# 创建游标对象,包含了增删改查的函数cur = con.cursor()# 定义sql#更新sql = "delete  from user_info  where user_id=%s"# 运行sql(增删改查sql的函数)cur.execute(sql, (id,))# 执行增删改sql的函数,返回一个受影响行数的数值,=0表示执行失败num = cur.rowcountif num > 0:print("删除成功")else:print("删除失败")# 提交con.commit()# 释放资源cur.close()con.close()
​
if __name__=="__main__":#add("王五",1)#update("李四",2)select(5)#delNum(10)
 

人脸采集

1 准备工作:创建人脸表

安装mysql和navicat,用navicat连接mysql使用

具体安装可以参考:Windows系统下mysql安装过程及以管理员身份运行cmd命令行问题合集_以管理员运行mysqld --no-defaults --initialize-insecure-CSDN博客

注意创建用户表时要勾选utf8#中文

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()
#数据采集
import pymysql
import PySimpleGUI as sg
import cv2
#人脸信息用户记录
def add(name,num):# 创建数据库连接con=pymysql.connect(host="localhost",#数据库地址user="root",#用户名passwd="123456",#密码port=3306,#端口database="demo91",#数据库名charset="utf8"#中文编码)#创建游标对象,包含了增删改查的函数cur=con.cursor()#定义sqlsql="insert into user_info(user_name,user_num) value(%s,%s)"#运行sql(增删改查sql的函数)cur.execute(sql, (name,num))#执行增删改sql的函数,返回一个受影响行数的数值,=0表示执行失败num=cur.rowcount# 提交con.commit()# 释放资源cur.close()con.close()
​if num>0:print("新增成功")return Trueelse:print("新增失败")return False
​
​
#数据采集窗口
def dataGet():# 开启摄像头cap=cv2.VideoCapture(0)if cap.isOpened()==False:print("摄像头没有开启")return#创建布局layout=[[sg.Text("编号:"),sg.InputText(key="num")],[sg.Text("姓名:"),sg.InputText(key="name")],[sg.Image(key="video")],[sg.Button("关闭"),sg.Button("人脸采集")]]#创建窗口window=sg.Window("人脸信息采集",layout)#循环while True:event,value=window.read(timeout=10)#读取视频ret,frame=cap.read()if event in(None,"关闭"):# 终止循环breakif ret:imtType=cv2.imencode(".png",frame)[1].tobytes()window["video"].update(imtType)if event=="人脸采集":#获取编号和姓名num=value["num"]name=value["name"]# 写入人脸图片iss=cv2.imwrite(f"D:\\faceImages\\{num}.png",frame)if iss:isAdd=add(name,num)if isAdd:sg.popup("人脸采集成功")else:sg.popup("人脸采集失败")
​cap.release()window.close()
​
if __name__=="__main__":dataGet()
#人脸识别
import pymysql
import PySimpleGUI as sg
import cv2
import face_recognition
import os
import numpy as np
#人脸信息用户记录
def select(num):# 创建数据库连接con = pymysql.connect(host="localhost",  # 数据库地址user="root",  # 用户名passwd="123456",  # 密码port=3306,  # 端口database="demo91",  # 数据库名charset="utf8"  # 中文编码)
​# 创建游标对象,包含了增删改查的函数cur = con.cursor()# 定义sql#更新sql = "select * from user_info where user_num=%s"# 运行sql(增删改查sql的函数)cur.execute(sql, (num,))# 执行查询sql的函数rs=cur.fetchall()print(rs)# 释放资源cur.close()con.close()
​if len(rs)>0:print(rs[0][1])return rs[0][1]else:return print("查无此人")
#人脸识别窗口
def dataGet():# 开启摄像头cap=cv2.VideoCapture(0)if cap.isOpened()==False:print("摄像头没有开启")return#创建布局layout=[[sg.Image(key="video")],[sg.Button("关闭"),sg.Button("人脸识别")]]#创建窗口window=sg.Window("人脸识别",layout)#循环while True:event,value=window.read(timeout=10)#读取视频ret,frame=cap.read()if event in(None,"关闭"):# 终止循环breakif ret:imtType=cv2.imencode(".png",frame)[1].tobytes()window["video"].update(imtType)if event=="人脸识别":# 查找人脸库list_dir=os.listdir("D:\\faceImages")if len(list_dir)>0:for i in list_dir:# 读取一个图片对象img=cv2.imread(f"D:\\faceImages\\{i}")if img is None:print("没有读取到图片")breakelse:# 获取已知图片的特征变量en1 = face_recognition.face_encodings(img)[0]# 获取需要检测图片的特征变量en2 = face_recognition.face_encodings(frame)[0]# 计算欧几里得距离rs = np.linalg.norm(en1 - en2)print(rs)if rs<0.5:b=i.split(".")[0]a=select(b)sg.popup(f"用户{a}打卡成功")#查到此人,终止循环breakelse:sg.popup("人脸库没有此人")#这里如果图片库里有多个图片,会逐一进行比对并弹框人脸库没有此人,需要修改
​cap.release()window.close()
​
if __name__=="__main__":dataGet()

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词