人脸检测在系列二中,使用了dlib自带的人脸检测器(detector),关键点提取需要一个特征提取器(predictor),为了构建特征提取器,预训练模型必不可少。
官方提供了训练自己模型的例子,除了自行进行训练外,还可以使用官方提供的一个模型。该模型可从dlib sourceforge库下载:
http://sourceforge.net/projects/dclib/files/dlib/v18.10/shape_predictor_68_face_landmarks.dat.bz2
这个库支持68个关键点的提取,face++提供了102个特征点,如果需要更多的特征点,我们需要自己去训练。
# -*-encoding=utf-8-*-
import sys
import dlib
import cv2
import os
current_path = os.getcwd()
#predictor_path = current_path +'\\model\\shape_predictor_68_face_landmarks.dat'
predictor_path = current_path +'./model/shape_predictor_68_face_landmarks.dat'
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(predictor_path)
for f in sys.argv[1:]:
img = cv2.imread(f, cv2.IMREAD_COLOR)
dets = detector(img, 2)
print("Number of faces detected: {}".format(len(dets)))
for index, face in enumerate(dets):
print('face {}; left {}; top {}; right {}; bottom {}'.format(index, face.left(), face.top(), face.right(), face.bottom()))
shape = predictor(img,face)
for index, pt in enumerate(shape.parts()):
print('part{}:{}'.format(index, pt))
pt_pos = (pt.x, pt.y)
cv2.circle(img, pt_pos, 2, (255,0,0), 1)
left = face.left()
top = face.top()
right = face.right()
bottom = face.bottom()
cv2.rectangle(img, (left, top), (right, bottom), (0, 255, 0), 1)
cv2.namedWindow(f, cv2.WINDOW_AUTOSIZE)
cv2.imshow(f, img)
k = cv2.waitKey(0)
cv2.destroyAllWindows()
运行命令为python xxx.py 1.jpg
如果是在pycharm ide 中,则只需在Edit Configurations 中的Script parameters项中配置1.jpg即可
试验原始图:
试验结果图: