人脸识别代码

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()

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

熬夜写代码的平头哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值