OpenCV基于dlib进行人脸关键点检测(摄像头)

1. dlib.get_frontal_face_detector()获取人脸检测器

2. dlib.shape_predictor()预测人脸关键点

人脸关键点模型,下载地址:
http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2

把下载好的压缩包解压放在项目中
如图所示:
OpenCV基于dlib进行人脸关键点检测(摄像头)_第1张图片

代码实现:

# 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)# 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)
        #8.3 获取关键点坐标
        for pt in shape.parts():
            # 每个点的坐标
            pt_position = (pt.x, pt.y)
            # 绘制关键点
            cv2.circle(frame, pt_position, 3, (255, 0, 0), -1)
    if cv2.waitKey(1) & 0xFF == ord('q'):
            break
        # 9 显示效果
    cv2.imshow("face detection landmark", frame)
capture.release()
cv2.destroyAllWindows()

你可能感兴趣的:(OpenCV课程总结,opencv,计算机视觉,人工智能)