手机版
你好,游客 登录 注册
背景:
阅读新闻

OpenCV人脸识别LBPH算法源码分析

[日期:2016-07-13] 来源:Linux社区  作者:zhaoweiwei [字体:大 中 小]

4 LBP人脸识别示例

最后给出LBP人脸识别的示例代码,代码中使用的人脸库是AT&T人脸库(又称ORL人脸数据库),库中有40个人,每人10张照片,共400张人脸照片。示例代码如下:

  1 #include "opencv2/core/core.hpp"
  2 #include "opencv2/highgui/highgui.hpp"
  3 #include "opencv2/contrib/contrib.hpp"
  4 
  5 #define CV_VERSION_ID       CVAUX_STR(CV_MAJOR_VERSION) CVAUX_STR(CV_MINOR_VERSION) CVAUX_STR(CV_SUBMINOR_VERSION)
  6 
  7 #ifdef _DEBUG
  8 #define cvLIB(name) "opencv_" name CV_VERSION_ID "d"
  9 #else
 10 #define cvLIB(name) "opencv_" name CV_VERSION_ID
 11 #endif
 12 
 13 #pragma comment( lib, cvLIB("core") )
 14 #pragma comment( lib, cvLIB("imgproc") )
 15 #pragma comment( lib, cvLIB("highgui") )
 16 #pragma comment( lib, cvLIB("flann") )
 17 #pragma comment( lib, cvLIB("features2d") )
 18 #pragma comment( lib, cvLIB("calib3d") )
 19 #pragma comment( lib, cvLIB("gpu") )
 20 #pragma comment( lib, cvLIB("legacy") )
 21 #pragma comment( lib, cvLIB("ml") )
 22 #pragma comment( lib, cvLIB("objdetect") )
 23 #pragma comment( lib, cvLIB("ts") )
 24 #pragma comment( lib, cvLIB("video") )
 25 #pragma comment( lib, cvLIB("contrib") )
 26 #pragma comment( lib, cvLIB("nonfree") )
 27 
 28 #include <iostream>
 29 #include <fstream>
 30 #include <sstream>
 31 
 32 using namespace cv;
 33 using namespace std;
 34 
 35 static void read_csv(const string& filename, vector<Mat>& images, vector<int>& labels, char separator =';') {
 36     std::ifstream file(filename.c_str(), ifstream::in);
 37     if (!file) {
 38         string error_message ="No valid input file was given, please check the given filename.";
 39         CV_Error(CV_StsBadArg, error_message);
 40     }
 41     string line, path, classlabel;
 42     while (getline(file, line)) {
 43         stringstream liness(line);
 44         getline(liness, path, separator);
 45         getline(liness, classlabel);
 46         if(!path.empty()&&!classlabel.empty()) {
 47             images.push_back(imread(path, 0));
 48             labels.push_back(atoi(classlabel.c_str()));
 49         }
 50     }
 51 }
 52 
 53 int main(int argc, const char *argv[]) {
 54     if (argc !=2) {
 55         cout <<"usage: "<< argv[0]<<" <csv.ext>"<< endl;
 56         exit(1);
 57     }
 58     string fn_csv = string(argv[1]);
 59     vector<Mat> images;
 60     vector<int> labels;
 61     try {
 62         read_csv(fn_csv, images, labels);
 63     } catch (cv::Exception& e) {
 64         cerr <<"Error opening file "<< fn_csv <<". Reason: "<< e.msg << endl;
 65         // nothing more we can do
 66         exit(1);
 67     }
 68     if(images.size()<=1) {
 69         string error_message ="This demo needs at least 2 images to work. Please add more images to your data set!";
 70         CV_Error(CV_StsError, error_message);
 71     }
 72     int height = images[0].rows;
 73     Mat testSample = images[images.size() -1];
 74     int testLabel = labels[labels.size() -1];
 75     images.pop_back();
 76     labels.pop_back();
 77     // TLBPHFaceRecognizer 使用了扩展的LBP
 78     // 在其他的算子中他可能很容易被扩展
 79     // 下面是默认参数
 80     //      radius = 1
 81     //      neighbors = 8
 82     //      grid_x = 8
 83     //      grid_y = 8
 84     //
 85     // 如果你要创建 LBPH FaceRecognizer 半径是2,16个邻域
 86     //      cv::createLBPHFaceRecognizer(2, 16);
 87     //
 88     // 如果你需要一个阈值,并且使用默认参数:
 89     //      cv::createLBPHFaceRecognizer(1,8,8,8,123.0)
 90     //
 91     Ptr<FaceRecognizer> model = createLBPHFaceRecognizer();
 92     model->train(images, labels);
 93     int predictedLabel = model->predict(testSample);
 94     //      int predictedLabel = -1;
 95     //      double confidence = 0.0;
 96     //      model->predict(testSample, predictedLabel, confidence);
 97     //
 98     string result_message = format("Predicted class = %d / Actual class = %d.", predictedLabel, testLabel);
 99     cout << result_message << endl;
100     // 有时你需要设置或者获取内部数据模型,
101     // 他不能被暴露在 cv::FaceRecognizer类中.
102     //
103     // 首先我们对FaceRecognizer的阈值设置到0.0,而不是重写训练模型
104     // 当你重新估计模型时很重要 
105     //
106     model->set("threshold",0.0);
107     predictedLabel = model->predict(testSample);
108     cout <<"Predicted class = "<< predictedLabel << endl;
109     // 由于确保高效率,LBP图没有被存储在模型里面。
110     cout <<"Model Information:"<< endl;
111     string model_info = format("tLBPH(radius=%i, neighbors=%i, grid_x=%i, grid_y=%i, threshold=%.2f)",
112         model->getInt("radius"),
113         model->getInt("neighbors"),
114         model->getInt("grid_x"),
115         model->getInt("grid_y"),
116         model->getDouble("threshold"));
117     cout << model_info << endl;
118     // 我们可以获取样本的直方图:
119     vector<Mat> histograms = model->getMatVector("histograms");
120     // 我需要现实它吗? 或许它的长度才是我们感兴趣的:
121     cout <<"Size of the histograms: "<< histograms[0].total()<< endl;
122     return 0;
123 }

程序中用一个CSV文件指明人脸数据库文件及标签,即CSV文件中每一行包含一个文件名路径之后是其标签值,中间以分号为分隔符,可以手工创建该CSV文件,当然也可以用一个简单的Python程序来帮你实现该文件,我的python脚本程序如下:

 1 import sys
 2 import os
 3 
 4 def read_images(path, sz=None):
 5     c = 0
 6     X,y = [], []
 7     fp = open(os.path.join(path,"test.txt"),'w')
 8     for dirname, dirnames, filenames in os.walk(path):
 9         #print dirname
10         #print dirnames
11         #print filenames
12         for subdirname in dirnames:
13             subject_path = os.path.join(dirname, subdirname)
14             for filename in os.listdir(subject_path):
15                 str = "%s;%d\n"%(os.path.join(subject_path, filename), c)
16                 print str
17                 fp.write(str)
18             c += 1
19     fp.close()
20 
21 if __name__ == '__main__':
22     read_images("F:\\mywork\\facerec_demo\\att_faces")

程序中22行需改成你自己的人脸库路径。

示例程序的运行结果如下所示:

结果第二行反应了当设置阈值为0.0时(model->set("threshold",0.0)),则不会有识别结果产生。

本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-07/133127.htm

linux
相关资讯       OpenCV人脸识别  LBPH算法源码