利用conda 安装
conda install cmake
conda install dlib
失败的话,参考安装教程
前往安装教程
官方文档:http://dlib.net/python/
人脸关键的方法有两个:
检测人脸:dlib.get_frontal_face_detector()
关键点检测:dlib.shape_predictor
第二个方法需要引入模型数据文件:
点击下载:https://download.csdn.net/download/monk96/86930067
也可以去官网下载(非常慢:)http://dlib.net/files/
放到指定目录,等回读取需要用到
开始编码:
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor('./shape_predictor_68_face_landmarks/shape_predictor_68_face_landmarks.dat')
# cv2读取图像
img = cv2.imread("i.png")
# 取灰度
img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
得到预测的所有人脸数
# 人脸数rects
rects = detector(img_gray, 0)
将所有的人脸点位绘制出来
for i in range(len(rects)):
cv2.rectangle(img, (rects[i].left(), rects[i].top()), (rects[i].right(), rects[i].bottom()), color= (255, 0, 255))
faces = predictor(img, rects[i]).parts()
points = np.matrix([[p.x, p.y] for p in faces])
for idx, point in enumerate(points):
pos = (point[0, 0], point[0, 1])
cv2.circle(img, pos, 2, (0, 0, 255), 1)
cv2.putText(img, str(idx + 1), pos, cv2.FONT_HERSHEY_SIMPLEX, 0.3, (0, 255, 255))
import numpy as np
import dlib
import cv2
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor('./shape_predictor_68_face_landmarks/shape_predictor_68_face_landmarks.dat')
# cv2读取图像
img = cv2.imread("i.png")
# 取灰度
img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# 人脸数rects
rects = detector(img_gray, 0)
for i in range(len(rects)):
cv2.rectangle(img, (rects[i].left(), rects[i].top()), (rects[i].right(), rects[i].bottom()), color= (255, 0, 255))
faces = predictor(img, rects[i]).parts()
points = np.matrix([[p.x, p.y] for p in faces])
for idx, point in enumerate(points):
pos = (point[0, 0], point[0, 1])
cv2.circle(img, pos, 2, (0, 0, 255), 1)
cv2.putText(img, str(idx + 1), pos, cv2.FONT_HERSHEY_SIMPLEX, 0.3, (0, 255, 255))
cv2.imshow("img", img)
cv2.waitKey(0)
接下来可以利用点位做一些相关方面的实验,如疲劳检测, 表情检测