Python 与 OpenCV 实现人脸识别考勤系统的完整方案
本文演示如何基于 Python 与 OpenCV 生态快速搭建轻量级人脸识别考勤系统。内容涵盖环境依赖安装、人员照片数据集目录规划、面部特征向量提取与实时视频流匹配算法,并结合 csv 模块实现打卡数据的自动写入。附带完整工程代码与运行指引,适合初学者理解计算机视觉基础应用开发流程。
环境准备与依赖安装
系统主要依赖 Python 标准库及第三方视觉组件。确保运行环境为 Python 3.x 以上版本,并在终端执行以下命令安装核心包:
pip install opencv-python
pip install opencv-contrib-python
pip install numpy
pip install face-recognition
构建人脸数据集结构
在工程根目录下建立规范的文件树,将收集到的员工或学员照片按姓名分类存放,便于程序遍历加载。建议每人准备 3 到 5 张不同光线下的正面清晰照片:
attendance-system/
├── dataset/
│ ├── person1/
│ │ ├── 01.jpg
│ │ ├── 02.jpg
│ └── person2/
│ │ ├── 01.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:
try:
enc = face_recognition.face_encodings(image)[0]
known_face_encodings.append(enc)
known_face_names.append(person_name)
except IndexError:
continue
return known_face_encodings, known_face_names
def recognize_faces_in_video(known_face_encodings, known_face_names):
video_capture = cv2.VideoCapture(0)
process_this_frame = True
while True:
ret, frame = video_capture.read()
if not ret:
break
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)
cv2.putText(frame, name, (left + 6, bottom - 6), cv2.FONT_HERSHEY_SIMPLEX, 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)
print("已知人脸数量:", len(known_face_names))
recognize_faces_in_video(known_face_encodings, known_face_names)
集成考勤记录功能
将识别结果与数据存储结合,创建 src/attendance.py。该脚本在检测到匹配人员时调用写入函数,生成按日归档的 CSV 记录表。代码优化了文件读写模式,避免 Windows 系统下的权限冲突:
import os
import datetime
import csv
from face_recognition import create_known_face_encodings, recognize_faces_in_video
ATTENDANCE_FILE = "../attendance/attendance.csv"
def save_attendance(name):
now = datetime.datetime.now()
date_string = now.strftime("%Y-%m-%d")
time_string = now.strftime("%H:%M:%S")
os.makedirs(os.path.dirname(ATTENDANCE_FILE), exist_ok=True)
file_exists = os.path.isfile(ATTENDANCE_FILE)
# 检查是否已存在今日记录,防止重复打卡
with open(ATTENDANCE_FILE, "r", encoding="utf-8", newline="") as f:
reader = csv.reader(f)
for row in reader:
if len(row) >= 2 and row[0] == name and row[1] == date_string:
return
# 追加写入新记录
with open(ATTENDANCE_FILE, "a", encoding="utf-8", newline="") as f:
writer = csv.writer(f)
if not file_exists:
writer.writerow(["Name", "Date", "Time"])
writer.writerow([name, date_string, time_string])
def main():
dataset_folder = "../dataset/"
known_face_encodings, known_face_names = create_known_face_encodings(dataset_folder)
if not known_face_encodings:
print("未检测到任何训练数据,请在 dataset 目录下放置人物照片。")
return
print("系统启动,按下 q 键退出窗口。")
recognize_faces_in_video(known_face_encodings, known_face_names)
if __name__ == "__main__":
main()
运行测试与注意事项
返回项目根目录,通过命令行启动考勤主脚本。系统将调起摄像头,对画面内人员框选标识并输出匹配姓名,同时后台生成 attendance.csv 文件:
python src/attendance.py
以上就是基于 Python 与 OpenCV 实现人脸识别考勤系统的详细内容。该系统采用现成的机器学习特征库替代了复杂的模型训练过程,配合简单的 CSV 日志管理即可满足小型场景需求。更多关于计算机视觉应用开发与本地部署的资料请关注本站其它相关文章!
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









