利用dlib库(Python)实现实时(摄像头)人脸检测以及特征点标定(landmark))

来源:互联网 发布:网络诈骗300元立案吗 编辑:程序博客网 时间:2024/05/23 05:08

此实现是在Windows环境下,Python2.7,以及利用opencv实现的。在用ubuntu 16.04实现时,出现了opencv不能打开摄像头的问题,希望有了解这个问题的可以沟通一下。

Dlib库的官方介绍,第一次见到dlib感觉像发现了新大陆!

Dlib is a modern C++ toolkit containing machine learning algorithms and tools for creating complex software in C++ to solve real world problems.

具体代码如下:

# coding=utf-8import cv2import dlib# landmark  datpredictor_path = "shape_predictor_68_face_landmarks.dat"# 初始化landmarkpredictor = dlib.shape_predictor(predictor_path)# 初始化dlib人脸检测器detector = dlib.get_frontal_face_detector()# 初始化显示窗口win = dlib.image_window()# opencv加载视频文件#cap = cv2.VideoCapture('/home/ljx/ImageDatabase/WaterBar.mp4')cap = cv2.VideoCapture(0)if cap.isOpened():    print "Unable to connect to camera !"

shape_predictor_68_face_landmarks.dat 是一个预处理后的数据文件,可用wget命令下载。
特征点的标定主要参考了论文

Kazemi V, Sullivan J. One millisecond face alignment with an ensemble of regression trees[C]//Computer Vision and Pattern Recognition (CVPR), 2014 IEEE Conference on. IEEE, 2014: 1867-1874

使用opencv读取摄像头时,一定要检查是否读到摄像头图像数据,一般,摄像头打开比较慢的话会读不到图像而报错。

接下来循环检测人脸以及特征点并显示在图像上,使用的都是dlib中的函数以及类。

while cap.isOpened():    ret, cv_img = cap.read()    if cv_img is None:        break    # RGB TO BGR    img = cv2.cvtColor(cv_img, cv2.COLOR_RGB2BGR)    dets = detector(img, 0)    print("Number of faces detected: {}".format(len(dets)))    shapes = []    for i, d in enumerate(dets):        print("Detection {}: Left: {} Top: {} Right: {} Bottom: {}".format(            i, d.left(), d.top(), d.right(), d.bottom()))        shape = predictor(img, d)        shapes.append(shape)# Draw the face landmarks on the screen.    win.clear_overlay()    win.set_image(img)    if len(shapes)!= 0 :        for i in range(len(shapes)):            win.add_overlay(shapes[i])    win.add_overlay(dets)cap.release()

opencv读取的图像一般为RGB格式的,而我们需要将其转换为BGR格式才能用dlib进行处理,dlib默认处理的图像格式是BGR格式。
shapes为列表,包含了所有的图像中出现的正脸的所有监测点。
对具体的Python API细节参考dilb官网。

参考:
1. 结合dlib与OpenCV的视频流人脸检测
2. Dlib提取人脸特征点(68点,opencv画图)

阅读全文
1 0
原创粉丝点击