人脸关键点检测

本文讨论用DLIB的人脸关键点检测器。用到的库文件包括 Python, dlib, 和 OpenCV, 下面有原程序。

 

人脸关键点检测模型有:

  • Haar cascades: 快但不准确.
  • HOG + Linear SVM: 相对准确但也相对慢.
  • Deep learning-based detectors: 准确高但慢

人脸关键点检测可以用来检测打瞌睡,眨眼睛等

下面是原程序加注解。如需要数据文件请留言。

###############################

# 用法
# python facial.py --shape-predictor shape_predictor_68_face_landmarks.dat --image images/example_01.jpg 

# 引入相关库文件
from imutils import face_utils
import numpy as np
import argparse
import imutils
import dlib
import cv2

# 构造输入参数
ap = argparse.ArgumentParser()
ap.add_argument("-p", "--shape-predictor", required=True,
    help="人脸关键点检测模型路径")
ap.add_argument("-i", "--image", required=True,
    help="检测图形路径")
args = vars(ap.parse_args())

# 初始化并使用dlib's HOG 人脸检测器 
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(args["shape_predictor"])

# 加载图片,设置尺寸,用灰色图
image = cv2.imread(args["image"])
image = imutils.resize(image, width=500)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# 检测人脸关键点
rects = detector(gray, 1)

# 循环人脸关键点
for (i, rect) in enumerate(rects):
    # 把人脸关键点换成NumPy数组
    shape = predictor(gray, rect)
    shape = face_utils.shape_to_np(shape)

    # 把 dlib's 类型 换成 OpenCV 边框类型
    # 画出边框
    (x, y, w, h) = face_utils.rect_to_bb(rect)
    cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)

    # 显示人脸关键点号
    cv2.putText(image, "Face #{}".format(i + 1), (x - 10, y - 10),
        cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)

    # 画出人脸关键点
    for (x, y) in shape:
        cv2.circle(image, (x, y), 1, (0, 0, 255), -1)

# 显示图形
cv2.imshow("Output", image)
cv2.waitKey(0)
posted @ 2021-02-01 01:26  wodeboke-1  阅读(353)  评论(0)    收藏  举报