pca.cpp 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. /*
  2. * pca.cpp
  3. *
  4. * Author:
  5. * Kevin Hughes <kevinhughes27[at]gmail[dot]com>
  6. *
  7. * Special Thanks to:
  8. * Philipp Wagner <bytefish[at]gmx[dot]de>
  9. *
  10. * This program demonstrates how to use OpenCV PCA with a
  11. * specified amount of variance to retain. The effect
  12. * is illustrated further by using a trackbar to
  13. * change the value for retained variance.
  14. *
  15. * The program takes as input a text file with each line
  16. * begin the full path to an image. PCA will be performed
  17. * on this list of images. The author recommends using
  18. * the first 15 faces of the AT&T face data set:
  19. * http://www.cl.cam.ac.uk/research/dtg/attarchive/facedatabase.html
  20. *
  21. * so for example your input text file would look like this:
  22. *
  23. * <path_to_at&t_faces>/orl_faces/s1/1.pgm
  24. * <path_to_at&t_faces>/orl_faces/s2/1.pgm
  25. * <path_to_at&t_faces>/orl_faces/s3/1.pgm
  26. * <path_to_at&t_faces>/orl_faces/s4/1.pgm
  27. * <path_to_at&t_faces>/orl_faces/s5/1.pgm
  28. * <path_to_at&t_faces>/orl_faces/s6/1.pgm
  29. * <path_to_at&t_faces>/orl_faces/s7/1.pgm
  30. * <path_to_at&t_faces>/orl_faces/s8/1.pgm
  31. * <path_to_at&t_faces>/orl_faces/s9/1.pgm
  32. * <path_to_at&t_faces>/orl_faces/s10/1.pgm
  33. * <path_to_at&t_faces>/orl_faces/s11/1.pgm
  34. * <path_to_at&t_faces>/orl_faces/s12/1.pgm
  35. * <path_to_at&t_faces>/orl_faces/s13/1.pgm
  36. * <path_to_at&t_faces>/orl_faces/s14/1.pgm
  37. * <path_to_at&t_faces>/orl_faces/s15/1.pgm
  38. *
  39. */
  40. #include <iostream>
  41. #include <fstream>
  42. #include <sstream>
  43. #include <opencv2/core.hpp>
  44. #include "opencv2/imgcodecs.hpp"
  45. #include <opencv2/highgui.hpp>
  46. using namespace cv;
  47. using namespace std;
  48. ///////////////////////
  49. // Functions
  50. static void read_imgList(const string& filename, vector<Mat>& images) {
  51. std::ifstream file(filename.c_str(), ifstream::in);
  52. if (!file) {
  53. string error_message = "No valid input file was given, please check the given filename.";
  54. CV_Error(Error::StsBadArg, error_message);
  55. }
  56. string line;
  57. while (getline(file, line)) {
  58. images.push_back(imread(line, 0));
  59. }
  60. }
  61. static Mat formatImagesForPCA(const vector<Mat> &data)
  62. {
  63. Mat dst(static_cast<int>(data.size()), data[0].rows*data[0].cols, CV_32F);
  64. for(unsigned int i = 0; i < data.size(); i++)
  65. {
  66. Mat image_row = data[i].clone().reshape(1,1);
  67. Mat row_i = dst.row(i);
  68. image_row.convertTo(row_i,CV_32F);
  69. }
  70. return dst;
  71. }
  72. static Mat toGrayscale(InputArray _src) {
  73. Mat src = _src.getMat();
  74. // only allow one channel
  75. if(src.channels() != 1) {
  76. CV_Error(Error::StsBadArg, "Only Matrices with one channel are supported");
  77. }
  78. // create and return normalized image
  79. Mat dst;
  80. cv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC1);
  81. return dst;
  82. }
  83. struct params
  84. {
  85. Mat data;
  86. int ch;
  87. int rows;
  88. PCA pca;
  89. string winName;
  90. };
  91. static void onTrackbar(int pos, void* ptr)
  92. {
  93. cout << "Retained Variance = " << pos << "% ";
  94. cout << "re-calculating PCA..." << std::flush;
  95. double var = pos / 100.0;
  96. struct params *p = (struct params *)ptr;
  97. p->pca = PCA(p->data, cv::Mat(), PCA::DATA_AS_ROW, var);
  98. Mat point = p->pca.project(p->data.row(0));
  99. Mat reconstruction = p->pca.backProject(point);
  100. reconstruction = reconstruction.reshape(p->ch, p->rows);
  101. reconstruction = toGrayscale(reconstruction);
  102. imshow(p->winName, reconstruction);
  103. cout << "done! # of principal components: " << p->pca.eigenvectors.rows << endl;
  104. }
  105. ///////////////////////
  106. // Main
  107. int main(int argc, char** argv)
  108. {
  109. cv::CommandLineParser parser(argc, argv, "{@input||image list}{help h||show help message}");
  110. if (parser.has("help"))
  111. {
  112. parser.printMessage();
  113. exit(0);
  114. }
  115. // Get the path to your CSV.
  116. string imgList = parser.get<string>("@input");
  117. if (imgList.empty())
  118. {
  119. parser.printMessage();
  120. exit(1);
  121. }
  122. // vector to hold the images
  123. vector<Mat> images;
  124. // Read in the data. This can fail if not valid
  125. try {
  126. read_imgList(imgList, images);
  127. } catch (const cv::Exception& e) {
  128. cerr << "Error opening file \"" << imgList << "\". Reason: " << e.msg << endl;
  129. exit(1);
  130. }
  131. // Quit if there are not enough images for this demo.
  132. if(images.size() <= 1) {
  133. string error_message = "This demo needs at least 2 images to work. Please add more images to your data set!";
  134. CV_Error(Error::StsError, error_message);
  135. }
  136. // Reshape and stack images into a rowMatrix
  137. Mat data = formatImagesForPCA(images);
  138. // perform PCA
  139. PCA pca(data, cv::Mat(), PCA::DATA_AS_ROW, 0.95); // trackbar is initially set here, also this is a common value for retainedVariance
  140. // Demonstration of the effect of retainedVariance on the first image
  141. Mat point = pca.project(data.row(0)); // project into the eigenspace, thus the image becomes a "point"
  142. Mat reconstruction = pca.backProject(point); // re-create the image from the "point"
  143. reconstruction = reconstruction.reshape(images[0].channels(), images[0].rows); // reshape from a row vector into image shape
  144. reconstruction = toGrayscale(reconstruction); // re-scale for displaying purposes
  145. // init highgui window
  146. string winName = "Reconstruction | press 'q' to quit";
  147. namedWindow(winName, WINDOW_NORMAL);
  148. // params struct to pass to the trackbar handler
  149. params p;
  150. p.data = data;
  151. p.ch = images[0].channels();
  152. p.rows = images[0].rows;
  153. p.pca = pca;
  154. p.winName = winName;
  155. // create the tracbar
  156. int pos = 95;
  157. createTrackbar("Retained Variance (%)", winName, &pos, 100, onTrackbar, (void*)&p);
  158. // display until user presses q
  159. imshow(winName, reconstruction);
  160. char key = 0;
  161. while(key != 'q')
  162. key = (char)waitKey();
  163. return 0;
  164. }