facerec_eigenfaces.cpp 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. /*
  2. * Copyright (c) 2011. Philipp Wagner <bytefish[at]gmx[dot]de>.
  3. * Released to public domain under terms of the BSD Simplified license.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the organization nor the names of its contributors
  13. * may be used to endorse or promote products derived from this software
  14. * without specific prior written permission.
  15. *
  16. * See <http://www.opensource.org/licenses/bsd-license>
  17. */
  18. #include "opencv2/core.hpp"
  19. #include "opencv2/face.hpp"
  20. #include "opencv2/highgui.hpp"
  21. #include "opencv2/imgproc.hpp"
  22. #include <iostream>
  23. #include <fstream>
  24. #include <sstream>
  25. using namespace cv;
  26. using namespace cv::face;
  27. using namespace std;
  28. static Mat norm_0_255(InputArray _src) {
  29. Mat src = _src.getMat();
  30. // Create and return normalized image:
  31. Mat dst;
  32. switch(src.channels()) {
  33. case 1:
  34. cv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC1);
  35. break;
  36. case 3:
  37. cv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC3);
  38. break;
  39. default:
  40. src.copyTo(dst);
  41. break;
  42. }
  43. return dst;
  44. }
  45. static void read_csv(const string& filename, vector<Mat>& images, vector<int>& labels, char separator = ';') {
  46. std::ifstream file(filename.c_str(), ifstream::in);
  47. if (!file) {
  48. string error_message = "No valid input file was given, please check the given filename.";
  49. CV_Error(Error::StsBadArg, error_message);
  50. }
  51. string line, path, classlabel;
  52. while (getline(file, line)) {
  53. stringstream liness(line);
  54. getline(liness, path, separator);
  55. getline(liness, classlabel);
  56. if(!path.empty() && !classlabel.empty()) {
  57. images.push_back(imread(path, 0));
  58. labels.push_back(atoi(classlabel.c_str()));
  59. }
  60. }
  61. }
  62. int main(int argc, const char *argv[]) {
  63. // Check for valid command line arguments, print usage
  64. // if no arguments were given.
  65. if (argc < 2) {
  66. cout << "usage: " << argv[0] << " <csv.ext> <output_folder> " << endl;
  67. exit(1);
  68. }
  69. string output_folder = ".";
  70. if (argc == 3) {
  71. output_folder = string(argv[2]);
  72. }
  73. // Get the path to your CSV.
  74. string fn_csv = string(argv[1]);
  75. // These vectors hold the images and corresponding labels.
  76. vector<Mat> images;
  77. vector<int> labels;
  78. // Read in the data. This can fail if no valid
  79. // input filename is given.
  80. try {
  81. read_csv(fn_csv, images, labels);
  82. } catch (const cv::Exception& e) {
  83. cerr << "Error opening file \"" << fn_csv << "\". Reason: " << e.msg << endl;
  84. // nothing more we can do
  85. exit(1);
  86. }
  87. // Quit if there are not enough images for this demo.
  88. if(images.size() <= 1) {
  89. string error_message = "This demo needs at least 2 images to work. Please add more images to your data set!";
  90. CV_Error(Error::StsError, error_message);
  91. }
  92. // Get the height from the first image. We'll need this
  93. // later in code to reshape the images to their original
  94. // size:
  95. int height = images[0].rows;
  96. // The following lines simply get the last images from
  97. // your dataset and remove it from the vector. This is
  98. // done, so that the training data (which we learn the
  99. // cv::BasicFaceRecognizer on) and the test data we test
  100. // the model with, do not overlap.
  101. Mat testSample = images[images.size() - 1];
  102. int testLabel = labels[labels.size() - 1];
  103. images.pop_back();
  104. labels.pop_back();
  105. // The following lines create an Eigenfaces model for
  106. // face recognition and train it with the images and
  107. // labels read from the given CSV file.
  108. // This here is a full PCA, if you just want to keep
  109. // 10 principal components (read Eigenfaces), then call
  110. // the factory method like this:
  111. //
  112. // EigenFaceRecognizer::create(10);
  113. //
  114. // If you want to create a FaceRecognizer with a
  115. // confidence threshold (e.g. 123.0), call it with:
  116. //
  117. // EigenFaceRecognizer::create(10, 123.0);
  118. //
  119. // If you want to use _all_ Eigenfaces and have a threshold,
  120. // then call the method like this:
  121. //
  122. // EigenFaceRecognizer::create(0, 123.0);
  123. //
  124. Ptr<EigenFaceRecognizer> model = EigenFaceRecognizer::create();
  125. model->train(images, labels);
  126. // The following line predicts the label of a given
  127. // test image:
  128. int predictedLabel = model->predict(testSample);
  129. //
  130. // To get the confidence of a prediction call the model with:
  131. //
  132. // int predictedLabel = -1;
  133. // double confidence = 0.0;
  134. // model->predict(testSample, predictedLabel, confidence);
  135. //
  136. string result_message = format("Predicted class = %d / Actual class = %d.", predictedLabel, testLabel);
  137. cout << result_message << endl;
  138. // Here is how to get the eigenvalues of this Eigenfaces model:
  139. Mat eigenvalues = model->getEigenValues();
  140. // And we can do the same to display the Eigenvectors (read Eigenfaces):
  141. Mat W = model->getEigenVectors();
  142. // Get the sample mean from the training data
  143. Mat mean = model->getMean();
  144. // Display or save:
  145. if(argc == 2) {
  146. imshow("mean", norm_0_255(mean.reshape(1, images[0].rows)));
  147. } else {
  148. imwrite(format("%s/mean.png", output_folder.c_str()), norm_0_255(mean.reshape(1, images[0].rows)));
  149. }
  150. // Display or save the Eigenfaces:
  151. for (int i = 0; i < min(10, W.cols); i++) {
  152. string msg = format("Eigenvalue #%d = %.5f", i, eigenvalues.at<double>(i));
  153. cout << msg << endl;
  154. // get eigenvector #i
  155. Mat ev = W.col(i).clone();
  156. // Reshape to original size & normalize to [0...255] for imshow.
  157. Mat grayscale = norm_0_255(ev.reshape(1, height));
  158. // Show the image & apply a Jet colormap for better sensing.
  159. Mat cgrayscale;
  160. applyColorMap(grayscale, cgrayscale, COLORMAP_JET);
  161. // Display or save:
  162. if(argc == 2) {
  163. imshow(format("eigenface_%d", i), cgrayscale);
  164. } else {
  165. imwrite(format("%s/eigenface_%d.png", output_folder.c_str(), i), norm_0_255(cgrayscale));
  166. }
  167. }
  168. // Display or save the image reconstruction at some predefined steps:
  169. for(int num_components = min(W.cols, 10); num_components < min(W.cols, 300); num_components+=15) {
  170. // slice the eigenvectors from the model
  171. Mat evs = Mat(W, Range::all(), Range(0, num_components));
  172. Mat projection = LDA::subspaceProject(evs, mean, images[0].reshape(1,1));
  173. Mat reconstruction = LDA::subspaceReconstruct(evs, mean, projection);
  174. // Normalize the result:
  175. reconstruction = norm_0_255(reconstruction.reshape(1, images[0].rows));
  176. // Display or save:
  177. if(argc == 2) {
  178. imshow(format("eigenface_reconstruction_%d", num_components), reconstruction);
  179. } else {
  180. imwrite(format("%s/eigenface_reconstruction_%d.png", output_folder.c_str(), num_components), reconstruction);
  181. }
  182. }
  183. // Display if we are not writing to an output folder:
  184. if(argc == 2) {
  185. waitKey(0);
  186. }
  187. return 0;
  188. }