在使用 dlib 检测面部标志后,有没有办法在面部选择特定点?

问题描述

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

Shape predictor 68 face landmarks

我已经设法从预测的地标中访问特定点,例如,我可以通过以下方式选择位于唇角的点,这是面部地标预测器中的第 48 个点 ' 导入 cv2 导入数据库 从 google.colab.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,255),-1)
cv2_imshow(img)'

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

这张图会详细说明:

Image

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

解决方法

我可能会向您推荐几种解决方案:

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,255),-1)
cv2.imshow('Show',img )
cv2.waitKey(0)
cv2.destroyAllWindows()

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

3- 困难的方法是重新训练和自定义您自己的形状检测器:Train a face landmarking model

对于地标索引,我使用了以下参考: Face reference points