实现人脸识别的python库有很多,这里以OpenCV和face_recognition为例,具体实现步骤如下:
1. 安装OpenCV和face_recognition库
pip install opencv-python
pip install face_recognition
2. 获取人脸图像并存储
import cv2
# 打开摄像头
cap = cv2.VideoCapture(0)
while True:
# 读取一帧图像
ret, frame = cap.read()
# 显示图像
cv2.imshow('video', frame)
# 按下q键退出
if cv2.waitKey(1) & 0xff == ord('q'):
break
# 释放摄像头资源
cap.release()
cv2.destroyAllWindows()
3. 对图像进行人脸检测
import face_recognition
# 将图像转为RGB格式
rgb_frame = frame[:, :, ::-1]
# 检测人脸位置
face_locations = face_recognition.face_locations(rgb_frame)
4. 对每个人脸进行识别
# 加载预先训练好的人脸数据
known_image = face_recognition.load_image_file("known_face.jpg")
known_encoding = face_recognition.face_encodings(known_image)[0]
# 对检测到的每个人脸进行识别
for face_location in face_locations:
# 提取人脸编码
unknown_encoding = face_recognition.face_encodings(rgb_frame, [face_location])[0]
# 比对人脸
results = face_recognition.compare_faces([known_encoding], unknown_encoding)
if results[0]:
# 识别成功
print("This is known_face.")
else:
# 识别失败
print("Unknown face.")
完整代码如下:
import cv2
import face_recognition
# 加载预先训练好的人脸数据
known_image = face_recognition.load_image_file("known_face.jpg")
known_encoding = face_recognition.face_encodings(known_image)[0]
# 打开摄像头
cap = cv2.VideoCapture(0)
while True:
# 读取一帧图像
ret, frame = cap.read()
# 将图像转为RGB格式
rgb_frame = frame[:, :, ::-1]
# 检测人脸位置
face_locations = face_recognition.face_locations(rgb_frame)
# 对每个人脸进行识别
for face_location in face_locations:
# 提取人脸编码
unknown_encoding = face_recognition.face_encodings(rgb_frame, [face_location])[0]
# 比对人脸
results = face_recognition.compare_faces([known_encoding], unknown_encoding)
if results[0]:
# 识别成功
cv2.rectangle(frame, (face_location[3], face_location[0]), (face_location[1], face_location[2]), (0, 255, 0), 2)
cv2.putText(frame, "Known Face", (face_location[3], face_location[2] + 20), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
else:
# 识别失败
cv2.rectangle(frame, (face_location[3], face_location[0]), (face_location[1], face_location[2]), (0, 0, 255), 2)
cv2.putText(frame, "Unknown Face", (face_location[3], face_location[2] + 20), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)
# 显示图像
cv2.imshow('video', frame)
# 按下q键退出
if cv2.waitKey(1) & 0xff == ord('q'):
break
# 释放摄像头资源
cap.release()
cv2.destroyAllWindows()