使用python语言实现人脸识别打卡,根据人脸检测和目标跟踪实现专注检测 opencv框架,捕获脸部数据,提取人脸特征 建立基于深度学习的学生课堂考勤和专注检测系统

使用python语言实现人脸识别打卡,再根据人脸检测和目标跟踪实现专注检测 opencv框架,捕获脸部数据,提取人脸特征 建立基于深度学习的学生课堂考勤和专注检测系统

实现功能

基于深度学习的学生打卡与专注检测系统围绕学校进行在线教学时利用摄像头采集人脸数据,使用python语言实现人脸识别打卡,再根据人脸检测和目标跟踪实现专注检测。借助opencv框架,捕获脸部数据,提取人脸特征,然后通过计算欧式距离来和预存的人脸特征进行对比,从而实现对学生的识别打卡,利用检测和跟踪算法计算出专注时长,当学生没有专注听课一段时间后就会对学生做出提醒。
在这里插入图片描述

1. 环境配置

确保安装了必要的库:

pip install opencv-python numpy dlib imutils face_recognition PyQt5

在这里插入图片描述

2. 数据准备

收集学生的人脸数据,并将其存储在数据库中。假设你已经有了一个包含学生人脸图片的文件夹students_faces
在这里插入图片描述

3. 人脸识别模块

使用face_recognition库进行人脸识别。

import face_recognition
import os
import cv2
import numpy as np

# 加载已知人脸数据
known_face_encodings = []
known_face_names = []

for filename in os.listdir('students_faces'):
    if filename.endswith('.jpg') or filename.endswith('.png'):
        image = face_recognition.load_image_file(os.path.join('students_faces', filename))
        face_encoding = face_recognition.face_encodings(image)[0]
        known_face_encodings.append(face_encoding)
        known_face_names.append(filename.split('.')[0])

def recognize_faces(frame):
    # 转换为RGB格式
    rgb_frame = frame[:, :, ::-1]

    # 检测人脸位置和编码
    face_locations = face_recognition.face_locations(rgb_frame)
    face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)

    face_names = []
    for face_encoding in face_encodings:
        # 计算与已知人脸的距离
        matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
        name = "Unknown"

        # 如果匹配,则返回名字
        if True in matches:
            first_match_index = matches.index(True)
            name = known_face_names[first_match_index]

        face_names.append(name)

    return face_locations, face_names

4. 目标跟踪模块

使用cv2.TrackerCSRT_create()进行目标跟踪。

def track_face(frame, bbox):
    tracker = cv2.TrackerCSRT_create()
    tracker.init(frame, bbox)
    return tracker

5. 专注检测模块

计算学生头部姿态变化,判断是否专注。

def is_focused(head_pose):
    # 根据头部姿态判断是否专注
    if abs(head_pose[0]) < 10 and abs(head_pose[1]) < 10:
        return True
    return False

6. 主程序

结合以上模块,构建主程序。

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QLabel, QVBoxLayout, QWidget, QFileDialog
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtCore import QTimer

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("网络课堂人脸识别考勤系统")
        self.setGeometry(100, 100, 800, 600)

        self.label = QLabel(self)
        self.label.setGeometry(10, 10, 640, 480)

        self.cap = cv2.VideoCapture(0)
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.update_frame)
        self.timer.start(30)

    def update_frame(self):
        ret, frame = self.cap.read()
        if not ret:
            return

        face_locations, face_names = recognize_faces(frame)

        for (top, right, bottom, left), name in zip(face_locations, face_names):
            cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
            cv2.putText(frame, name, (left + 6, bottom - 6), cv2.FONT_HERSHEY_DUPLEX, 0.5, (255, 255, 255), 1)

        height, width, channel = frame.shape
        bytes_per_line = 3 * width
        q_img = QImage(frame.data, width, height, bytes_per_line, QImage.Format_RGB888).rgbSwapped()
        self.label.setPixmap(QPixmap.fromImage(q_img))

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

7. 数据库记录

将识别结果记录到数据库中。

import sqlite3

def record_attendance(name):
    conn = sqlite3.connect('attendance.db')
    c = conn.cursor()

    c.execute('''CREATE TABLE IF NOT EXISTS attendance
                 (name TEXT, timestamp TEXT)''')

    c.execute("INSERT INTO attendance VALUES (?, datetime('now'))", (name,))
    conn.commit()
    conn.close()

8. 运行程序

启动程序并测试功能。

python main.py

