您的位置:首页 > 其它

使用Dlib库进行人脸检测与对齐

2017-02-12 10:03 826 查看

简介

上一篇中,讲述了如何在windows上编译dlib的静态库dlib.lib。现在来使用dlib.lib进行人脸检测与对齐。例子中源码来自官方案例,进行稍微修改。

准备

1.编译好的静态库文件,dlib.lib
2.人脸特征点对齐模型:http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2  解压后大约97M左右。

程序

1.新建win32控制台程序,修改为 Release x64平台,为了与lib库保持一致
2.C/C++ -> 常规 -> 附加包含目录中,将dlib-18.17和libjpeg包含进去
    E:\dlib-18.17

    E:\dlib-18.17\dlib\external\libjpeg

3.C/C++ -> 预处理器 -> 预处理器定义,加入DLIB_PNG_SUPPORT 和DLIB_JPEG_SUPPORT
4.链接器 -> 输入 -> 附加依赖项,添加 dlib.lib
5.为了便于方便,直接将dlib.lib文件和对齐模型放入源码目录下,整体结构如下所示:



6.源码,代码解释见注释中。
#include <dlib/image_processing/frontal_face_detector.h>
#include <dlib/image_processing/render_face_detections.h>
#include <dlib/image_processing.h>
#include <dlib/gui_widgets.h>
#include <dlib/image_io.h>
#include <iostream>

using namespace dlib;
using namespace std;

// ----------------------------------------------------------------------------------------

int main(int argc, char** argv)
{
try
{
// 定义人脸检测器,使用它来获取一张图片中,每个人脸的边界位置
frontal_face_detector detector = get_frontal_face_detector();

//定义形状预测器,用来预测给定图片和脸边界框时候的标记点的位置。
//这里我们从shape_predictor_68_face_landmarks.dat文件加载模型
shape_predictor sp;
deserialize("shape_predictor_68_face_landmarks.dat") >> sp;

image_window win, win_faces;

// 循环所有图片,为演示效果,只用了一张图片
for (int i = 0; i < 1; ++i)
{
cout << "processing image " << "2.jpg"  << endl;
array2d<rgb_pixel> img;
load_image(img, "2.jpg");

// 放大图片以便检测到比较小的人脸.
pyramid_up(img);

//检测人脸,获得边界框
std::vector<rectangle> dets = detector(img);
cout << "Number of faces detected: " << dets.size() << endl;

// Now we will go ask the shape_predictor to tell us the pose of
// each face we detected.
//****调用shape_predictor类函数,返回每张人脸的姿势
std::vector<full_object_detection> shapes;//注意形状变量的类型,full_object_detection
for (unsigned long j = 0; j < dets.size(); ++j)
{
//预测姿势,注意输入是两个,一个是图片,另一个是从该图片检测到的边界框
full_object_detection shape = sp(img, dets[j]);
cout << "number of parts: " << shape.num_parts() << endl;

/*打印出全部68个点*/
/*for (int i = 0; i < 68; i++)
{
cout << "第 " << i+1 << " 个点的坐标: " << shape.part(i) << endl;
}*/

shapes.push_back(shape);
}

//显示结果
win.clear_overlay();
win.set_image(img);
win.add_overlay(dets, rgb_pixel(255, 0, 0));
win.add_overlay(render_face_detections(shapes));

//我们也能提取每张对齐剪裁后的人脸的副本,旋转和缩放到一个标准尺寸
dlib::array<array2d<rgb_pixel> > face_chips;
extract_image_chips(img, get_face_chip_details(shapes), face_chips);
win_faces.set_image(tile_images(face_chips));

cout << "Hit enter to process the next image..." << endl;
cin.get();
}
}
catch (exception& e)
{
cout << "\nexception thrown!" << endl;
cout << e.what() << endl;
}

return 0;
}

// ----------------------------------------------------------------------------------------

结果

原图



检测效果



裁切对齐效果



总结

检测精度可以,但速度方面不尽人意。优化:可以采用opencv的检测方法加上dlib的对齐方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  人脸识别 dlib