facerec_save_load.cpp 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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::FaceRecognizer 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. // cv::face::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. // cv::face::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. // cv::face::EigenFaceRecognizer::create(0, 123.0);
  123. //
  124. Ptr<EigenFaceRecognizer> model0 = EigenFaceRecognizer::create();
  125. model0->train(images, labels);
  126. // save the model to eigenfaces_at.yaml
  127. model0->save("eigenfaces_at.yml");
  128. //
  129. //
  130. // Now create a new Eigenfaces Recognizer
  131. //
  132. Ptr<EigenFaceRecognizer> model1 = Algorithm::load<EigenFaceRecognizer>("eigenfaces_at.yml");
  133. // The following line predicts the label of a given
  134. // test image:
  135. int predictedLabel = model1->predict(testSample);
  136. //
  137. // To get the confidence of a prediction call the model with:
  138. //
  139. // int predictedLabel = -1;
  140. // double confidence = 0.0;
  141. // model->predict(testSample, predictedLabel, confidence);
  142. //
  143. string result_message = format("Predicted class = %d / Actual class = %d.", predictedLabel, testLabel);
  144. cout << result_message << endl;
  145. // Here is how to get the eigenvalues of this Eigenfaces model:
  146. Mat eigenvalues = model1->getEigenValues();
  147. // And we can do the same to display the Eigenvectors (read Eigenfaces):
  148. Mat W = model1->getEigenVectors();
  149. // Get the sample mean from the training data
  150. Mat mean = model1->getMean();
  151. // Display or save:
  152. if(argc == 2) {
  153. imshow("mean", norm_0_255(mean.reshape(1, images[0].rows)));
  154. } else {
  155. imwrite(format("%s/mean.png", output_folder.c_str()), norm_0_255(mean.reshape(1, images[0].rows)));
  156. }
  157. // Display or save the Eigenfaces:
  158. for (int i = 0; i < min(10, W.cols); i++) {
  159. string msg = format("Eigenvalue #%d = %.5f", i, eigenvalues.at<double>(i));
  160. cout << msg << endl;
  161. // get eigenvector #i
  162. Mat ev = W.col(i).clone();
  163. // Reshape to original size & normalize to [0...255] for imshow.
  164. Mat grayscale = norm_0_255(ev.reshape(1, height));
  165. // Show the image & apply a Jet colormap for better sensing.
  166. Mat cgrayscale;
  167. applyColorMap(grayscale, cgrayscale, COLORMAP_JET);
  168. // Display or save:
  169. if(argc == 2) {
  170. imshow(format("eigenface_%d", i), cgrayscale);
  171. } else {
  172. imwrite(format("%s/eigenface_%d.png", output_folder.c_str(), i), norm_0_255(cgrayscale));
  173. }
  174. }
  175. // Display or save the image reconstruction at some predefined steps:
  176. for(int num_components = 10; num_components < 300; num_components+=15) {
  177. // slice the eigenvectors from the model
  178. Mat evs = Mat(W, Range::all(), Range(0, num_components));
  179. Mat projection = LDA::subspaceProject(evs, mean, images[0].reshape(1,1));
  180. Mat reconstruction = LDA::subspaceReconstruct(evs, mean, projection);
  181. // Normalize the result:
  182. reconstruction = norm_0_255(reconstruction.reshape(1, images[0].rows));
  183. // Display or save:
  184. if(argc == 2) {
  185. imshow(format("eigenface_reconstruction_%d", num_components), reconstruction);
  186. } else {
  187. imwrite(format("%s/eigenface_reconstruction_%d.png", output_folder.c_str(), num_components), reconstruction);
  188. }
  189. }
  190. // Display if we are not writing to an output folder:
  191. if(argc == 2) {
  192. waitKey(0);
  193. }
  194. return 0;
  195. }