博客
关于我
人脸跟踪、识别、脸部标识
阅读量:735 次
发布时间:2019-03-22

本文共 3978 字,大约阅读时间需要 13 分钟。

使用 dlib 进行人脸识别与特征提取

项目概述

在这个项目中,我们将使用 dlib 库来实现人脸识别和特征提取任务。目标是通过摄像头输入实时采集视频流,将目标人脸识别并标注关键特征点。本文将详细介绍实现过程,包括人脸跟踪、特征提取以及识别匹配等关键步骤。

人脸跟踪与特征提取

技术选型与配置

为了实现人脸识别,我们选择使用 dlib 库。具体来说,dlib 提供了两个核心组件:

  • 人脸跟踪检测器:通过 dlib.get_frontal_face_detector() 获取一个用于检测面部区域的前置面部检测器。
  • 特征点预测器:使用 dlib.shape_predictor 预测 68 个面部关键点的位置。
  • 此外,我们还需要以下模型文件:

    • shape_predictor_68_face_landmarks.dat:用于提取面部特征点的预测模型。
    • dlib_face_recognition_resnet_model_v1.dat:用于将面部特征映射为 128 维向量的模型。

    代码实现

    import dlibimport cv2import numpy as npfrom imutils import face_utils# 预定义路径predictor_path = 'models\\shape_predictor_68_face_landmarks.dat'face_rec_model_path = 'models\\dlib_face_recognition_resnet_model_v1.dat'# 初始化人脸检测器和特征提取器detector = dlib.get_frontal_face_detector()predictor = dlib.shape_predictor(predictor_path)facerec = dlib.face_recognition_model_v1(face_rec_model_path)# 获取鼻子特征索引(noseStart, noseEnd) = face_utils.FACIAL_LANDMARKS_IDXS["nose"]

    鼻子特征标识

    在实际应用中,我们还需要对目标人脸进行鼻子区域的标识。这可以通过以下步骤实现:

  • 读取图像并预处理

    success, img = cap.read()frame = imutils.resize(img, width=300)gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
  • 检测人脸区域

    rects = detector(gray, 0)rect = rects[0]  # 假设只检测到一个人脸
  • 提取特征点

    shape = predictor(gray, rect)shape = face_utils.shape_to_np(shape)
  • 提取鼻子区域

    nose = shape[noseStart:noseEnd]noseHull = cv2.convexHull(nose)cv2.drawContours(frame, [noseHull], -1, (0, 255, 0), 1)cv2.putText(frame, "nose", (nose[0][0], nose[0][1]), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
  • 特征描述与计算

    为了实现面部特征的描述,我们使用 dlib 提供的面部特征描述模型。具体实现如下:

  • 特征向量计算

    face_vector = facerec.compute_face_descriptor(img, shape)
  • 特征距离计算

    def distance(a, b):    a, b = np.array(a), np.array(b)    sub = np.sum((a - b) ** 2)    add = (np.sum(a ** 2) + np.sum(b ** 2)) / 2    return sub / add
  • 人脸识别与匹配

    匹配逻辑

    我们需要将输入人脸与已知特征进行匹配。具体实现如下:

  • 初始化特征库

    faces = [    (get_feature('faces\\dbh.jpg'), 'McKay')]
  • 匹配过程

    def process_face_id(faces, frame, rect, shape):    found_face_id = 'Unknown'    if len(faces) > 0:        face_descriptor = facerec.compute_face_descriptor(frame, shape)        min_face_id = found_face_id        min_face_distance = 1        for face_feature, face_id in faces:            cur_distance = distance(face_feature, face_descriptor)            if cur_distance < min_face_distance:                min_face_distance = cur_distance                min_face_id = face_id        if min_face_distance < threshold:            found_face_id = min_face_id    cv2.rectangle(frame, (rect.left(), rect.top() + 10), (rect.right(), rect.bottom()), (0, 255, 0), 2)    cv2.putText(frame, found_face_id, (rect.left(), rect.top()), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2, cv2.LINE_AA)    if found_face_id != 'Unknown':        events.append(('user_found', found_face_id, time.time()))
  • 代码实现

    import dlibimport cv2import numpy as npfrom imutils import face_utils# 预定义路径predictor_path = 'models\\shape_predictor_68_face_landmarks.dat'face_rec_model_path = 'models\\dlib_face_recognition_resnet_model_v1.dat'# 初始化人脸检测器和特征提取器detector = dlib.get_frontal_face_detector()predictor = dlib.shape_predictor(predictor_path)facerec = dlib.face_recognition_model_v1(face_rec_model_path)# 获取鼻子特征索引(noseStart, noseEnd) = face_utils.FACIAL_LANDMARKS_IDXS["nose"]# 特征描述计算函数def get_feature(path):    img = cv2.imread(path)    frame = img    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)    dets = detector(gray, 0)    shape = predictor(gray, dets[0])    face_vector = facerec.compute_face_descriptor(frame, shape)    return face_vector# 特征距离计算函数def distance(a, b):    a, b = np.array(a), np.array(b)    sub = np.sum((a - b) ** 2)    add = (np.sum(a ** 2) + np.sum(b ** 2)) / 2    return sub / add# 初始化特征库faces = [(get_feature('faces\\dbh.jpg'), 'McKay')]# 初始化摄像头和事件记录cap = cv2.VideoCapture(0)success = Noneevents = []

    依赖安装

    为了运行上述代码,您需要安装以下依赖:

    pip install dlibpip install opencv-pythonpip install numpypip install imutilspip install imageio

    代码结构说明

  • 导入库和初始化:加载所需的库和预定义模型路径。
  • 人脸检测与特征提取:通过 dlib 检测人脸区域并提取特征点。
  • 特征描述与匹配:计算特征向量并与已知库进行匹配。
  • 实时识别与展示:在摄像头输入流中实时检测并标注人脸特征。
  • 通过以上实现,我们成功完成了人脸识别与特征提取的整个流程。

    转载地址:http://eckwk.baihongyu.com/

    你可能感兴趣的文章
    no available service ‘default‘ found, please make sure registry config corre seata
    查看>>
    No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
    查看>>
    no connection could be made because the target machine actively refused it.问题解决
    查看>>
    No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
    查看>>
    No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
    查看>>
    No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
    查看>>
    No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
    查看>>
    No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
    查看>>
    No module named 'crispy_forms'等使用pycharm开发
    查看>>
    No module named cv2
    查看>>
    No module named tensorboard.main在安装tensorboardX的时候遇到的问题
    查看>>
    No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
    查看>>
    No new migrations found. Your system is up-to-date.
    查看>>
    No qualifying bean of type XXX found for dependency XXX.
    查看>>
    No qualifying bean of type ‘com.netflix.discovery.AbstractDiscoveryClientOptionalArgs<?>‘ available
    查看>>
    No resource identifier found for attribute 'srcCompat' in package的解决办法
    查看>>
    no session found for current thread
    查看>>
    No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
    查看>>
    NO.23 ZenTaoPHP目录结构
    查看>>
    no1
    查看>>