python+OpenCV人脸识别考勤系统实现的详细代码

 更新时间:2023年05月22日 08:55:12   作者:A等天晴  
作为一个基于人脸识别算法的考勤系统的设计与实现教程,以下内容将提供详细的步骤和代码示例。本教程将使用 Python 语言和 OpenCV 库进行实现,需要的朋友可以参考下

一、环境配置

  • 安装 Python

请确保您已经安装了 Python 3.x。可以在Python 官网下载并安装。

  • 安装所需库

在命令提示符或终端中运行以下命令来安装所需的库:

pip install opencv-python
pip install opencv-contrib-python
pip install numpy
pip install face-recognition

二、创建数据集

  • 创建文件夹结构

在项目目录下创建如下文件夹结构:

attendance-system/
├── dataset/
│   ├── person1/
│   ├── person2/
│   └── ...
└── src/

将每个人的照片放入对应的文件夹中,例如:

attendance-system/
├── dataset/
│   ├── person1/
│   │   ├── 01.jpg
│   │   ├── 02.jpg
│   │   └── ...
│   ├── person2/
│   │   ├── 01.jpg
│   │   ├── 02.jpg
│   │   └── ...
│   └── ...
└── src/

三、实现人脸识别算法

在 src 文件夹下创建一个名为 face_recognition.py 的文件,并添加以下代码:

import os
import cv2
import face_recognition
import numpy as np

def load_images_from_folder(folder):
    images = []
    for filename in os.listdir(folder):
        img = cv2.imread(os.path.join(folder, filename))
        if img is not None:
            images.append(img)
    return images

def create_known_face_encodings(root_folder):
    known_face_encodings = []
    known_face_names = []
    for person_name in os.listdir(root_folder):
        person_folder = os.path.join(root_folder, person_name)
        images = load_images_from_folder(person_folder)
        for image in images:
            face_encoding = face_recognition.face_encodings(image)[0]
            known_face_encodings.append(face_encoding)
            known_face_names.append(person_name)
    return known_face_encodings, known_face_names

