正文是解释,若懒得看解释就直接到最下方找完整代码
如果需要dlib库的5点或者68点的dat文件,可在下方blog下载
https://blog.csdn.net/Mimido_luoluo/article/details/107774321
使用dlib库可以实现对人脸68个关键点进行标定,还可以搞5个点的标定,只需更换dat文件即可
首先需要引用dat文件、加载检测器预测器:
dlib.get_frontal_face_detector()可以获取人脸检测器
dlib.shape_predictor(dat文件路径)可以配上检测使用的dat文件
predictor_path = "shape_predictor_68_face_landmarks.dat"
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(predictor_path)
之后需要打开摄像头:
captureframe = cv2.VideoCapture(0)
注意:部分电脑可能会有terminating async callback之类的报错,可以用下面代码解决,即后方加一个cv2.CAP_DSHOW
captureframe = cv2.VideoCapture(0 , cv2.CAP_DSHOW)
接下来便是主循环,对摄像头获取图片逐帧处理
使用 while(1) 实现
在while(1)内:
首先获取一帧图片并且转换为灰度图
前面 ReturnValue 是返回 Bool 值,用以表示图片是否读取正确,本程序中用处不大;后者 frame 才是返回的图片值
转化灰度图用 cvtColor,你懂得
ReturnValue, frame = captureframe.read()
gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
检测灰度图片的人脸位置返回给 rects
返回的是人脸所在的区域即rectangles的坐标的首元素地址,如下图
rects = detector(gray,1)
之后需要遍历 rects 元素,即所有的人脸,对每一个人脸检测68个特征点,并保存坐标到 landmarks
for i in range(len(rects)):
landmarks = np.matrix([[p.x,p.y] for p in predictor(gray,rects[i]).parts()])
下一步对提取到的点进行遍历,并在原来的彩色图画点
for idx,point in enumerate(landmarks):
pos=(point[0,0],point[0,1])
points_keys.append([point[0,0],point[0,1]])
cv2.circle(frame,pos,2,(255,0,0),-1)
最后显示图片并进行短暂延迟:
cv2.imshow('frame',frame)
cv2.waitKey(5)
完整代码:
import dlib
import numpy as np
import cv2
predictor_path = "shape_predictor_68_face_landmarks.dat"
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(predictor_path)
points_keys = []
captureframe = cv2.VideoCapture(0 , cv2.CAP_DSHOW)
while(1):
ReturnValue, frame = captureframe.read()
gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
rects = detector(gray,1)
for i in range(len(rects)):
landmarks = np.matrix([[p.x,p.y] for p in predictor(gray,rects[i]).parts()])
for idx,point in enumerate(landmarks):
pos=(point[0,0],point[0,1])
points_keys.append([point[0,0],point[0,1]])
cv2.circle(frame,pos,2,(255,0,0),-1)
cv2.imshow('frame',frame)
cv2.waitKey(5)