3a104b86b309a75e9fe06e67e30203d76331bdc5
[platform/upstream/opencv.git] / samples / cpp / facerec_demo.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/core/utility.hpp"
21 #include "opencv2/highgui.hpp"
22 #include "opencv2/contrib.hpp"
23
24 #include <iostream>
25 #include <fstream>
26 #include <sstream>
27
28 using namespace cv;
29 using namespace std;
30
31 static Mat toGrayscale(InputArray _src) {
32     Mat src = _src.getMat();
33     // only allow one channel
34     if(src.channels() != 1) {
35         CV_Error(Error::StsBadArg, "Only Matrices with one channel are supported");
36     }
37     // create and return normalized image
38     Mat dst;
39     cv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC1);
40     return dst;
41 }
42
43 static void read_csv(const string& filename, vector<Mat>& images, vector<int>& labels, char separator = ';') {
44     std::ifstream file(filename.c_str(), ifstream::in);
45     if (!file) {
46         string error_message = "No valid input file was given, please check the given filename.";
47         CV_Error(Error::StsBadArg, error_message);
48     }
49     string line, path, classlabel;
50     while (getline(file, line)) {
51         stringstream liness(line);
52         getline(liness, path, separator);
53         getline(liness, classlabel);
54         if(!path.empty() && !classlabel.empty()) {
55             images.push_back(imread(path, 0));
56             labels.push_back(atoi(classlabel.c_str()));
57         }
58     }
59 }
60
61 int main(int argc, const char *argv[]) {
62     // Check for valid command line arguments, print usage
63     // if no arguments were given.
64     if (argc != 2) {
65         cout << "usage: " << argv[0] << " <csv.ext>" << endl;
66         exit(1);
67     }
68     // Get the path to your CSV.
69     string fn_csv = string(argv[1]);
70     // These vectors hold the images and corresponding labels.
71     vector<Mat> images;
72     vector<int> labels;
73     // Read in the data. This can fail if no valid
74     // input filename is given.
75     try {
76         read_csv(fn_csv, images, labels);
77     } catch (cv::Exception& e) {
78         cerr << "Error opening file \"" << fn_csv << "\". Reason: " << e.msg << endl;
79         // nothing more we can do
80         exit(1);
81     }
82     // Quit if there are not enough images for this demo.
83     if(images.size() <= 1) {
84         string error_message = "This demo needs at least 2 images to work. Please add more images to your data set!";
85         CV_Error(Error::StsError, error_message);
86     }
87     // Get the height from the first image. We'll need this
88     // later in code to reshape the images to their original
89     // size:
90     int height = images[0].rows;
91     // The following lines simply get the last images from
92     // your dataset and remove it from the vector. This is
93     // done, so that the training data (which we learn the
94     // cv::FaceRecognizer on) and the test data we test
95     // the model with, do not overlap.
96     Mat testSample = images[images.size() - 1];
97     int testLabel = labels[labels.size() - 1];
98     images.pop_back();
99     labels.pop_back();
100     // The following lines create an Eigenfaces model for
101     // face recognition and train it with the images and
102     // labels read from the given CSV file.
103     // This here is a full PCA, if you just want to keep
104     // 10 principal components (read Eigenfaces), then call
105     // the factory method like this:
106     //
107     //      cv::createEigenFaceRecognizer(10);
108     //
109     // If you want to create a FaceRecognizer with a
110     // confidennce threshold, call it with:
111     //
112     //      cv::createEigenFaceRecognizer(10, 123.0);
113     //
114     Ptr<FaceRecognizer> model = createEigenFaceRecognizer();
115     model->train(images, labels);
116     // The following line predicts the label of a given
117     // test image:
118     int predictedLabel = model->predict(testSample);
119     //
120     // To get the confidence of a prediction call the model with:
121     //
122     //      int predictedLabel = -1;
123     //      double confidence = 0.0;
124     //      model->predict(testSample, predictedLabel, confidence);
125     //
126     string result_message = format("Predicted class = %d / Actual class = %d.", predictedLabel, testLabel);
127     cout << result_message << endl;
128     // Sometimes you'll need to get/set internal model data,
129     // which isn't exposed by the public cv::FaceRecognizer.
130     // Since each cv::FaceRecognizer is derived from a
131     // cv::Algorithm, you can query the data.
132     //
133     // First we'll use it to set the threshold of the FaceRecognizer
134     // to 0.0 without retraining the model. This can be useful if
135     // you are evaluating the model:
136     //
137     model->set("threshold", 0.0);
138     // Now the threshold of this model is set to 0.0. A prediction
139     // now returns -1, as it's impossible to have a distance below
140     // it
141     predictedLabel = model->predict(testSample);
142     cout << "Predicted class = " << predictedLabel << endl;
143     // Here is how to get the eigenvalues of this Eigenfaces model:
144     Mat eigenvalues = model->getMat("eigenvalues");
145     // And we can do the same to display the Eigenvectors (read Eigenfaces):
146     Mat W = model->getMat("eigenvectors");
147     // From this we will display the (at most) first 10 Eigenfaces:
148     for (int i = 0; i < min(10, W.cols); i++) {
149         string msg = format("Eigenvalue #%d = %.5f", i, eigenvalues.at<double>(i));
150         cout << msg << endl;
151         // get eigenvector #i
152         Mat ev = W.col(i).clone();
153         // Reshape to original size & normalize to [0...255] for imshow.
154         Mat grayscale = toGrayscale(ev.reshape(1, height));
155         // Show the image & apply a Jet colormap for better sensing.
156         Mat cgrayscale;
157         applyColorMap(grayscale, cgrayscale, COLORMAP_JET);
158         imshow(format("%d", i), cgrayscale);
159     }
160     waitKey(0);
161
162     return 0;
163 }