自学内容网 自学内容网

使用Dlib库实现人脸检测和关键点定位

目录

前言

一、安装Dlib库

二、人脸检测

三、人脸关键点定位


前言

        Dlib是一个现代化的 C++ 工具包,提供了一些机器学习算法和工具,特别是在面部识别和人脸关键点检测方面非常流行。它具有易于使用的 Python 接口,并被广泛应用于计算机视觉项目中。

 

一、安装Dlib库

  1. 在这里提供了几个python版本的dlib库文件
  2. 下载dlib库的安装包,
  3. 在安装包所在文件夹输入cmd进入命令提示符
  4. 使用pip进行安装

Dlib库安装文件

 

二、人脸检测

  1. 使用dlib.get_frontal_face_detector() 创建人脸检测器
  2. 导入图片,传入检测器,返回检测到的所有人脸框
  3. 遍历每个人脸框,获取四个边的坐标,拼成左上角和右下角坐标
  4. 然后画出每个人脸的矩形框
import cv2
import dlib

detector = dlib.get_frontal_face_detector()  # 创建人脸检测器
img = cv2.imread('quanjiafu1.jpg')
img = cv2.resize(img, None, fx=0.3, fy=0.3)

faces = detector(img, 2)
# faces = detector(image,n)使用人脸检测器返回检测到的人脸
# 参数:image:待检测的可能含有人脸的图像。
# 参数n:表示采用上采样的次数。上采样会让图像变大,能够检测到更多人脸对象,提高小人脸的检测效果#通常建议将此参数设置为0 或1。较大的值会增加检测的准确性,但会降低处理速度。
# 返回值faces:返回检测图像中的所有人脸。

for face in faces:  # 对每个人脸框进行逐个处理
    x1 = face.left()
    y1 = face.top()
    x2 = face.right()
    y2 = face.bottom()

    cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.imshow('result', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

输出:

 

三、人脸关键点定位

  1. 下载人脸68个关键点的模型 人脸68关键点定位模型
  2. 使用dlib.shape_predictor()载入模型
  3. 使用模型检测人脸的关键点
  4. 使用.parts()属性获取关键点的x,y的坐标
  5. 然后在图片上画出关键点,并写出关键点的序号
import cv2
import dlib
import numpy as np

img = cv2.imread('xzq.png')
img = cv2.resize(img, None, fx=1.3, fy=1.3)

detector = dlib.get_frontal_face_detector()  # 构造人脸检测器
faces = detector(img, 0)  # 检测人脸
print(faces)  # 人脸轮廓矩形的四个顶点
# dlib.shape_predictor 载入模型
predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')

for face in faces:
    shape = predictor(img, face)  # 获取关键点
    landmarks = np.array([[p.x, p.y] for p in shape.parts()])  # 将关键点转换成坐标形式
    for idx, point in enumerate(landmarks):  # 绘制每一张脸的关键点
        pos = [point[0], point[1]]
        cv2.circle(img, pos, 2, color=(0, 255, 0), thickness=- 1)  # 给关键点标出来

        cv2.putText(img, str(idx), pos, cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255, 255, 255), 1, cv2.LINE_AA)  # 给关键点标上序号

cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

输出:


原文地址:https://blog.csdn.net/weixin_65047977/article/details/143028458

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!