作者:富农032884 | 来源:互联网 | 2023-10-15 16:48
1.人脸特征点检测
dlib关键点模型官方有两种,分别为5个点和68个点的,下载地址:
http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2
人脸68个关键点如下:
主要函数:
dlib.get_frontal_face_detector()获取人脸检测器
dlib.shape_predictor()预测人脸关键点。
2.人脸5个关键点检测——图片
# 1.导入库
import cv2
import dlib
import numpy as np
import matplotlib.pyplot as plt# 2.读取一张照片
img=cv2.imread('img_1.jpg')# 3.调用人脸检测器
detector=dlib.get_frontal_face_detector()# 4.加载预测关键点模型(5个关键点)
predictor=dlib.shape_predictor("shape_predictor_5_face_landmarks.dat")# 5.灰度转换
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)# 6.人脸检测
faces=detector(gray,1)# 7.循环,遍历每一张人脸,给人脸绘制矩形和关键点
for face in faces:# 8.绘制矩形框cv2.rectangle(img,(face.left(),face.top()),(face.right(),face.bottom()),(0,0,255),3)# 9.预测关键点shape=predictor(img,face)# 10.获取关键点坐标for pt in shape.parts():# 获取横纵坐标pt_position=(pt.x,pt.y)# 11.显示/检测关键点cv2.circle(img,pt_position,3,(0,255,0),-1)# 12.显示整个效果图
img_RGB=img[:,:,::-1]
plt.imshow(img_RGB)
plt.axis('off')
plt.show()
3.人脸68个关键点检测——图片
# 4.加载预测关键点模型(68个关键点)
predictor=dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
4.人脸68个关键点检测——视频
# 1.导入库
import cv2
import dlib
import numpy as np
import matplotlib.pyplot as plt# 2.打开摄像头
capture=cv2.VideoCapture(0)# 3.调用人脸检测器
detector=dlib.get_frontal_face_detector()# 4.加载预测关键点模型(68个关键点)
predictor=dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")while True:# 6.读取视频流ret,img=capture.read()# 6.灰度转换gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)# 7.人脸检测faces=detector(gray,1)# 8.循环,遍历每一张人脸,给人脸绘制矩形和关键点for face in faces:# 8.1.绘制矩形框cv2.rectangle(img,(face.left(),face.top()),(face.right(),face.bottom()),(0,0,255),3)# 8.2.预测关键点shape=predictor(img,face)# 8.3.获取关键点坐标for pt in shape.parts():# 获取横纵坐标pt_position=(pt.x,pt.y)# 8.4.显示/检测关键点cv2.circle(img,pt_position,3,(0,255,0),-1)if cv2.waitKey(1) & 0xff == ord('q'):break# 9.显示结果cv2.imshow('face detection landmark',img)capture.release()
cv2.destroyAllWindows()