基于python的人脸识别系统代码,用qt界面,使用决策树算法和LBP特征提取方法
时间: 2024-03-21 19:43:24 浏览: 187
好的,针对您的问题,我为您提供以下的代码实现:
```python
# 导入需要的库
import cv2
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
from skimage.feature import local_binary_pattern
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout, QHBoxLayout, QPushButton, QFileDialog, QMessageBox
# 定义人脸识别界面
class FaceRecognition(QWidget):
def __init__(self):
super(FaceRecognition, self).__init__()
self.setWindowTitle('人脸识别系统')
self.setFixedSize(640, 480)
# 定义界面控件
self.label_image = QLabel('请选择一张图片', self)
self.label_image.setAlignment(4)
self.button_select = QPushButton('选择图片', self)
self.button_select.clicked.connect(self.select_image)
self.button_recognize = QPushButton('识别人脸', self)
self.button_recognize.clicked.connect(self.recognize_face)
# 定义界面布局
layout_v = QVBoxLayout()
layout_h = QHBoxLayout()
layout_h.addWidget(self.label_image)
layout_v.addLayout(layout_h)
layout_v.addWidget(self.button_select)
layout_v.addWidget(self.button_recognize)
self.setLayout(layout_v)
# 加载数据集
self.data, self.target = self.load_dataset()
# 训练决策树模型
self.model = DecisionTreeClassifier()
self.model.fit(self.data, self.target)
# 加载数据集
def load_dataset(self):
# 加载人脸数据集
face_dataset = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# 定义空列表
data, target = [], []
# 遍历样本文件夹
for i in range(1, 41):
for j in range(1, 11):
# 读取样本图片
image = cv2.imread('data/s' + str(i) + '/' + str(j) + '.pgm', cv2.IMREAD_GRAYSCALE)
# 检测人脸
faces = face_dataset.detectMultiScale(image, scaleFactor=1.2, minNeighbors=5)
for x, y, w, h in faces:
# 提取LBP特征
lbp = local_binary_pattern(image[y:y+h, x:x+w], 8, 1, 'uniform')
# 统计LBP特征直方图
hist, _ = np.histogram(lbp.ravel(), 256, [0, 256])
# 添加至数据集
data.append(hist)
target.append(i)
# 转化为数组类型
data = np.array(data, dtype=np.float32)
target = np.array(target, dtype=np.int32)
# 返回数据集和标签
return data, target
# 选择图片
def select_image(self):
# 弹出文件选择框
filename, _ = QFileDialog.getOpenFileName(self, '选择图片', '.', 'Image Files(*.png *.jpg *.bmp)')
# 判断是否选择了图片
if filename:
# 显示图片
image = cv2.imread(filename)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image = cv2.resize(image, (320, 240))
image = QImage(image.data, image.shape[1], image.shape[0], QImage.Format_RGB888)
pixmap = QPixmap.fromImage(image)
self.label_image.setPixmap(pixmap)
# 识别人脸
def recognize_face(self):
# 获取图片
pixmap = self.label_image.pixmap()
if pixmap:
# 转化为OpenCV格式
image = pixmap.toImage()
image = image.convertToFormat(QImage.Format_RGB888)
rows = image.height()
cols = image.width()
ptr = image.constBits()
ptr.setsize(rows * cols * 3)
img = np.array(ptr).reshape(rows, cols, 3)
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
# 检测人脸
face_dataset = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
faces = face_dataset.detectMultiScale(img, scaleFactor=1.2, minNeighbors=5)
# 提取LBP特征
for x, y, w, h in faces:
lbp = local_binary_pattern(img[y:y+h, x:x+w], 8, 1, 'uniform')
hist, _ = np.histogram(lbp.ravel(), 256, [0, 256])
# 预测人脸
result = self.model.predict(hist.reshape(1, -1))
# 显示预测结果
QMessageBox.information(self, '识别结果', '该人脸属于第' + str(result[0]) + '个人')
else:
QMessageBox.warning(self, '警告', '请先选择一张图片')
# 定义人脸识别线程
class FaceRecognitionThread(QThread):
# 定义信号
signal_finish = pyqtSignal()
def __init__(self):
super(FaceRecognitionThread, self).__init__()
# 重写run方法
def run(self):
# 创建应用
app = QApplication([])
# 创建人脸识别界面
face_recognition = FaceRecognition()
face_recognition.show()
# 运行应用
app.exec_()
# 发送结束信号
self.signal_finish.emit()
# 主函数
if __name__ == '__main__':
# 创建人脸识别线程
face_recognition_thread = FaceRecognitionThread()
# 启动线程
face_recognition_thread.start()
# 等待线程结束
face_recognition_thread.wait()
```
上述代码实现了一个基于Python的人脸识别系统,使用了Qt界面、决策树算法和LBP特征提取方法。其中,`FaceRecognition`类定义了人脸识别界面,包含选择图片和识别人脸两个按钮,同时实现了加载数据集、训练决策树模型、选择图片、识别人脸等功能。`FaceRecognitionThread`类定义了人脸识别线程,用于运行人脸识别系统。在主函数中,我们创建了人脸识别线程,并启动线程运行人脸识别系统。
阅读全文