前面我们学习了基于特征脸的人脸识别,现在我们学习一下基于Fisher脸的人脸识别,Fisher人脸识别基于LDA(线性判别算法)算法,算法的详细介绍可以参考下面两篇教程内容:

http://docs.opencv.org/modules/contrib/doc/facerec/facerec_tutorial.html

LDA算法细节参考:

http://www.cnblogs.com/mikewolf2002/p/3435750.html

 

程序代码:

#include "opencv2/core/core.hpp"
#include "opencv2/contrib/contrib.hpp"
#include "opencv2/highgui/highgui.hpp" #include <iostream>
#include <fstream>
#include <sstream> using namespace cv;
using namespace std; static Mat norm_0_255(InputArray _src)
{
Mat src = _src.getMat();
Mat dst;
switch(src.channels())
{
case 1:
cv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC1);
break;
case 3:
cv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC3);
break;
default:
src.copyTo(dst);
break;
}
return dst;
} static void read_csv(const string& filename, vector<Mat>& images, vector<int>& labels, char separator = ';')
{
std::ifstream file(filename.c_str(), ifstream::in);
if (!file)
{
string error_message = "No valid input file was given, please check the given filename.";
CV_Error(CV_StsBadArg, error_message);
}
string line, path, classlabel;
while (getline(file, line))
{
stringstream liness(line);
getline(liness, path, separator);
getline(liness, classlabel);
if(!path.empty() && !classlabel.empty())
{
images.push_back(imread(path, 0));
labels.push_back(atoi(classlabel.c_str()));
}
}
} int main(int argc, const char *argv[])
{ string fn_csv = string("facerec_at_t.txt");
vector<Mat> images;
vector<int> labels; try
{
read_csv(fn_csv, images, labels);
} catch (cv::Exception& e)
{
cerr << "Error opening file \"" << fn_csv << "\". Reason: " << e.msg << endl;
exit(1);
} if(images.size() <= 1)
{
string error_message = "This demo needs at least 2 images to work. Please add more images to your data set!";
CV_Error(CV_StsError, error_message);
} int height = images[0].rows; Mat testSample = images[images.size() - 1];
int testLabel = labels[labels.size() - 1]; images.pop_back();
labels.pop_back(); Ptr<FaceRecognizer> model = createFisherFaceRecognizer();
model->train(images, labels);
int predictedLabel = model->predict(testSample); string result_message = format("Predicted class = %d / Actual class = %d.", predictedLabel, testLabel);
cout << result_message << endl; Mat eigenvalues = model->getMat("eigenvalues");
Mat W = model->getMat("eigenvectors");
Mat mean = model->getMat("mean");
imshow("mean", norm_0_255(mean.reshape(1, images[0].rows))); for (int i = 0; i < min(16, W.cols); i++)
{
string msg = format("Eigenvalue #%d = %.5f", i, eigenvalues.at<double>(i));
cout << msg << endl;
Mat ev = W.col(i).clone();
Mat grayscale = norm_0_255(ev.reshape(1, height));
Mat cgrayscale;
applyColorMap(grayscale, cgrayscale, COLORMAP_BONE);
imshow(format("fisherface_%d", i), cgrayscale); } for(int num_component = 0; num_component < min(16, W.cols); num_component++)
{ Mat ev = W.col(num_component);
Mat projection = subspaceProject(ev, mean, images[0].reshape(1,1));
Mat reconstruction = subspaceReconstruct(ev, mean, projection);
reconstruction = norm_0_255(reconstruction.reshape(1, images[0].rows));
imshow(format("fisherface_reconstruction_%d", num_component), reconstruction); } while(1)
waitKey(0);
return 0;
}

      从代码中我们可以看到,最大的区别就是创建人脸识别模式类时候,调用的函数不一样,其它代码和特征脸识别的代码一样,对于train和predict函数来说,调用方式完全一样,只是底层的具体算法细节不一样。

    Ptr<FaceRecognizer> model = createFisherFaceRecognizer();

  

     下面是Fisher人脸识别类的train函数,从中可以看到,函数会先调用PCA算法进行降维,之后再执行LDA算法,求得Fisher特征值和特征向量。注意投影矩阵是PCA算法的特征向量和LDA算法特征向量的乘积。

    // 先用PCA算法降维perform a PCA and keep (N-C) components

    PCA pca(data, Mat(), CV_PCA_DATA_AS_ROW, (N-C));

    // 把数据投影到 PCA空间,再对该数据执行LDA算法

    LDA lda(pca.project(data),labels, _num_components);

   // 保存总的均值向量

    _mean = pca.mean.reshape(1,1);

    _labels = labels.clone();

    lda.eigenvalues().convertTo(_eigenvalues, CV_64FC1);

   //计算投影矩阵=pca.eigenvectors * lda.eigenvectors.

    // Note: OpenCV stores the eigenvectors by row, so we need to transpose it!

    gemm(pca.eigenvectors, lda.eigenvectors(), 1.0, Mat(), 0.0, _eigenvectors, GEMM_1_T);

    //把原始矩阵投影到新的投影空间

    for(int sampleIdx = 0; sampleIdx < data.rows; sampleIdx++) {

        Mat p = subspaceProject(_eigenvectors, _mean, data.row(sampleIdx));

        _projections.push_back(p);

    }

 

    在程序中,我们仍然使用AT&T Facedatabase数据库的图片,原教程中推荐用Yale Facedatabase A,但是它的图像格式是gif,OpenCV不支持,只好放弃。

