要实现一个人脸识别系统,可以使用 Python 的 OpenCV 和 face_recognition 模块。下面是一个简单的人脸识别系统实现的示例代码:
import cv2
import face_recognition
# 加载已知人脸图像和相应名称
known_face_encodings = []
known_face_names = []
for i in range(1, 4):
image = face_recognition.load_image_file('known_faces/{}.jpg'.format(i))
face_encoding = face_recognition.face_encodings(image)[0]
known_face_encodings.append(face_encoding)
known_face_names.append('Person {}'.format(i))
# 打开摄像头
cap = cv2.VideoCapture(0)
while True:
# 读取摄像头画面
ret, frame = cap.read()
# 转换画面颜色格式
rgb_frame = frame[:, :, ::-1]
# 检测当前画面中的人脸
face_locations = face_recognition.face_locations(rgb_frame)
face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)
# 对检测到的人脸进行识别
for face_encoding, face_location in zip(face_encodings, face_locations):
matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
# 如果找到了匹配的人脸,则在画面上显示名称标签
if True in matches:
match_index = matches.index(True)
name = known_face_names[match_index]
top, right, bottom, left = face_location
cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
cv2.putText(frame, name, (left + 6, bottom - 6), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 255), 1)
# 显示画面
cv2.imshow('frame', frame)
# 等待按键事件
key = cv2.waitKey(1)
if key == ord('q'):
break
# 关闭摄像头
cap.release()
cv2.destroyAllWindows()
运行此程序将会打开电脑的摄像头,并检测当前画面中的人脸,并将识别出的人脸名称标签添加到画面上。你可以根据自己的需要使用 OpenCV 和 face_recognition 模块中的其他函数和方法来实现更多的人脸识别系统功能。
未经允许不得转载:445IT之家 » 用python实现脸识别系统 超简单