使用Python编写一个简单的人脸识别系统
发布时间:2023-12-04 11:42:14
人脸识别是一种用于识别和验证人脸的技术,它通常用于安全性访问控制和身份验证等应用程序中。Python是一种非常流行的编程语言,它具有丰富的图像处理和计算机视觉库,如OpenCV和Dlib,可以很方便地实现人脸识别系统。
下面是一个使用Python编写的简单人脸识别系统的示例代码:
import cv2
import dlib
# 人脸检测器
detector = dlib.get_frontal_face_detector()
# 人脸关键点检测器
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
# 人脸识别模型
facerec = dlib.face_recognition_model_v1("dlib_face_recognition_resnet_model_v1.dat")
# 加载已知人脸数据
known_face_encodings = []
known_face_names = []
# 添加已知人脸的编码和名称
def add_known_face_encoding(encoding, name):
known_face_encodings.append(encoding)
known_face_names.append(name)
# 从图像中获取人脸编码
def get_face_encoding(image):
face_locations = detector(image, 1)
landmarks = [predictor(image, face_location) for face_location in face_locations]
return [facerec.compute_face_descriptor(image, landmark_set, 1) for landmark_set in landmarks]
# 从图像中识别人脸并返回名称
def recognize_faces(image):
face_encodings = get_face_encoding(image)
face_names = []
for face_encoding in face_encodings:
matches = facerec.face_distance(known_face_encodings, face_encoding)
min_distance_index = matches.argmin()
if matches[min_distance_index] < 0.5:
name = known_face_names[min_distance_index]
else:
name = "Unknown"
face_names.append(name)
return face_names
# 加载已知人脸数据
add_known_face_encoding("known_face_encoding_1", "Person 1")
add_known_face_encoding("known_face_encoding_2", "Person 2")
# ...
# 从摄像头中实时识别人脸并显示名称
video_capture = cv2.VideoCapture(0)
while True:
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
face_names = recognize_faces(gray)
for (top, right, bottom, left), name in zip(face_locations, face_names):
cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
cv2.putText(frame, name, (left, top), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
cv2.imshow("Video", frame)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
video_capture.release()
cv2.destroyAllWindows()
在上述代码中,我们首先使用Dlib库中的人脸检测器和关键点检测器定位人脸及其关键点。然后,我们使用Dlib中的人脸识别模型计算人脸的128维编码。接下来,我们通过比较已知人脸编码和检测到的人脸编码之间的欧氏距离来识别人脸。如果距离小于0.5,则被判定为已知人脸,否则为未知人脸。
我们可以通过调用add_known_face_encoding()函数来添加已知人脸的编码和名称。在实际应用中,可以使用多种方法来生成和加载已知人脸的编码,如从图像文件中提取、从数据库中读取等。
最后,我们使用OpenCV库来实时从摄像头中捕获图像,并调用recognize_faces()函数来识别人脸并在图像上显示名称。
需要注意的是,上述代码只是一个简单的示例,实际应用中可能还需要进行更多的优化和处理,如人脸对齐、活体检测等。另外,为了获得更好的人脸识别效果,可能需要更多的已知人脸数据用于训练和匹配。
