facerec_fisherfaces.cpp 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  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 Fisherfaces model for
  106. // face recognition and train it with the images and
  107. // labels read from the given CSV file.
  108. // If you just want to keep 10 Fisherfaces, then call
  109. // the factory method like this:
  110. //
  111. // FisherFaceRecognizer::create(10);
  112. //
  113. // However it is not useful to discard Fisherfaces! Please
  114. // always try to use _all_ available Fisherfaces for
  115. // classification.
  116. //
  117. // If you want to create a FaceRecognizer with a
  118. // confidence threshold (e.g. 123.0) and use _all_
  119. // Fisherfaces, then call it with:
  120. //
  121. // FisherFaceRecognizer::create(0, 123.0);
  122. //
  123. Ptr<FisherFaceRecognizer> model = FisherFaceRecognizer::create();
  124. model->train(images, labels);
  125. // The following line predicts the label of a given
  126. // test image:
  127. int predictedLabel = model->predict(testSample);
  128. //
  129. // To get the confidence of a prediction call the model with:
  130. //
  131. // int predictedLabel = -1;
  132. // double confidence = 0.0;
  133. // model->predict(testSample, predictedLabel, confidence);
  134. //
  135. string result_message = format("Predicted class = %d / Actual class = %d.", predictedLabel, testLabel);
  136. cout << result_message << endl;
  137. // Here is how to get the eigenvalues of this Eigenfaces model:
  138. Mat eigenvalues = model->getEigenValues();
  139. // And we can do the same to display the Eigenvectors (read Eigenfaces):
  140. Mat W = model->getEigenVectors();
  141. // Get the sample mean from the training data
  142. Mat mean = model->getMean();
  143. // Display or save:
  144. if(argc == 2) {
  145. imshow("mean", norm_0_255(mean.reshape(1, images[0].rows)));
  146. } else {
  147. imwrite(format("%s/mean.png", output_folder.c_str()), norm_0_255(mean.reshape(1, images[0].rows)));
  148. }
  149. // Display or save the first, at most 16 Fisherfaces:
  150. for (int i = 0; i < min(16, W.cols); i++) {
  151. string msg = format("Eigenvalue #%d = %.5f", i, eigenvalues.at<double>(i));
  152. cout << msg << endl;
  153. // get eigenvector #i
  154. Mat ev = W.col(i).clone();
  155. // Reshape to original size & normalize to [0...255] for imshow.
  156. Mat grayscale = norm_0_255(ev.reshape(1, height));
  157. // Show the image & apply a Bone colormap for better sensing.
  158. Mat cgrayscale;
  159. applyColorMap(grayscale, cgrayscale, COLORMAP_BONE);
  160. // Display or save:
  161. if(argc == 2) {
  162. imshow(format("fisherface_%d", i), cgrayscale);
  163. } else {
  164. imwrite(format("%s/fisherface_%d.png", output_folder.c_str(), i), norm_0_255(cgrayscale));
  165. }
  166. }
  167. // Display or save the image reconstruction at some predefined steps:
  168. for(int num_component = 0; num_component < min(16, W.cols); num_component++) {
  169. // Slice the Fisherface from the model:
  170. Mat ev = W.col(num_component);
  171. Mat projection = LDA::subspaceProject(ev, mean, images[0].reshape(1,1));
  172. Mat reconstruction = LDA::subspaceReconstruct(ev, mean, projection);
  173. // Normalize the result:
  174. reconstruction = norm_0_255(reconstruction.reshape(1, images[0].rows));
  175. // Display or save:
  176. if(argc == 2) {
  177. imshow(format("fisherface_reconstruction_%d", num_component), reconstruction);
  178. } else {
  179. imwrite(format("%s/fisherface_reconstruction_%d.png", output_folder.c_str(), num_component), reconstruction);
  180. }
  181. }
  182. // Display if we are not writing to an output folder:
  183. if(argc == 2) {
  184. waitKey(0);
  185. }
  186. return 0;
  187. }