5 * Kevin Hughes <kevinhughes27[at]gmail[dot]com>
8 * Philipp Wagner <bytefish[at]gmx[dot]de>
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 varaince.
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
21 * so for example your input text file would look like this:
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
45 #include <opencv2/core/core.hpp>
46 #include <opencv2/highgui/highgui.hpp>
51 ///////////////////////
53 void read_imgList(const string& filename, vector<Mat>& images) {
54 std::ifstream file(filename.c_str(), ifstream::in);
56 string error_message = "No valid input file was given, please check the given filename.";
57 CV_Error(CV_StsBadArg, error_message);
60 while (getline(file, line)) {
61 images.push_back(imread(line, 0));
65 Mat formatImagesForPCA(const vector<Mat> &data)
67 Mat dst(data.size(), data[0].rows*data[0].cols, CV_32F);
68 for(unsigned int i = 0; i < data.size(); i++)
70 Mat image_row = data[i].clone().reshape(1,1);
71 Mat row_i = dst.row(i);
72 image_row.convertTo(row_i,CV_32F);
77 Mat toGrayscale(InputArray _src) {
78 Mat src = _src.getMat();
79 // only allow one channel
80 if(src.channels() != 1) {
81 CV_Error(CV_StsBadArg, "Only Matrices with one channel are supported");
83 // create and return normalized image
85 cv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC1);
98 void onTrackbar(int pos, void* ptr)
100 cout << "Retained Variance = " << pos << "% ";
101 cout << "re-calculating PCA..." << std::flush;
103 double var = pos / 100.0;
105 struct params *p = (struct params *)ptr;
107 p->pca = PCA(p->data, cv::Mat(), CV_PCA_DATA_AS_ROW, var);
109 Mat point = p->pca.project(p->data.row(0));
110 Mat reconstruction = p->pca.backProject(point);
111 reconstruction = reconstruction.reshape(p->ch, p->rows);
112 reconstruction = toGrayscale(reconstruction);
114 imshow(p->winName, reconstruction);
115 cout << "done! # of principal components: " << p->pca.eigenvectors.rows << endl;
119 ///////////////////////
121 int main(int argc, char** argv)
124 cout << "usage: " << argv[0] << " <image_list.txt>" << endl;
128 // Get the path to your CSV.
129 string imgList = string(argv[1]);
131 // vector to hold the images
134 // Read in the data. This can fail if not valid
136 read_imgList(imgList, images);
137 } catch (cv::Exception& e) {
138 cerr << "Error opening file \"" << imgList << "\". Reason: " << e.msg << endl;
142 // Quit if there are not enough images for this demo.
143 if(images.size() <= 1) {
144 string error_message = "This demo needs at least 2 images to work. Please add more images to your data set!";
145 CV_Error(CV_StsError, error_message);
148 // Reshape and stack images into a rowMatrix
149 Mat data = formatImagesForPCA(images);
152 PCA pca(data, cv::Mat(), CV_PCA_DATA_AS_ROW, 0.95); // trackbar is initially set here, also this is a common value for retainedVariance
154 // Demonstration of the effect of retainedVariance on the first image
155 Mat point = pca.project(data.row(0)); // project into the eigenspace, thus the image becomes a "point"
156 Mat reconstruction = pca.backProject(point); // re-create the image from the "point"
157 reconstruction = reconstruction.reshape(images[0].channels(), images[0].rows); // reshape from a row vector into image shape
158 reconstruction = toGrayscale(reconstruction); // re-scale for displaying purposes
160 // init highgui window
161 string winName = "Reconstruction | press 'q' to quit";
162 namedWindow(winName, CV_WINDOW_NORMAL);
164 // params struct to pass to the trackbar handler
167 p.ch = images[0].channels();
168 p.rows = images[0].rows;
172 // create the tracbar
174 createTrackbar("Retained Variance (%)", winName, &pos, 100, onTrackbar, (void*)&p);
176 // display until user presses q
177 imshow(winName, reconstruction);