人脸识别代码

import cv2
import dlib

# 加载人脸检测器
detector = dlib.get_frontal_face_detector()

# 加载人脸特征提取器
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")

# 加载人脸识别模型
face_recognition = dlib.face_recognition_model_v1("dlib_face_recognition_resnet_model_v1.dat")

# 加载已知人脸图像
known_face_image = cv2.imread("known_face.jpg")

# 检测人脸并提取特征
face_rects = detector(known_face_image, 1)
face_shapes = []
for rect in face_rects:
    shape = predictor(known_face_image, rect)
    face_shapes.append(shape)
face_descriptors = []
for face_shape in face_shapes:
    face_descriptor = face_recognition.compute_face_descriptor(known_face_image, face_shape)
    face_descriptors.append(face_descriptor)

# 打开摄像头进行实时识别
cap = cv2.VideoCapture(0)
while True:
    ret, frame = cap.read()
    if not ret:
        break
    # 检测人脸并提取特征
    face_rects = detector(frame, 1)
    face_shapes = []
    for rect in face_rects:
        shape = predictor(frame, rect)
        face_shapes.append(shape)
    face_descriptors = []
    for face_shape in face_shapes:
        face_descriptor = face_recognition.compute_face_descriptor(frame, face_shape)
        face_descriptors.append(face_descriptor)
    # 进行人脸匹配
    matches = []
    for face_descriptor in face_descriptors:
        distance = dlib.distance(face_descriptor, face_descriptors[0])
        matches.append(distance < 0.5)
    # 画出人脸框和匹配结果
    for i, face_rect in enumerate(face_rects):
        color = (0, 255, 0) if matches[i] else (0, 0, 255)
        cv2.rectangle(frame, (face_rect.left(), face_rect.top()), (face_rect.right(), face_rect.bottom()), color, 2)
    # 显示画面
    cv2.imshow("Face Recognition", frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# 释放摄像头并关闭窗口
cap.release()
cv2.destroyAllWindows()

你可能感兴趣的:(计算机视觉,opencv,python)