OpenCV学习(38) 人脸识别(3)
前面我们学习了基于特征脸的人脸识别,现在我们学习一下基于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)的更多相关文章
- OpenCV学习(37) 人脸识别(2)
在前面一篇教程中,我们学习了OpenCV中基于特征脸的人脸识别的代码实现,我们通过代码 Ptr<FaceRecognizer> model = createEigenFaceR ...
- OpenCV学习(36) 人脸识别(1)
本文主要参考OpenCV人脸识别教程:http://docs.opencv.org/modules/contrib/doc/facerec/facerec_tutorial.html 1.OpenCV ...
- OpenCV学习(40) 人脸识别(4)
在人脸识别模式类中,还实现了一种基于LBP直方图的人脸识别方法.LBP图的原理参照:http://www.cnblogs.com/mikewolf2002/p/3438698.html 在 ...
- 【从零学习openCV】IOS7人脸识别实战
前言 接着上篇<IOS7下的人脸检測>,我们顺藤摸瓜的学习怎样在IOS7下用openCV的进行人脸识别,实际上非常easy,因为人脸检測部分已经完毕,剩下的无非调用openCV的方法对採集 ...
- 基于深度学习的人脸识别系统(Caffe+OpenCV+Dlib)【一】如何配置caffe属性表
前言 基于深度学习的人脸识别系统,一共用到了5个开源库:OpenCV(计算机视觉库).Caffe(深度学习库).Dlib(机器学习库).libfacedetection(人脸检测库).cudnn(gp ...
- 基于深度学习的人脸识别系统(Caffe+OpenCV+Dlib)【三】VGG网络进行特征提取
前言 基于深度学习的人脸识别系统,一共用到了5个开源库:OpenCV(计算机视觉库).Caffe(深度学习库).Dlib(机器学习库).libfacedetection(人脸检测库).cudnn(gp ...
- 基于深度学习的人脸识别系统(Caffe+OpenCV+Dlib)【二】人脸预处理
前言 基于深度学习的人脸识别系统,一共用到了5个开源库:OpenCV(计算机视觉库).Caffe(深度学习库).Dlib(机器学习库).libfacedetection(人脸检测库).cudnn(gp ...
- 基于深度学习的人脸识别系统系列(Caffe+OpenCV+Dlib)——【四】使用CUBLAS加速计算人脸向量的余弦距离
前言 基于深度学习的人脸识别系统,一共用到了5个开源库:OpenCV(计算机视觉库).Caffe(深度学习库).Dlib(机器学习库).libfacedetection(人脸检测库).cudnn(gp ...
- 基于Opencv快速实现人脸识别(完整版)
无耻收藏网页链接: 基于OpenCV快速实现人脸识别:https://blog.csdn.net/beyond9305/article/details/92844258 基于Opencv快速实现人脸识 ...
随机推荐
- poj1703 Find them, Catch them(带权并查集)
题目链接 http://poj.org/problem?id=1703 题意 有两个帮派:龙帮和蛇帮,两个帮派共有n个人(编号1~n),输入m组数据,每组数据为D [a][b]或A [a][b],D[ ...
- C#.net实现图片上传功能
C#.NET前台:<asp:Image ID="imgFood" runat="server" /> <asp:FileUpload ID=& ...
- Effective C++ —— 模板与泛型编程(七)
C++ templates的最初发展动机很直接:让我们得以建立“类型安全”的容器如vector,list和map.然而当愈多人用上templates,他们发现templates有能力完成愈多可能的变化 ...
- Android DecorView浅析
摘要 一.DecorView为整个Window界面的最顶层View. 二.DecorView只有一个子元素为LinearLayout.代表整个Window界面,包含通知栏,标题栏,内容显示栏三块区域. ...
- [SQL]197. Rising Temperature
Given a Weather table, write a SQL query to find all dates' Ids with higher temperature compared to ...
- [ 转载 ]学习笔记-深入剖析Java中的装箱和拆箱
深入剖析Java中的装箱和拆箱 自动装箱和拆箱问题是Java中一个老生常谈的问题了,今天我们就来一些看一下装箱和拆箱中的若干问题.本文先讲述装箱和拆箱最基本的东西,再来看一下面试笔试中经常遇到的与装箱 ...
- 使用IIS实现反向代理
IIS的反向代理是通过ARR模块来完成的,ARR模块需要另外安装,而且只能通过Web PlatForm Installer安装.关于安装来源与步骤,帖子已有很多,不做描述.启用“Application ...
- BZOJ 3572: [Hnoi2014]世界树 虚树 树形dp
https://www.lydsy.com/JudgeOnline/problem.php?id=3572 http://hzwer.com/6804.html 写的时候参考了hzwer的代码,不会写 ...
- disable_functions php-fpm root
php.ini disable_functions 禁用某些函数 需要时注意打开 php-fpm 对应conf user group为root时 ERROR: [pool www] please sp ...
- [ZHOJ1954]lyd的旅行
题目大意: 一个做直线运动的物体已知初速度v0和v1,每分钟速度最大改变d,总共运动了t分钟,问至多运动了多少距离.(每个单位时间只能以同一种速度行驶) 思路: 肯定是先尽可能加速再减速,我们可以想一 ...