OpenCV实践之路——用dlib库进行人脸检测与人脸标记(Python)

来源:互联网 发布:c语言return返回值给谁 编辑:程序博客网 时间:2024/06/07 12:26

参考:http://blog.csdn.net/xingchenbingbuyu/article/details/51116354


主要步骤:

1.加载dlib自带的frontal_face_detector作为我们的人脸征检测器
2.加载官方提供的模型构建特征提取器
3.使用detector进行人脸检测
4.输出人脸个数
5.使用predictor进行人脸关键点识别
6.绘出关键点

其中预训练模型shape_predictor_68_face_landmarks.dat,点击这里找到并下载

Python程序

import cv2import dlibimport numpyimport sysPREDICTOR_PATH = "./data/shape_predictor_68_face_landmarks.dat"# 1.使用dlib自带的frontal_face_detector作为我们的人脸提取器detector = dlib.get_frontal_face_detector()# 2.使用官方提供的模型构建特征提取器predictor = dlib.shape_predictor(PREDICTOR_PATH)class NoFaces(Exception):    passim = cv2.imread("./image/nba.jpg")# 3.使用detector进行人脸检测 rects为返回的结果rects = detector(im, 1)# 4.输出人脸数,dets的元素个数即为脸的个数if len(rects) >= 1:    print("{} faces detected".format(len(rects)))if len(rects) == 0:    raise NoFacesfor i in range(len(rects)):    # 5.使用predictor进行人脸关键点识别    landmarks = numpy.matrix([[p.x, p.y] for p in predictor(im, rects[i]).parts()])    im = im.copy()    # 使用enumerate 函数遍历序列中的元素以及它们的下标    for idx, point in enumerate(landmarks):        pos = (point[0, 0], point[0, 1])        # cv2.putText(im,str(idx),pos,        # fontFace=cv2.FONT_HERSHEY_SCRIPT_SIMPLEX,        # fontScale=0.4,        #        # color=(0,0,255))        # 6.绘制特征点        cv2.circle(im, pos, 1, color=(0, 255, 0))cv2.namedWindow("im", 2)cv2.imshow("im", im)cv2.waitKey(0)cv2.destroyAllWindows()
阅读全文
0 0
原创粉丝点击