树莓派3B+指南(七)人脸特征点标定(python3+Dlib+OpenCV)

人脸特征点标定(python3+Dlib+OpenCV)

这个很有趣,也便于对后面的东西做理解,玩一玩还是很有意思的。这篇文章同样是从网上借鉴来的,原文参考:https://blog.csdn.net/hongbin_xu/article/details/78348086

Dlib提供了很好的训练模型,可以识别脸部68个特征点,模型需要先下载。
下载地址:https://download.csdn.net/download/weixin_44086593/10961208。

import dlib
import cv2
import os

current_path = os.getcwd()  # 获取当前路径
predictor_path = current_path + "/Dlib_Models/shape_predictor_68_face_landmarks.dat"  # shape_predictor_68_face_landmarks.dat是进行人脸标定的模型,它是基于HOG特征的,这里是他所在的路径
face_directory_path = current_path + "/PIC/"    # 存放人脸图片的路径

detector = dlib.get_frontal_face_detector() #获取人脸分类器
predictor = dlib.shape_predictor(predictor_path)    # 获取人脸检测器

# 图片路径,目录+文件名
face_path = face_directory_path + "taonaimu.jpg"

# opencv 读取图片,并显示
img = cv2.imread(face_path, cv2.IMREAD_COLOR)
dets = detector(img, 1) #使用detector进行人脸检测 dets为返回的结果
print("Number of faces detected: {}".format(len(dets)))   # 打印识别到的人脸个数
# enumerate是一个Python的内置方法,用于遍历索引
# index是序号;face是dets中取出的dlib.rectangle类的对象,包含了人脸的区域等信息
# left()、top()、right()、bottom()都是dlib.rectangle类的方法,对应矩形四条边的位置
for index, face in enumerate(dets):
    print('face {}; left {}; top {}; right {}; bottom {}'.format(index, face.left(), face.top(), face.right(), face.bottom()))
    shape = predictor(img, face)  # 寻找人脸的68个标定点
    
    # 遍历所有点,打印出其坐标,并用蓝色的圈表示出来
    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)

    # 在新窗口中显示
    cv2.namedWindow(face_path, cv2.WINDOW_AUTOSIZE)
    cv2.imshow(face_path, img)

# 等待按键,随后退出,销毁窗口
k = cv2.waitKey(0)
cv2.destroyAllWindows()

效果如下:

在这里插入图片描述
在这里插入图片描述
看来还还是不错的。

至此就结束了,希望可以帮助到大家。

猜你喜欢

转载自blog.csdn.net/weixin_44086593/article/details/87520588