匹配臉

這個程序是由多張人臉生成特徵臉

#if 1

#include <opencv2\contrib\contrib.hpp>
#include <opencv2\core\core.hpp>
#include <opencv2\highgui\highgui.hpp>

#include <iostream>
#include <fstream>
#include <sstream>

using namespace std;
using namespace cv;

static  Mat norm_0_255(cv::InputArray _src)
{
 Mat src = _src.getMat();
 Mat dst;

 switch(src.channels())
 {
 case 1:
  cv::normalize(_src, dst, 0, 255, cv::NORM_MINMAX, CV_8UC1);
  break;
 case 3:
  cv::normalize(_src, dst, 0, 255, cv::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.";
  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, char *argv[])
{
 string output_folder;
 output_folder = string("D:\\ORL\\result");

 //讀取你的CSV文件路徑
 string fn_csv = string("D:\\ORL\\to\\at.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.";
  CV_Error(CV_StsError, error_message);
 }

 //得到第一張照片的高度,在下面對圖像變形到他們原始大小時需要
 int height = images[0].rows;

 //移除最後一張圖片,用於做測試
 Mat testSample = images[images.size() - 1];
 cv::imshow("testSample", testSample);
 int testLabel = labels[labels.size() - 1];

 images.pop_back();
 labels.pop_back();


 /*
 * 下面創建一個特徵臉模型用於人臉識別,
 * 通過CSV文件讀取的圖像和標籤訓練它。
 */

 cv::Ptr<cv::FaceRecognizer> model = cv::createEigenFaceRecognizer();
 model->train(images, labels);

 /*
 * 下面對測試圖像進行預測,predictedLabel 是預測標籤結果
 */
 int predictedLabel = model->predict(testSample);

 string result_message = format("Predicted class = %d / Actual class = %d.", predictedLabel, testLabel);
 cout<<result_message<<endl;


 //獲取特徵臉模型的特徵值的例子,使用了getMat方法
 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)));
 cv::imwrite(format("%s/mean.png", output_folder.c_str()), norm_0_255(mean.reshape(1, images[0].rows)));

 //實現並保存特徵臉
 for(int i=0; i <min(10, W.cols); i++)
 {
  string msg = format("Eigenvalue #%d = %.5f", i, eigenvalues.at<double>(i));
  cout<<msg<<endl;

  Mat ev = W.col(i).clone();

  //把他變成原始大小,爲了把數據顯示歸一化到0-255.
  Mat grayscale = norm_0_255(ev.reshape(1,height));

  //使用僞彩色來顯示結果
  Mat cgrayscale;
  cv::applyColorMap(grayscale, cgrayscale, COLORMAP_JET);

  imshow(format("eigenface_%d", i), cgrayscale);
  imwrite(format("%s/eigenface_%d.png", output_folder.c_str(), i), cgrayscale);
 }
 
 //在預測過程中,顯示並保存重建後的圖片
 for(int num_components = 10; num_components < 390; num_components += 15)
 {
  //從模型中的特徵向量截取一部分
  Mat evs = Mat(W, Range::all(), Range(0, num_components));
  //投影
  Mat projection = cv::subspaceProject(evs, mean, images[0].reshape(1,1));
  //重構
  Mat reconstruction = cv::subspaceReconstruct(evs, mean, projection);

  reconstruction = norm_0_255(reconstruction.reshape(1, images[0].rows));

  imshow(format("eigenface_reconstruction_%d", num_components),reconstruction);
  imwrite(format("%s/eigenface_reconstruction_%d.png", output_folder.c_str(),num_components), reconstruction);

 }
 
 cv::waitKey(0);
 return 0;
}

#endif

發佈了4 篇原創文章 · 獲贊 0 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章