程序代码:FirstOpenCV34

OpenCV学习(38) 人脸识别(3)的更多相关文章

  1. OpenCV学习(37) 人脸识别(2)

          在前面一篇教程中,我们学习了OpenCV中基于特征脸的人脸识别的代码实现,我们通过代码 Ptr<FaceRecognizer> model = createEigenFaceR ...

  2. OpenCV学习(36) 人脸识别(1)

    本文主要参考OpenCV人脸识别教程:http://docs.opencv.org/modules/contrib/doc/facerec/facerec_tutorial.html 1.OpenCV ...

  3. OpenCV学习(40) 人脸识别(4)

    在人脸识别模式类中,还实现了一种基于LBP直方图的人脸识别方法.LBP图的原理参照:http://www.cnblogs.com/mikewolf2002/p/3438698.html       在 ...

  4. 【从零学习openCV】IOS7人脸识别实战

    前言 接着上篇<IOS7下的人脸检測>,我们顺藤摸瓜的学习怎样在IOS7下用openCV的进行人脸识别,实际上非常easy,因为人脸检測部分已经完毕,剩下的无非调用openCV的方法对採集 ...

  5. 基于深度学习的人脸识别系统(Caffe+OpenCV+Dlib)【一】如何配置caffe属性表

    前言 基于深度学习的人脸识别系统,一共用到了5个开源库:OpenCV(计算机视觉库).Caffe(深度学习库).Dlib(机器学习库).libfacedetection(人脸检测库).cudnn(gp ...

  6. 基于深度学习的人脸识别系统(Caffe+OpenCV+Dlib)【三】VGG网络进行特征提取

    前言 基于深度学习的人脸识别系统,一共用到了5个开源库:OpenCV(计算机视觉库).Caffe(深度学习库).Dlib(机器学习库).libfacedetection(人脸检测库).cudnn(gp ...

  7. 基于深度学习的人脸识别系统(Caffe+OpenCV+Dlib)【二】人脸预处理

    前言 基于深度学习的人脸识别系统,一共用到了5个开源库:OpenCV(计算机视觉库).Caffe(深度学习库).Dlib(机器学习库).libfacedetection(人脸检测库).cudnn(gp ...

  8. 基于深度学习的人脸识别系统系列(Caffe+OpenCV+Dlib)——【四】使用CUBLAS加速计算人脸向量的余弦距离

    前言 基于深度学习的人脸识别系统,一共用到了5个开源库:OpenCV(计算机视觉库).Caffe(深度学习库).Dlib(机器学习库).libfacedetection(人脸检测库).cudnn(gp ...

  9. 基于Opencv快速实现人脸识别(完整版)

    无耻收藏网页链接: 基于OpenCV快速实现人脸识别:https://blog.csdn.net/beyond9305/article/details/92844258 基于Opencv快速实现人脸识 ...

随机推荐

  1. hdoj2602 Bone Collector(DP,01背包)

    题目链接 http://acm.hdu.edu.cn/showproblem.php?pid=2602 题意 有n块骨头,每块骨头体积为volume,价值为value,还有一个容量为v的背包,现在将骨 ...

  2. JAVAEE——宜立方商城03:Nginx负载均衡高可用、Keepalived+Nginx实现主备

    1 nginx负载均衡高可用 1.1 什么是负载均衡高可用 nginx作为负载均衡器,所有请求都到了nginx,可见nginx处于非常重点的位置,如果nginx服务器宕机后端web服务将无法提供服务, ...

  3. Web服务评估工具Nikto

    Web服务评估工具Nikto   Nikto是一款Perl语言编写的Web服务评估工具.该工具主要侧重于发现网站的默认配置和错误配置.它通过扫描的方式,检测服务器.服务和网站的配置文件,从中找出默认配 ...

  4. interrupt_control

    中断的概念CPU在处理过程中,经常需要同外部设备进行交互,交互的方式由“轮询方式”“中断方式” 轮询方式: 方式:在同外设进行交互的过程中,CPU每隔一定的时间状态就去查询相关的状态位,所以在交互期间 ...

  5. IO编程

    1.文件读写 >>>f = open('/Users/michael/test.txt', 'r') >>> f.read() 'Hello, world!' &g ...

  6. Git 统计提交代码行数

    指定用户名 git log --author="your_name_here" --pretty=tformat: --numstat | awk '{ add += $1; su ...

  7. wpf企业应用之带选项框的TreeView

    wpf里面实现层次绑定主要使用HierarchicalDataTemplate,这里主要谈一谈带checkbox的treeview,具体效果见 wpf企业级开发中的几种常见业务场景. 先来看一下我的控 ...

  8. codevs 1073 家族 并查集

    家族 Time Limit: 1 Sec  Memory Limit: 256 MB 题目连接 http://www.codevs.cn/problem/1073/ Description 若某个家族 ...

  9. codevs 1052 地鼠游戏 优先队列

    1052 地鼠游戏 Time Limit: 1 Sec  Memory Limit: 256 MB 题目连接 http://www.codevs.cn/problem/1052/ Descriptio ...

  10. Codeforces 505A Mr. Kitayuta's Gift 暴力

    A. Mr. Kitayuta's Gift time limit per test 1 second memory limit per test 256 megabytes input standa ...