Merge pull request #2887 from ilya-lavrenov:ipp_morph_fix
[platform/upstream/opencv.git] / modules / contrib / doc / facerec / src / facerec_eigenfaces.cpp
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
19 #include "opencv2/core.hpp"
20 #include "opencv2/contrib.hpp"
21 #include "opencv2/highgui.hpp"
22
23 #include <iostream>
24 #include <fstream>
25 #include <sstream>
26
27 using namespace cv;
28 using namespace std;
29
30 static Mat norm_0_255(InputArray _src) {
31     Mat src = _src.getMat();
32     // Create and return normalized image:
33     Mat dst;
34     switch(src.channels()) {
35     case 1:
36         cv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC1);
37         break;
38     case 3:
39         cv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC3);
40         break;
41     default:
42         src.copyTo(dst);
43         break;
44     }
45     return dst;
46 }
47
48 static void read_csv(const string& filename, vector<Mat>& images, vector<int>& labels, char separator = ';') {
49     std::ifstream file(filename.c_str(), ifstream::in);
50     if (!file) {
51         string error_message = "No valid input file was given, please check the given filename.";
52         CV_Error(CV_StsBadArg, error_message);
53     }
54     string line, path, classlabel;
55     while (getline(file, line)) {
56         stringstream liness(line);
57         getline(liness, path, separator);
58         getline(liness, classlabel);
59         if(!path.empty() && !classlabel.empty()) {
60             images.push_back(imread(path, 0));
61             labels.push_back(atoi(classlabel.c_str()));
62         }
63     }
64 }
65
66 int main(int argc, const char *argv[]) {
67     // Check for valid command line arguments, print usage
68     // if no arguments were given.
69     if (argc < 2) {
70         cout << "usage: " << argv[0] << " <csv.ext> <output_folder> " << endl;
71         exit(1);
72     }
73     string output_folder = ".";
74     if (argc == 3) {
75         output_folder = string(argv[2]);
76     }
77     // Get the path to your CSV.
78     string fn_csv = string(argv[1]);
79     // These vectors hold the images and corresponding labels.
80     vector<Mat> images;
81     vector<int> labels;
82     // Read in the data. This can fail if no valid
83     // input filename is given.
84     try {
85         read_csv(fn_csv, images, labels);
86     } catch (cv::Exception& e) {
87         cerr << "Error opening file \"" << fn_csv << "\". Reason: " << e.msg << endl;
88         // nothing more we can do
89         exit(1);
90     }
91     // Quit if there are not enough images for this demo.
92     if(images.size() <= 1) {
93         string error_message = "This demo needs at least 2 images to work. Please add more images to your data set!";
94         CV_Error(CV_StsError, error_message);
95     }
96     // Get the height from the first image. We'll need this
97     // later in code to reshape the images to their original
98     // size:
99     int height = images[0].rows;
100     // The following lines simply get the last images from
101     // your dataset and remove it from the vector. This is
102     // done, so that the training data (which we learn the
103     // cv::FaceRecognizer on) and the test data we test
104     // the model with, do not overlap.
105     Mat testSample = images[images.size() - 1];
106     int testLabel = labels[labels.size() - 1];
107     images.pop_back();
108     labels.pop_back();
109     // The following lines create an Eigenfaces model for
110     // face recognition and train it with the images and
111     // labels read from the given CSV file.
112     // This here is a full PCA, if you just want to keep
113     // 10 principal components (read Eigenfaces), then call
114     // the factory method like this:
115     //
116     //      cv::createEigenFaceRecognizer(10);
117     //
118     // If you want to create a FaceRecognizer with a
119     // confidence threshold (e.g. 123.0), call it with:
120     //
121     //      cv::createEigenFaceRecognizer(10, 123.0);
122     //
123     // If you want to use _all_ Eigenfaces and have a threshold,
124     // then call the method like this:
125     //
126     //      cv::createEigenFaceRecognizer(0, 123.0);
127     //
128     Ptr<FaceRecognizer> model = createEigenFaceRecognizer();
129     model->train(images, labels);
130     // The following line predicts the label of a given
131     // test image:
132     int predictedLabel = model->predict(testSample);
133     //
134     // To get the confidence of a prediction call the model with:
135     //
136     //      int predictedLabel = -1;
137     //      double confidence = 0.0;
138     //      model->predict(testSample, predictedLabel, confidence);
139     //
140     string result_message = format("Predicted class = %d / Actual class = %d.", predictedLabel, testLabel);
141     cout << result_message << endl;
142     // Here is how to get the eigenvalues of this Eigenfaces model:
143     Mat eigenvalues = model->getMat("eigenvalues");
144     // And we can do the same to display the Eigenvectors (read Eigenfaces):
145     Mat W = model->getMat("eigenvectors");
146     // Get the sample mean from the training data
147     Mat mean = model->getMat("mean");
148     // Display or save:
149     if(argc == 2) {
150         imshow("mean", norm_0_255(mean.reshape(1, images[0].rows)));
151     } else {
152         imwrite(format("%s/mean.png", output_folder.c_str()), norm_0_255(mean.reshape(1, images[0].rows)));
153     }
154     // Display or save the Eigenfaces:
155     for (int i = 0; i < min(10, W.cols); i++) {
156         string msg = format("Eigenvalue #%d = %.5f", i, eigenvalues.at<double>(i));
157         cout << msg << endl;
158         // get eigenvector #i
159         Mat ev = W.col(i).clone();
160         // Reshape to original size & normalize to [0...255] for imshow.
161         Mat grayscale = norm_0_255(ev.reshape(1, height));
162         // Show the image & apply a Jet colormap for better sensing.
163         Mat cgrayscale;
164         applyColorMap(grayscale, cgrayscale, COLORMAP_JET);
165         // Display or save:
166         if(argc == 2) {
167             imshow(format("eigenface_%d", i), cgrayscale);
168         } else {
169             imwrite(format("%s/eigenface_%d.png", output_folder.c_str(), i), norm_0_255(cgrayscale));
170         }
171     }
172
173     // Display or save the image reconstruction at some predefined steps:
174     for(int num_components = min(W.cols, 10); num_components < min(W.cols, 300); num_components+=15) {
175         // slice the eigenvectors from the model
176         Mat evs = Mat(W, Range::all(), Range(0, num_components));
177         Mat projection = subspaceProject(evs, mean, images[0].reshape(1,1));
178         Mat reconstruction = subspaceReconstruct(evs, mean, projection);
179         // Normalize the result:
180         reconstruction = norm_0_255(reconstruction.reshape(1, images[0].rows));
181         // Display or save:
182         if(argc == 2) {
183             imshow(format("eigenface_reconstruction_%d", num_components), reconstruction);
184         } else {
185             imwrite(format("%s/eigenface_reconstruction_%d.png", output_folder.c_str(), num_components), reconstruction);
186         }
187     }
188     // Display if we are not writing to an output folder:
189     if(argc == 2) {
190         waitKey(0);
191     }
192     return 0;
193 }