构建一个基于Python的人脸识别学生课堂考勤和专注检测系统的详细步骤和代码示例。

为了实现一个基于深度学习的学生课堂考勤和专注检测系统,我们可以将上述功能模块整合到一个完整的Python项目中。以下是详细的代码示例,包括人脸识别、目标跟踪、专注检测以及用户界面设计。

1. 项目结构

network_attendance_system/
├── control/
│   ├── __init__.py
│   ├── attendance_control.py
│   └── focus_control.py
├── database/
│   ├── __init__.py
│   └── db_operations.py
├── model/
│   ├── __init__.py
│   └── face_recognition_model.py
├── others/
│   ├── __init__.py
│   └── utils.py
├── ui_frame/
│   ├── __init__.py
│   └── mainwindow.py
├── venv/
├── FaceClass.zip
├── mainwindow.py
├── requirements.txt
├── resource_rc.py
└── test.py

2. 代码实现

model/face_recognition_model.py
import face_recognition
import os
import numpy as np

class FaceRecognitionModel:
    def __init__(self, known_faces_dir):
        self.known_face_encodings = []
        self.known_face_names = []

        for filename in os.listdir(known_faces_dir):
            if filename.endswith('.jpg') or filename.endswith('.png'):
                image = face_recognition.load_image_file(os.path.join(known_faces_dir, filename))
                face_encoding = face_recognition.face_encodings(image)[0]
                self.known_face_encodings.append(face_encoding)
                self.known_face_names.append(filename.split('.')[0])

    def recognize_faces(self, frame):
        rgb_frame = frame[:, :, ::-1]
        face_locations = face_recognition.face_locations(rgb_frame)
        face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)

        face_names = []
        for face_encoding in face_encodings:
            matches = face_recognition.compare_faces(self.known_face_encodings, face_encoding)
            name = "Unknown"

            if True in matches:
                first_match_index = matches.index(True)
                name = self.known_face_names[first_match_index]

            face_names.append(name)

        return face_locations, face_names
control/attendance_control.py
from model.face_recognition_model import FaceRecognitionModel
import cv2
import sqlite3

class AttendanceControl:
    def __init__(self, known_faces_dir, db_path):
        self.face_model = FaceRecognitionModel(known_faces_dir)
        self.db_path = db_path

    def record_attendance(self, name):
        conn = sqlite3.connect(self.db_path)
        c = conn.cursor()

        c.execute('''CREATE TABLE IF NOT EXISTS attendance
                     (name TEXT, timestamp TEXT)''')

        c.execute("INSERT INTO attendance VALUES (?, datetime('now'))", (name,))
        conn.commit()
        conn.close()

    def process_frame(self, frame):
        face_locations, face_names = self.face_model.recognize_faces(frame)

        for name in face_names:
            if name != "Unknown":
                self.record_attendance(name)

        return face_locations, face_names
ui_frame/mainwindow.py
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QLabel, QVBoxLayout, QWidget, QFileDialog
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtCore import QTimer
import sys
import cv2

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("网络课堂人脸识别考勤系统")
        self.setGeometry(100, 100, 800, 600)

        self.label = QLabel(self)
        self.label.setGeometry(10, 10, 640, 480)

        self.cap = cv2.VideoCapture(0)
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.update_frame)
        self.timer.start(30)

    def update_frame(self):
        ret, frame = self.cap.read()
        if not ret:
            return

        # 这里调用控制模块的处理函数
        face_locations, face_names = self.control.process_frame(frame)

        for (top, right, bottom, left), name in zip(face_locations, face_names):
            cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
            cv2.putText(frame, name, (left + 6, bottom - 6), cv2.FONT_HERSHEY_DUPLEX, 0.5, (255, 255, 255), 1)

        height, width, channel = frame.shape
        bytes_per_line = 3 * width
        q_img = QImage(frame.data, width, height, bytes_per_line, QImage.Format_RGB888).rgbSwapped()
        self.label.setPixmap(QPixmap.fromImage(q_img))

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

3. 整合与运行

mainwindow.py中,你需要实例化AttendanceControl类,并将其传递给MainWindow类以进行帧处理。

from control.attendance_control import AttendanceControl

# 实例化控制模块
control = AttendanceControl('students_faces', 'attendance.db')

# 在MainWindow类中添加control属性
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.control = control
        # 其他初始化代码...

最后,确保所有依赖库都已安装,并且数据文件路径正确。运行mainwindow.py即可启动系统。

文字及代码仅供参考。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值