引言
隨著人工智能技術的飛速發展,人臉識別技術已廣泛應用于安防、金融、教育等多個領域。本文將帶領大家利用Python的face-recognition
庫、OpenCV
和SQLite
數據庫,從零開始構建一個具備異常報警功能的人臉識別考勤系統。該系統能夠實時檢測視頻流中的人臉,與預存數據庫進行比對,自動記錄考勤信息,并在檢測到未注冊人員時觸發報警。通過本文的學習,你將掌握以下技能:
- 人臉特征提取與數據庫構建
- 實時視頻流處理與人臉識別
- 考勤記錄管理與異常報警
- 模型優化與部署基礎
技術棧簡介
- Python:作為核心編程語言,提供豐富的庫支持。
- face-recognition:基于dlib的深度學習模型,用于高效的人臉識別。
- OpenCV:開源計算機視覺庫,處理圖像和視頻流。
- SQLite:輕量級數據庫,用于存儲人臉特征及考勤記錄。
環境搭建
首先,確保安裝以下依賴庫:
bash復制代碼pip install face-recognition opencv-python numpy sqlite3
一、構建人臉特征數據庫
步驟1:采集人臉圖像
- 創建
dataset
文件夾,按員工姓名建立子文件夾(如Alice
、Bob
),每個子文件夾內存放該員工的清晰正面照片(至少5張)。
步驟2:提取人臉特征并存儲
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:捕獲視頻流
import cv2video_capture = cv2.VideoCapture(0) # 使用默認攝像頭
步驟2:實時人臉識別
import numpy as npknown_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 *= 4right *= 4bottom *= 4left *= 4cv2.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'):breakvideo_capture.release()
cv2.destroyAllWindows()
三、考勤記錄系統開發
步驟1:創建考勤表
CREATE TABLE attendance (id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT,timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
);
步驟2:集成考勤記錄功能
修改實時識別代碼,添加考勤記錄邏輯:
# 在識別到已知人臉后添加
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:實現郵件通知
import smtplib
from email.mime.text import MIMETextdef send_alert(message):msg = MIMEText(message)msg['Subject'] = '考勤異常警報'msg['From'] = 'your_email@example.com'msg['To'] = 'admin@example.com'with smtplib.SMTP('smtp.example.com', 587) as server:server.login('your_email@example.com', 'your_password')server.sendmail('your_email@example.com', ['admin@example.com'], msg.as_string())# 在檢測到未知人臉時觸發報警
if name == "Unknown":send_alert("檢測到未注冊人員!")
五、模型優化與部署
優化策略
- 算法優化:使用更高效的模型(如MobileFaceNet)
- 硬件加速:利用GPU加速計算
- 多線程處理:分離視頻采集與識別任務
部署建議
- 容器化部署:使用Docker打包應用
- API服務化:將核心功能封裝為REST API
- 監控集成:添加系統健康檢查與日志記錄
總結
本文完整展示了基于Python生態構建人臉識別考勤系統的全過程,從數據采集到模型部署,涵蓋了計算機視覺應用的典型流程。通過實踐,讀者不僅掌握了具體技術的實現細節,更能理解系統設計中的權衡與優化思路。該系統可進一步擴展為更復雜的應用場景,如結合門禁控制、體溫檢測等功能,構建智慧辦公解決方案。
希望本文能成為你探索計算機視覺領域的起點,激發更多創新應用的靈感!