def recognize_faces_in_video(known_face_encodings, known_face_names):
    video_capture = cv2.VideoCapture(0)
    face_locations = []
    face_encodings = []
    face_names = []
    process_this_frame = True

    while True:
        ret, frame = video_capture.read()
        small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
        rgb_small_frame = small_frame[:, :, ::-1]

        if process_this_frame:
            face_locations = face_recognition.face_locations(rgb_small_frame)
            face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)

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

                face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
                best_match_index = np.argmin(face_distances)
                if matches[best_match_index]:
                    name = known_face_names[best_match_index]

                face_names.append(name)

        process_this_frame = not process_this_frame

        for (top, right, bottom, left), name in zip(face_locations, face_names):
            top *= 4
            right *= 4
            bottom *= 4
            left *= 4

            cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
            cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
            font = cv2.FONT_HERSHEY_DUPLEX
            cv2.putText(frame, name, (left + 6, bottom - 6), font, 0.8, (255, 255, 255), 1)

        cv2.imshow('Video', frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    video_capture.release()
    cv2.destroyAllWindows()

if __name__ == "__main__":
    dataset_folder = "../dataset/"
    known_face_encodings, known_face_names = create_known_face_encodings(dataset_folder)
    recognize_faces_in_video(known_face_encodings, known_face_names)

四、实现考勤系统

在 src 文件夹下创建一个名为 attendance.py 的文件,并添加以下代码:

import os
import datetime
import csv
from face_recognition import create_known_face_encodings, recognize_faces_in_video

def save_attendance(name):
    attendance_file = "../attendance/attendance.csv"
    now = datetime.datetime.now()
    date_string = now.strftime("%Y-%m-%d")
    time_string = now.strftime("%H:%M:%S")
    if not os.path.exists(attendance_file):
        with open(attendance_file, "w", newline="") as csvfile:
            csv_writer = csv.writer(csvfile)
            csv_writer.writerow(["Name", "Date", "Time"])
    with open(attendance_file, "r+", newline="") as csvfile:
        csv_reader = csv.reader(csvfile)
        rows = [row for row in csv_reader]
        for row in rows:
            if row[0] == name and row[1] == date_string:
                return
        csv_writer = csv.writer(csvfile)
        csv_writer.writerow([name, date_string, time_string])

def custom_recognize_faces_in_video(known_face_encodings, known_face_names):
    video_capture = cv2.VideoCapture(0)
    face_locations = []
    face_encodings = []
    face_names = []
    process_this_frame = True
    while True:
        ret, frame = video_capture.read()
        small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
        rgb_small_frame = small_frame[:, :, ::-1]

        if process_this_frame:
            face_locations = face_recognition.face_locations(rgb_small_frame)
            face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)
            face_names = []
            for face_encoding in face_encodings:
                matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
                name = "Unknown"
                face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
                best_match_index = np.argmin(face_distances)
                if matches[best_match_index]:
                    name = known_face_names[best_match_index]
                    save_attendance(name)
                face_names.append(name)
        process_this_frame = not process_this_frame
        for (top, right, bottom, left), name in zip(face_locations, face_names):
            top *= 4
            right *= 4
            bottom *= 4
            left *= 4
            cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
            cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
            font = cv2.FONT_HERSHEY_DUPLEX
            cv2.putText(frame, name, (left + 6, bottom - 6), font, 0.8, (255, 255, 255), 1)

        cv2.imshow('Video', frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    video_capture.release()
    cv2.destroyAllWindows()

if __name__ == "__main__":
    dataset_folder = "../dataset/"
    known_face_encodings, known_face_names = create_known_face_encodings(dataset_folder)
    custom_recognize_faces_in_video(known_face_encodings, known_face_names)

五、运行考勤系统

运行 attendance.py 文件,系统将开始识别并记录考勤信息。考勤记录将保存在 attendance.csv 文件中。

python src/attendance.py

现在,您的基于人脸识别的考勤系统已经实现。请注意,这是一个基本示例,您可能需要根据实际需求对其进行优化和扩展。例如,您可以考虑添加更多的人脸识别算法、考勤规则等。

到此这篇关于python+OpenCV人脸识别考勤系统实现的详细代码的文章就介绍到这了,更多相关python OpenCV人脸识别考勤系统内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • peewee创建连接前的前置操作wireshark抓包实现

    peewee创建连接前的前置操作wireshark抓包实现

    这篇文章主要为大家介绍了peewee创建连接前的前置操作wireshark 抓包实现示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-10-10
  • python多线程抽象编程模型详解

    python多线程抽象编程模型详解

    这篇文章主要为大家详细介绍了python多线程抽象编程模型,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-03-03
  • 使用sklearn之LabelEncoder将Label标准化的方法

    使用sklearn之LabelEncoder将Label标准化的方法

    今天小编就为大家分享一篇使用sklearn之LabelEncoder将Label标准化的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-07-07
  • 解决pycharm下os.system执行命令返回有中文乱码的问题

    解决pycharm下os.system执行命令返回有中文乱码的问题

    今天小编就为大家分享一篇解决pycharm下os.system执行命令返回有中文乱码的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-07-07
  • 11行Python代码实现解密摩斯密码

    11行Python代码实现解密摩斯密码

    摩尔斯电码是一种时通时断的信号代码,通过不同的排列顺序来表达不同的英文字母、数字和标点符号。本文将通过Python代码来实现解密摩斯密码,感兴趣的可以学习一下
    2022-04-04
  • PyQt5每天必学之QSplitter实现窗口分隔

    PyQt5每天必学之QSplitter实现窗口分隔

    这篇文章主要介绍了PyQt5每天必学之窗口分隔,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-04-04
  • 利用 Monkey 命令操作屏幕快速滑动

    利用 Monkey 命令操作屏幕快速滑动

    Monkey测试是Android平台自动化测试的一种手段,通过Monkey程序模拟用户触摸屏幕、滑动Trackball、按键等操作来对设备上的程序进行压力测试,检测程序多久的时间会发生异常
    2016-12-12
  • Python使用PyShark分析网络流量的脚本分享

    Python使用PyShark分析网络流量的脚本分享

    作为一名网络安全工程师,是常常需要自己编写一些实用的脚本的,下面是一个使用 PyShark 库编写的网络流量分析脚本,感兴趣的小伙伴可以了解下
    2025-08-08
  • Python技法之如何用re模块实现简易tokenizer

    Python技法之如何用re模块实现简易tokenizer

    当我们在Python中开始新的东西时,我通常首先看一些模块或库来使用,下面这篇文章主要给大家介绍了关于Python技法之如何用re模块实现简易tokenizer的相关资料,需要的朋友可以参考下
    2022-05-05
  • django中资源文件夹的引入及配置方法

    django中资源文件夹的引入及配置方法

    这篇文章主要介绍了django中资源文件夹的引入,主要包括静态资源文件夹的引入及媒体资源文件夹的引入,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-08-08

最新评论