1、图片识别
注意点:
1. dlib.get_frontal_face_detector( ) 获取人脸检测器
2. dlib.shape_predictor( ) 预测人脸关键点
人脸关键点模型,下载地址:
# 1 加入库
import cv2
import matplotlib.pyplot as plt
import dlib
# 2 读取一张图片
image = cv2.imread("Tom.jpeg")
# 3 调用人脸检测器
detector = dlib.get_frontal_face_detector()
# 4 加载预测关键点模型(68个关键点)
# 人脸关键点模型,下载地址:
# http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2.
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
# 5 灰度转换
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 6 人脸检测
faces = detector(gray, 1)
# 7 循环,遍历每一张人脸,给人脸绘制矩形框和关键点
for face in faces: #(x, y, w, h)
# 8 绘制矩形框
cv2.rectangle(image, (face.left(), face.top()), (face.right(), face.bottom()), (0,255,0), 2)
# 9 预测关键点
shape = predictor(image, face)
# 10 获取到关键点坐标
for pt in shape.parts():
# 获取横纵坐标
pt_position = (pt.x, pt.y)
# 11 绘制关键点坐标
cv2.circle(image, pt_position, 1, (255, 0, 0), -1)# -1填充,2表示大小
# 12 显示整个效果图
plt.imshow(image)
plt.axis("off")
plt.show()
2、电脑摄像头识别
# 1 加入库
import cv2
import dlib
# 2 打开摄像头
capture = cv2.VideoCapture(0)
# 3 获取人脸检测器
detector = dlib.get_frontal_face_detector()
# 4 获取人脸关键点检测模型
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
while True:
# 5 读取视频流
ret, frame = capture.read()
# 6 灰度转换
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 7 人脸检测
faces = detector(gray, 1)
# 8 绘制每张人脸的矩形框和关键点
for face in faces:
# 8.1 绘制矩形框
cv2.rectangle(frame, (face.left(), face.top()), (face.right(), face.bottom()), (0,255,0), 3)
# 8.2 检测到关键点
shape = predictor(gray, face) #68个关键点
# 8.3 获取关键点的坐标
for pt in shape.parts():
# 每个点的坐标
pt_position = (pt.x, pt.y)
# 8.4 绘制关键点
cv2.circle(frame, pt_position, 3, (255,0,0), -1)
if cv2.waitKey(1) ÿ= ord('q'):
break
# 9 显示效果
cv2.imshow("face detection landmark", frame)
capture.release()
cv2.destroyAllWindows()