使用Python的face_recognition
库搭建人脸识别系统,可按以下步骤操作,适用于门禁、签到等场景:
一、环境准备
-
安装依赖库
face_recognition
基于dlib
实现,需先安装相关依赖:
# 安装dlib(Windows建议通过conda或预编译whl,Linux/macOS可直接pip) pip install cmake # 编译依赖 pip install dlib # 安装face_recognition和OpenCV(用于图像/视频处理) pip install face_recognition opencv-python
-
准备人脸数据库 创建文件夹(如known_faces
),存放已知人员的人脸照片(每人1-3张清晰正脸照,文件名建议为姓名,如zhangsan.jpg
)。
二、核心功能实现
1. 人脸检测与编码
将人脸图像转换为128维特征向量(人脸编码),用于后续比对:
import face_recognition import cv2 # 加载已知人脸并生成编码 def load_known_faces(known_dir="known_faces"): known_encodings = [] known_names = [] for filename in os.listdir(known_dir): if filename.endswith(('.jpg', '.png')): name = os.path.splitext(filename)[0] image = face_recognition.load_image_file(f"{known_dir}/{filename}") # 获取人脸编码(假设每张图仅1张人脸) encoding = face_recognition.face_encodings(image)[0] known_encodings.append(encoding) known_names.append(name) return known_encodings, known_names
2. 人脸比对
比较输入人脸编码与数据库编码的相似度,tolerance
为阈值(默认0.6,值越小越严格):
def recognize_face(unknown_image, known_encodings, known_names, tolerance=0.6): # 检测人脸并生成编码 face_locations = face_recognition.face_locations(unknown_image) face_encodings = face_recognition.face_encodings(unknown_image, face_locations) results = [] for encoding in face_encodings: # 与数据库比对 matches = face_recognition.compare_faces(known_encodings, encoding, tolerance) name = "Unknown" # 取最相似的匹配结果 if True in matches: first_match_idx = matches.index(True) name = known_names[first_match_idx] results.append(name) return face_locations, results
3. 实时摄像头识别
结合OpenCV调用摄像头,实时检测并标注人脸:
def realtime_recognition(known_encodings, known_names): video_capture = cv2.VideoCapture(0) # 0表示默认摄像头 while True: ret, frame = video_capture.read() if not ret: break # 缩小图像以提高速度(可选) small_frame = cv2.resize(frame, (0, 0), fx=0.5, fy=0.5) rgb_small_frame = small_frame[:, :, ::-1] # BGR转RGB # 识别人脸 face_locations, names = recognize_face(rgb_small_frame, known_encodings, known_names) # 绘制边框和姓名 for (top, right, bottom, left), name in zip(face_locations, names): # 还原缩放后的坐标 top *= 2 right *= 2 bottom *= 2 left *= 2 # 画矩形框 cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2) # 标注姓名 cv2.putText(frame, name, (left, top - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) cv2.imshow('Face Recognition', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break video_capture.release() cv2.destroyAllWindows()
三、系统集成与应用
以员工门禁系统为例,完整流程如下:
-
初始化数据库:加载员工人脸照片生成编码。
-
实时检测:摄像头捕捉人脸,生成编码并比对。
-
结果处理:匹配成功则开门(可通过GPIO控制硬件),失败则触发警报。
if __name__ == "__main__": known_encodings, known_names = load_known_faces() print(f"Loaded {len(known_names)} known faces.") realtime_recognition(known_encodings, known_names)
四、注意事项
-
安装问题:Windows安装
dlib
可能需手动下载预编译whl(如Unofficial Windows Binaries )。
-
性能优化:使用
model='cnn'
(face_locations
函数参数)提升检测精度,但速度较慢;可缩小图像尺寸或使用GPU加速。
-
准确率影响:确保人脸图像光照均匀、无遮挡,数据库样本覆盖不同角度和表情。
通过以上步骤,可快速搭建轻量级人脸识别系统,适用于个人项目或小型应用场景。