首页 > 解决方案 > 有没有办法在使用 dlib 检测面部标志后选择面部的特定点?

问题描述

我正在使用 Dlib 的 68 点人脸界标预测器,它有 68 个点标记在人脸的各个区域,如下图所示:

形状预测器 68 个面部标志

我已经设法从预测的地标中访问特定点,例如,我可以选择一个位于唇角的点,它是面部地标预测器中的第 48 个点,方法是从 google.colab 导入 cv2 .patches 导入 cv2_imshow

p = "path_to_shape_predictor_68_face_landmarks.dat"
img= cv2.imread('Obama.jpg')
gray=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(p)
face = detector(gray)
# Get the shape using the predictor
landmarks=predictor(gray, face)

# Defining x and y coordinates of a specific point
x=landmarks.part(48).x
y=landmarks.part(48).y
# Drawing a circle
cv2.circle(img, (x, y), 6, (0, 0, 255), -1)
cv2_imshow(img)'

它会在指定区域上绘制一个带有红色小圆圈的图像。然而; 如果我想选择一个不属于地标模型的 68 个点的点,我该如何获得它?

这张图会更详细的说明:图片

红色圆圈表示我使用代码访问的点,蓝色圆圈表示所需的点。

标签: pythonopencvimage-processingdlibfacial-landmark-alignment

解决方案


我可能会向您建议几种解决方案:

1-简单的方法是使用三角学和几何学,例如计算左眼的瞳孔:

pupil_x = int((abs(landmarks.part(39).x + landmarks.part(36).x)) / 2) # The midpoint of a line Segment between eye's corners in x axis
pupil_y = int((abs(landmarks.part(39).y + landmarks.part(36).y)) / 2) # The midpoint of a line Segment between eye's corners in y axis
pupil_coordination = (pupil_x, pupil_y)

完整代码:

import cv2
import dlib

detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("shape_predictor_81_face_landmarks.dat")

img = cv2.imread("test.jpg")
(h, w, _) = img.shape
h2 = 600
w2 = int(h2 * h / w)
img = cv2.resize(img , (h2, w2))
img = cv2.flip(img , 1)
gray = cv2.cvtColor(img , cv2.COLOR_BGR2GRAY)
faces = detector(gray)
face = faces[0]
landmarks = predictor(gray, face)

pupil_x = int((abs(landmarks.part(39).x + landmarks.part(36).x)) / 2)
pupil_y = int((abs(landmarks.part(39).y + landmarks.part(36).y)) / 2)
pupil_coordination = (pupil_x, pupil_y)

cv2.circle(img, pupil_coordination, 6, (0, 0, 255), -1)
cv2.imshow('Show', img )
cv2.waitKey(0)
cv2.destroyAllWindows()

2- 其他解决方案是使用更大的面部标志模型,请查看: 81 Facial Landmarks Shape Predictor

3- 困难的方法是重新训练和定制你自己的形状检测器:训练一个人脸标记模型

对于地标索引,我使用了以下参考: 人脸参考点


推荐阅读