facerec_demo.cpp 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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/highgui.hpp"
  20. #include "opencv2/imgproc.hpp"
  21. #include "opencv2/face.hpp"
  22. #include "opencv2/core/utility.hpp"
  23. #include <iostream>
  24. #include <fstream>
  25. #include <sstream>
  26. #include <map>
  27. using namespace cv;
  28. using namespace cv::face;
  29. using namespace std;
  30. static void read_csv(const string& filename, vector<Mat>& images, vector<int>& labels, std::map<int, string>& labelsInfo, char separator = ';') {
  31. ifstream csv(filename.c_str());
  32. if (!csv) CV_Error(Error::StsBadArg, "No valid input file was given, please check the given filename.");
  33. string line, path, classlabel, info;
  34. while (getline(csv, line)) {
  35. stringstream liness(line);
  36. path.clear(); classlabel.clear(); info.clear();
  37. getline(liness, path, separator);
  38. getline(liness, classlabel, separator);
  39. getline(liness, info, separator);
  40. if(!path.empty() && !classlabel.empty()) {
  41. cout << "Processing " << path << endl;
  42. int label = atoi(classlabel.c_str());
  43. if(!info.empty())
  44. labelsInfo.insert(std::make_pair(label, info));
  45. // 'path' can be file, dir or wildcard path
  46. String root(path.c_str());
  47. vector<String> files;
  48. glob(root, files, true);
  49. for(vector<String>::const_iterator f = files.begin(); f != files.end(); ++f) {
  50. cout << "\t" << *f << endl;
  51. Mat img = imread(*f, IMREAD_GRAYSCALE);
  52. static int w=-1, h=-1;
  53. static bool showSmallSizeWarning = true;
  54. if(w>0 && h>0 && (w!=img.cols || h!=img.rows)) cout << "\t* Warning: images should be of the same size!" << endl;
  55. if(showSmallSizeWarning && (img.cols<50 || img.rows<50)) {
  56. cout << "* Warning: for better results images should be not smaller than 50x50!" << endl;
  57. showSmallSizeWarning = false;
  58. }
  59. images.push_back(img);
  60. labels.push_back(label);
  61. }
  62. }
  63. }
  64. }
  65. int main(int argc, const char *argv[]) {
  66. // Check for valid command line arguments, print usage
  67. // if no arguments were given.
  68. if (argc != 2 && argc != 3) {
  69. cout << "Usage: " << argv[0] << " <csv> [arg2]\n"
  70. << "\t<csv> - path to config file in CSV format\n"
  71. << "\targ2 - if the 2nd argument is provided (with any value) "
  72. << "the advanced stuff is run and shown to console.\n"
  73. << "The CSV config file consists of the following lines:\n"
  74. << "<path>;<label>[;<comment>]\n"
  75. << "\t<path> - file, dir or wildcard path\n"
  76. << "\t<label> - non-negative integer person label\n"
  77. << "\t<comment> - optional comment string (e.g. person name)"
  78. << endl;
  79. exit(1);
  80. }
  81. // Get the path to your CSV.
  82. string fn_csv = string(argv[1]);
  83. // These vectors hold the images and corresponding labels.
  84. vector<Mat> images;
  85. vector<int> labels;
  86. std::map<int, string> labelsInfo;
  87. // Read in the data. This can fail if no valid
  88. // input filename is given.
  89. try {
  90. read_csv(fn_csv, images, labels, labelsInfo);
  91. } catch (const cv::Exception& e) {
  92. cerr << "Error opening file \"" << fn_csv << "\". Reason: " << e.msg << endl;
  93. // nothing more we can do
  94. exit(1);
  95. }
  96. // Quit if there are not enough images for this demo.
  97. if(images.size() <= 1) {
  98. string error_message = "This demo needs at least 2 images to work. Please add more images to your data set!";
  99. CV_Error(Error::StsError, error_message);
  100. }
  101. // The following lines simply get the last images from
  102. // your dataset and remove it from the vector. This is
  103. // done, so that the training data (which we learn the
  104. // cv::FaceRecognizer on) and the test data we test
  105. // the model with, do not overlap.
  106. Mat testSample = images[images.size() - 1];
  107. int nlabels = (int)labels.size();
  108. int testLabel = labels[nlabels-1];
  109. images.pop_back();
  110. labels.pop_back();
  111. // The following lines create an Eigenfaces model for
  112. // face recognition and train it with the images and
  113. // labels read from the given CSV file.
  114. // This here is a full PCA, if you just want to keep
  115. // 10 principal components (read Eigenfaces), then call
  116. // the factory method like this:
  117. //
  118. // EigenFaceRecognizer::create(10);
  119. //
  120. // If you want to create a FaceRecognizer with a
  121. // confidennce threshold, call it with:
  122. //
  123. // EigenFaceRecognizer::create(10, 123.0);
  124. //
  125. Ptr<EigenFaceRecognizer> model = EigenFaceRecognizer::create();
  126. for( int i = 0; i < nlabels; i++ )
  127. model->setLabelInfo(i, labelsInfo[i]);
  128. model->train(images, labels);
  129. string saveModelPath = "face-rec-model.txt";
  130. cout << "Saving the trained model to " << saveModelPath << endl;
  131. model->save(saveModelPath);
  132. // The following line predicts the label of a given
  133. // test image:
  134. int predictedLabel = model->predict(testSample);
  135. //
  136. // To get the confidence of a prediction call the model with:
  137. //
  138. // int predictedLabel = -1;
  139. // double confidence = 0.0;
  140. // model->predict(testSample, predictedLabel, confidence);
  141. //
  142. string result_message = format("Predicted class = %d / Actual class = %d.", predictedLabel, testLabel);
  143. cout << result_message << endl;
  144. if( (predictedLabel == testLabel) && !model->getLabelInfo(predictedLabel).empty() )
  145. cout << format("%d-th label's info: %s", predictedLabel, model->getLabelInfo(predictedLabel).c_str()) << endl;
  146. // advanced stuff
  147. if(argc>2) {
  148. // Sometimes you'll need to get/set internal model data,
  149. // which isn't exposed by the public cv::FaceRecognizer.
  150. // Since each cv::FaceRecognizer is derived from a
  151. // cv::Algorithm, you can query the data.
  152. //
  153. // First we'll use it to set the threshold of the FaceRecognizer
  154. // to 0.0 without retraining the model. This can be useful if
  155. // you are evaluating the model:
  156. //
  157. model->setThreshold(0.0);
  158. // Now the threshold of this model is set to 0.0. A prediction
  159. // now returns -1, as it's impossible to have a distance below
  160. // it
  161. predictedLabel = model->predict(testSample);
  162. cout << "Predicted class = " << predictedLabel << endl;
  163. // Here is how to get the eigenvalues of this Eigenfaces model:
  164. Mat eigenvalues = model->getEigenValues();
  165. // And we can do the same to display the Eigenvectors (read Eigenfaces):
  166. Mat W = model->getEigenVectors();
  167. // From this we will display the (at most) first 10 Eigenfaces:
  168. for (int i = 0; i < min(10, W.cols); i++) {
  169. string msg = format("Eigenvalue #%d = %.5f", i, eigenvalues.at<double>(i));
  170. cout << msg << endl;
  171. // get eigenvector #i
  172. Mat ev = W.col(i).clone();
  173. // Reshape to original size & normalize to [0...255] for imshow.
  174. Mat grayscale;
  175. normalize(ev.reshape(1), grayscale, 0, 255, NORM_MINMAX, CV_8UC1);
  176. // Show the image & apply a Jet colormap for better sensing.
  177. Mat cgrayscale;
  178. applyColorMap(grayscale, cgrayscale, COLORMAP_JET);
  179. imshow(format("%d", i), cgrayscale);
  180. }
  181. waitKey(0);
  182. }
  183. return 0;
  184. }