最近一直在做有关人脸识别的一些东西,今天来记录一下如何使用face_recognition和dlib实时标记人脸特征。很简单的东西,各位大佬见笑了。有关环境的配置以及各种库的安装欢迎移步我的这两篇博客,《face_recognition+python-opencv实现摄像头实时人脸识别》和《Python3.7安装dlib19.17,亲测可行!!!》。
dlib提供了训练好的模型,可以识别人脸的68个特征点。 dlib模型没有的评论或私信就行,我发给你。
face_recognition是基于dlib开发的,二者用的模型应该是相同的,这当你用了两种方法都标定出来的时候就知道了。
开始代码吧
首先是dlib获取特征点并标定。
camera = cv2.VideoCapture(0)
current_path = os.getcwd()
predictor_path = current_path + "\\model\\shape_predictor_68_face_landmarks.dat" #
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(predictor_path)
dets = detector(img, 1)
for index, face in enumerate(dets):
left = face.left()
top = face.top()
right = face.right()
bottom = face.bottom()
cv2.rectangle(img, (left, top), (right, bottom), (0, 255, 0), 3)
shape = predictor(img, face)
for index, pt in enumerate(shape.parts()):
pt_pos = (pt.x, pt.y)
cv2.circle(img, pt_pos, 2, (255, 0, 0), 1)
detector就是用来进行人脸检测的,调用它可以得到图片中包含的所有人脸以及人脸相关的一些信息比如包含人脸的区域等等。predictor 可以用到detector得到的信息得到人脸的68个特征点。
接下来是face_recognition获取特征点并标定。
face_landmarks_list = face_recognition.face_landmarks(img)
if len(face_landmarks_list) != 0:
for index, name in enumerate(face_landmarks_list[0]):
pt = face_landmarks_list[0].get(name)
for i in range(len(pt)):
# pt_pos = (pt[i].x, pt[i].y)
cv2.circle(img, pt[i], 2, (0, 0, 255), 2)
可以看到这种方法相对于第一种方法要简洁的多。face_recognition.face_landmarks返回的是一个字典,里面内容如下图所示:
要取出来并显示也比较方便,就不详细说取出来并实时显示的方法了,附上完整代码大家可以看看。
import dlib
import face_recognition
import cv2
import os
camera = cv2.VideoCapture(0)
current_path = os.getcwd() # 获取当前路径
predictor_path = current_path + "\\model\\shape_predictor_68_face_landmarks.dat" #
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(predictor_path)
while True:
success,img = camera.read()
dets = detector(img, 1)
for index, face in enumerate(dets):
# 画出人脸的框
left = face.left()
top = face.top()
right = face.right()
bottom = face.bottom()
cv2.rectangle(img, (left, top), (right, bottom), (0, 255, 0), 3)
# dlib
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)
face_landmarks_list = face_recognition.face_landmarks(img)
if len(face_landmarks_list) != 0:
print(face_landmarks_list[0])
for index, name in enumerate(face_landmarks_list[0]):
pt = face_landmarks_list[0].get(name)
print(pt)
for i in range(len(pt)):
cv2.circle(img, pt[i], 2, (0, 0, 255), 2)
cv2.imshow('face', img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
camera.release()
cv2.destroyAllWindows()