##1. 源代码
先给出测试的结果,关键点并不是特别准,原因是训练样本数据量太少。
以下给出完整的人脸关键点检测器训练代码。详细的代码解读请看第二部分。
/* faceLandmarksTrain.cpp
function:借助dlib训练自己的人脸关键点检测器(参考dlib/examples/train_shape_predictor_ex)
date:2016/11/6
author:Elaine_Bao
*/
#include <dlib/image_processing.h>
#include <dlib/data_io.h>
#include <iostream>
using namespace dlib;
using namespace std;
// ----------------------------------------------------------------------------------------
//获取两眼间距离,输出D[i][j]表示objects[i][j]中人脸的两眼间距离
std::vector<std::vector<double> > get_interocular_distances(
const std::vector<std::vector<full_object_detection> >& objects
);
// ----------------------------------------------------------------------------------------
int main(int argc, char** argv)
{
try
{
//一、preprocessing
//1. 载入训练集,测试集
const std::string faces_directory = "faces";
dlib::array<array2d<unsigned char> > images_train, images_test;
std::vector<std::vector<full_object_detection> > faces_train, faces_test;
load_image_dataset(images_train, faces_train, faces_directory + "/training_with_face_landmarks.xml");
load_image_dataset(images_test, faces_test, faces_directory + "/testing_with_face_landmarks.xml");
// 二、training
//1. 定义trainer类型
shape_predictor_trainer trainer;
//设置训练参数
trainer.set_oversampling_amount(300);
trainer.set_nu(0.05);
trainer.set_tree_depth(2);
trainer.be_verbose();
// 2. 训练,生成人脸关键点检测器
shape_predictor sp = trainer.train(images_train, faces_train);
// 三、测试
cout << "mean training error: " <<
test_shape_predictor(sp, images_train, faces_train, get_interocular_distances(faces_train)) << endl;
cout << "mean testing error: " <<
test_shape_predictor(sp, images_test, faces_test, get_interocular_distances(faces_test)) << endl;
// 四、存储
serialize("sp.dat") << sp;
}
catch (exception& e)
{
cout << "\nexception thrown!" << endl;
cout << e.what() << endl;
}
}
// ----------------------------------------------------------------------------------------
double interocular_distance(
const full_object_detection& det
)
{
dlib::vector<double, 2> l, r;
double cnt = 0;
// Find the center of the left eye by averaging the poi