引言
随着人工智能技术的飞速发展,人脸识别技术已广泛应用于安防、金融、教育等多个领域。本文将带领大家利用Python的face-recognition
库、OpenCV
和SQLite
数据库,从零开始构建一个具备异常报警功能的人脸识别考勤系统。该系统能够实时检测视频流中的人脸,与预存数据库进行比对,自动记录考勤信息,并在检测到未注册人员时触发报警。通过本文的学习,你将掌握以下技能:
- 人脸特征提取与数据库构建
- 实时视频流处理与人脸识别
- 考勤记录管理与异常报警
- 模型优化与部署基础
技术栈简介
- Python:作为核心编程语言,提供丰富的库支持。
- face-recognition:基于dlib的深度学习模型,用于高效的人脸识别。
- OpenCV:开源计算机视觉库,处理图像和视频流。
- SQLite:轻量级数据库,用于存储人脸特征及考勤记录。
环境搭建
首先,确保安装以下依赖库:
bash
bash复制代码
pip install face-recognition opencv-python numpy sqlite3
一、构建人脸特征数据库
步骤1:采集人脸图像
- 创建
dataset
文件夹,按员工姓名建立子文件夹(如Alice
、Bob
),每个子文件夹内存放该员工的清晰正面照片(至少5张)。
步骤2:提取人脸特征并存储
python
import face_recognition
import sqlite3
import os
# 连接SQLite数据库
conn = sqlite3.connect('attendance.db')
c = conn.cursor()
# 创建表存储人脸特征
c.execute('''CREATE TABLE IF NOT EXISTS faces
(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, encoding BLOB)''')
# 遍历dataset文件夹,提取人脸特征
def load_faces():
for root, dirs, files in os.walk('dataset'):
for dir_name in dirs:
person_dir = os.path.join(root, dir_name)
for file in os.listdir(person_dir):
file_path = os.path.join(person_dir, file)
image = face_recognition.load_image_file(file_path)
encodings = face_recognition.face_encodings(image)
if len(encodings) > 0:
encoding = encodings[0]
c.execute("INSERT INTO faces (name, encoding) VALUES (?, ?)",
(dir_name, sqlite3.Binary(encoding.tobytes())))
conn.commit()
load_faces()
conn.close()
二、实时视频流处理
步骤1:捕获视频流
python
import cv2
video_capture = cv2.VideoCapture(0) # 使用默认摄像头
步骤2:实时人脸识别
python
import numpy as np
known_face_encodings = []
known_face_names = []
# 从数据库加载已知人脸数据
conn = sqlite3.connect('attendance.db')
c = conn.cursor()
c.execute("SELECT name, encoding FROM faces")
rows = c.fetchall()
for row in rows:
name = row[0]
encoding = np.frombuffer(row[1], dtype=np.float64)
known_face_encodings.append(encoding)
known_face_names.append(name)
conn.close()
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]
# 查找所有人脸位置及特征
face_locations = face_recognition.face_locations(rgb_small_frame)
face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)
# 遍历检测到的人脸
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] and face_distances[best_match_index] < 0.6:
name = known_face_names[best_match_index]
# 在画面上标注识别结果
top, right, bottom, left = face_locations[0]
top *= 4
right *= 4
bottom *= 4
left *= 4
cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
cv2.putText(frame, name, (left + 6, bottom - 6),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1)
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows()
三、考勤记录系统开发
步骤1:创建考勤表
sql
CREATE TABLE attendance (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
);
步骤2:集成考勤记录功能
修改实时识别代码,添加考勤记录逻辑:
python
# 在识别到已知人脸后添加
if name != "Unknown":
conn = sqlite3.connect('attendance.db')
c = conn.cursor()
c.execute("INSERT INTO attendance (name) VALUES (?)", (name,))
conn.commit()
conn.close()
四、异常报警与邮件通知
步骤1:定义异常规则
例如:非工作时间段考勤、连续多次未识别到人脸等。
步骤2:实现邮件通知
python
import smtplib
from email.mime.text import MIMEText
def send_alert(message):
msg = MIMEText(message)
msg['Subject'] = '考勤异常警报'
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'
with smtplib.SMTP('smtp.example.com', 587) as server:
server.login('[email protected]', 'your_password')
server.sendmail('[email protected]', ['[email protected]'], msg.as_string())
# 在检测到未知人脸时触发报警
if name == "Unknown":
send_alert("检测到未注册人员!")
五、模型优化与部署
优化策略
- 算法优化:使用更高效的模型(如MobileFaceNet)
- 硬件加速:利用GPU加速计算
- 多线程处理:分离视频采集与识别任务
部署建议
- 容器化部署:使用Docker打包应用
- API服务化:将核心功能封装为REST API
- 监控集成:添加系统健康检查与日志记录
总结
本文完整展示了基于Python生态构建人脸识别考勤系统的全过程,从数据采集到模型部署,涵盖了计算机视觉应用的典型流程。通过实践,读者不仅掌握了具体技术的实现细节,更能理解系统设计中的权衡与优化思路。该系统可进一步扩展为更复杂的应用场景,如结合门禁控制、体温检测等功能,构建智慧办公解决方案。
希望本文能成为你探索计算机视觉领域的起点,激发更多创新应用的灵感!