简要:
FisherFace是基于LDA降维的人脸识别算法,由Ronald Fisher最早提出,故以此为名。它和PCA类似,都是将原始数据映射到低维空间,但和PCA最大的区别就是它考虑了降维后数据的类间方差和类内方差,使得降维后的数据类间方差最大,类内方差最小,而PCA是使整体数据降维后的方差最大,没有考虑降维后类间的变化。这又让我想到了二值化中的自适应阈值法,跟LDA的原理有点类似,依次遍历阈值,对于阈值分割后的黑白像素两类,使其两类间灰度值的方差最大,找到的这个阈值即为最适应阈值。
LDA原理:
#include<opencv2\opencv.hpp>
#include<opencv2\face.hpp>
using namespace cv;
using namespace face;
using namespace std;
char win_title[40] = {};
int main(int arc, char** argv) {
namedWindow("input",CV_WINDOW_AUTOSIZE);
//读入模型需要输入的数据,用来训练的图像vector<Mat>images和标签vector<int>labels
string filename = string("path.txt");
ifstream file(filename);
if (!file) { printf("could not load file"); }
vector<Mat>images;
vector<int>labels;
char separator = ';';
string line,path, classlabel;
while (getline(file,line)) {
stringstream lines(line);
getline(lines, path, separator);
getline(lines, classlabel);
//printf("%d\n", atoi(classlabel.c_str()));
images.push_back(imread(path, 0));
labels.push_back(atoi(classlabel.c_str()));//atoi(ASCLL to int)将字符串转换为整数型
}
int height = images[0].rows;
int width = images[0].cols;
printf("height:%d,width:%d\n", height, width);
//将最后一个样本作为测试样本
Mat testSample = images[images.size() - 1];
int testLabel = labels[labels.size() - 1];
//删除列表末尾的元素
images.pop_back();
labels.pop_back();
//加载,训练,预测
Ptr<BasicFaceRecognizer> model = FisherFaceRecognizer::create();
model->train(images, labels);
int predictedLabel = model->predict(testSample);
printf("actual label:%d,predict label :%d\n", testLabel, predictedLabel);
//计算特征值特征向量及平均值
Mat vals = model->getEigenValues();//89*1
printf("%d,%d\n", vals.rows, vals.cols);
Mat vecs = model->getEigenVectors();//10324*89
printf("%d,%d\n", vecs.rows, vecs.cols);
Mat mean = model->getMean();//1*10304
printf("%d,%d\n", mean.rows, mean.cols);
//显示平均脸
Mat meanFace = mean.reshape(1, height);//第一个参数为通道数,第二个参数为多少行
normalize(meanFace, meanFace, 0, 255, NORM_MINMAX, CV_8UC1);
imshow("Mean Face", meanFace);
//显示特征脸
for (int i = 0; i<min(10, vecs.cols); i++) {
Mat feature_vec = vecs.col(i).clone();
Mat feature_face= feature_vec.reshape(1, height);
normalize(feature_face, feature_face, 0, 255, NORM_MINMAX, CV_8UC1);
Mat colorface;
applyColorMap(feature_face, colorface, COLORMAP_JET);
sprintf_s(win_title, "fisherface%d", i);
imshow(win_title, colorface);
}
//重建人脸
for (int i = min(0, vecs.cols); i <min(16, vals.cols); i++) {
Mat vecs_space = vecs.col(i);
Mat projection = LDA::subspaceProject(vecs_space, mean, images[0].reshape(1, 1));
Mat reconstruction = LDA::subspaceReconstruct(vecs_space, mean, projection);
Mat result = reconstruction.reshape(1, height);
normalize(result, result, 0, 255, NORM_MINMAX, CV_8UC1);
//char wintitle[40] = {};
sprintf_s(win_title, "recon face %d", i);
imshow(win_title, result);
}
waitKey(0);
return 0;
}