opencv入门基础(八)基于dlib进行人脸关键点检测
一.基础知识
1.dlib.get_frontal_face_detector()获取人脸检测器
2.dlib.shape_predictor()预测人脸关键点
二.本地图片具体实现
运用已经训练好的人脸关键点检测器,分为5点和68点两种。
检测器下载链接:https://pan.baidu.com/s/1rnqP5OxaY11kJisVrQa3TQ
提取码:ayai
下载后将检测器放在项目目录中:
import cv2
import numpy as np
import matplotlib.pyplot as plt
import dlib
# 读取一张图片
# 调用人脸检测器
# 加载预测关键点模型(68个关键点)
# 灰度转换
# 人脸检测
# 循环,遍历每一张人脸,给人脸绘制矩形框和关键点
# 绘制矩形框
# 预测关键点
# 获取关键点坐标
# 显示/绘制关键点
# 显示整个效果图
image = cv2.imread("Taylor.jpg")
detector = dlib.get_frontal_face_detector()
# 加载预测关键点模型(68个点的)
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
faces = detector(gray,1) # 1表示图片增大一倍
# 循环遍历每一张人脸,为每一张人脸绘制关键点和矩形框
for face in faces:
cv2.rectangle(image.copy(),(face.left(),face.top()),(face.right(),face.bottom()),(0,255,0),5)
# 预测关键点
shape = predictor(image,face)
# 获取关键点坐标
for pt in shape.parts():
# 获取横纵坐标
pt_position = (pt.x,pt.y)
# 绘制关键点坐标
cv2.circle(image,pt_position,5,(255,0,0),-1) # -1表示颜色填充关键点圆圈
plt.imshow(image)
plt.show()
结果为:
三.摄像头实时检测
import matplotlib.pyplot as plt
import dlib
import cv2
capture = cv2.VideoCapture(0)
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
while True:
ret,frame = capture.read()
gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
faces = detector(gray,1)
for face in faces:
cv2.rectangle(frame, (face.left(), face.top()), (face.right(), face.bottom()), (0, 255, 0), 5)
shape = predictor(frame, face)
for pt in shape.parts():
pt_position = (pt.x, pt.y)
cv2.circle(frame, pt_position, 5, (255, 0, 0), -1)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.imshow("face detection landmark",frame)
capture.release()
cv2.destroyWindow()
结果为:
四.基于face_recognition进行人脸关键点检测
1.face_recognition使用世界上最简单的人脸识别工具,它使用dlib最先进的人脸识别技术构建而成,并具有深度学习功能。
给出face_recognition相关内容链接:
github地址:https://github.com/ageitgey/face_recognition
官方指南:https://face-recognition.readthedocs.io/en/latest/readme.html
源码底层实现:https://face-recognition.readthedocs.io/en/latest/face_recognition.html