Merge pull request #1263 from abidrahmank:pyCLAHE_24
[profile/ivi/opencv.git] / modules / contrib / doc / facerec / facerec_api.rst
1 FaceRecognizer
2 ==============
3
4 .. highlight:: cpp
5
6 .. Sample code::
7
8    * An example using the FaceRecognizer class can be found at opencv_source_code/samples/cpp/facerec_demo.cpp
9
10    * (Python)  An example using the FaceRecognizer class can be found at opencv_source_code/samples/python2/facerec_demo.py
11
12 FaceRecognizer
13 --------------
14
15 .. ocv:class:: FaceRecognizer : public Algorithm
16
17 All face recognition models in OpenCV are derived from the abstract base class :ocv:class:`FaceRecognizer`, which provides
18 a unified access to all face recongition algorithms in OpenCV. ::
19
20   class FaceRecognizer : public Algorithm
21   {
22   public:
23       //! virtual destructor
24       virtual ~FaceRecognizer() {}
25
26       // Trains a FaceRecognizer.
27       virtual void train(InputArray src, InputArray labels) = 0;
28
29       // Updates a FaceRecognizer.
30       virtual void update(InputArrayOfArrays src, InputArray labels);
31
32       // Gets a prediction from a FaceRecognizer.
33       virtual int predict(InputArray src) const = 0;
34
35       // Predicts the label and confidence for a given sample.
36       virtual void predict(InputArray src, int &label, double &confidence) const = 0;
37
38       // Serializes this object to a given filename.
39       virtual void save(const string& filename) const;
40
41       // Deserializes this object from a given filename.
42       virtual void load(const string& filename);
43
44       // Serializes this object to a given cv::FileStorage.
45       virtual void save(FileStorage& fs) const = 0;
46
47       // Deserializes this object from a given cv::FileStorage.
48       virtual void load(const FileStorage& fs) = 0;
49   };
50
51
52 Description
53 +++++++++++
54
55 I'll go a bit more into detail explaining :ocv:class:`FaceRecognizer`, because it doesn't look like a powerful interface at first sight. But: Every :ocv:class:`FaceRecognizer` is an :ocv:class:`Algorithm`, so you can easily get/set all model internals (if allowed by the implementation). :ocv:class:`Algorithm` is a relatively new OpenCV concept, which is available since the 2.4 release. I suggest you take a look at its description.
56
57 :ocv:class:`Algorithm` provides the following features for all derived classes:
58
59 * So called “virtual constructor”. That is, each Algorithm derivative is registered at program start and you can get the list of registered algorithms and create instance of a particular algorithm by its name (see :ocv:func:`Algorithm::create`). If you plan to add your own algorithms, it is good practice to add a unique prefix to your algorithms to distinguish them from other algorithms.
60
61 * Setting/Retrieving algorithm parameters by name. If you used video capturing functionality from OpenCV highgui module, you are probably familar with :ocv:cfunc:`cvSetCaptureProperty`, :ocv:cfunc:`cvGetCaptureProperty`, :ocv:func:`VideoCapture::set` and :ocv:func:`VideoCapture::get`. :ocv:class:`Algorithm` provides similar method where instead of integer id's you specify the parameter names as text strings. See :ocv:func:`Algorithm::set` and :ocv:func:`Algorithm::get` for details.
62
63 * Reading and writing parameters from/to XML or YAML files. Every Algorithm derivative can store all its parameters and then read them back. There is no need to re-implement it each time.
64
65 Moreover every :ocv:class:`FaceRecognizer` supports the:
66
67 * **Training** of a :ocv:class:`FaceRecognizer` with :ocv:func:`FaceRecognizer::train` on a given set of images (your face database!).
68
69 * **Prediction** of a given sample image, that means a face. The image is given as a :ocv:class:`Mat`.
70
71 * **Loading/Saving** the model state from/to a given XML or YAML.
72
73 Setting the Thresholds
74 +++++++++++++++++++++++
75
76 Sometimes you run into the situation, when you want to apply a threshold on the prediction. A common scenario in face recognition is to tell, wether a face belongs to the training dataset or if it is unknown. You might wonder, why there's no public API in :ocv:class:`FaceRecognizer` to set the threshold for the prediction, but rest assured: It's supported. It just means there's no generic way in an abstract class to provide an interface for setting/getting the thresholds of *every possible* :ocv:class:`FaceRecognizer` algorithm. The appropriate place to set the thresholds is in the constructor of the specific :ocv:class:`FaceRecognizer` and since every :ocv:class:`FaceRecognizer` is a :ocv:class:`Algorithm` (see above), you can get/set the thresholds at runtime!
77
78 Here is an example of setting a threshold for the Eigenfaces method, when creating the model:
79
80 .. code-block:: cpp
81
82     // Let's say we want to keep 10 Eigenfaces and have a threshold value of 10.0
83     int num_components = 10;
84     double threshold = 10.0;
85     // Then if you want to have a cv::FaceRecognizer with a confidence threshold,
86     // create the concrete implementation with the appropiate parameters:
87     Ptr<FaceRecognizer> model = createEigenFaceRecognizer(num_components, threshold);
88
89 Sometimes it's impossible to train the model, just to experiment with threshold values. Thanks to :ocv:class:`Algorithm` it's possible to set internal model thresholds during runtime. Let's see how we would set/get the prediction for the Eigenface model, we've created above:
90
91 .. code-block:: cpp
92
93     // The following line reads the threshold from the Eigenfaces model:
94     double current_threshold = model->getDouble("threshold");
95     // And this line sets the threshold to 0.0:
96     model->set("threshold", 0.0);
97
98 If you've set the threshold to ``0.0`` as we did above, then:
99
100 .. code-block:: cpp
101
102     //
103     Mat img = imread("person1/3.jpg", CV_LOAD_IMAGE_GRAYSCALE);
104     // Get a prediction from the model. Note: We've set a threshold of 0.0 above,
105     // since the distance is almost always larger than 0.0, you'll get -1 as
106     // label, which indicates, this face is unknown
107     int predicted_label = model->predict(img);
108     // ...
109
110 is going to yield ``-1`` as predicted label, which states this face is unknown.
111
112 Getting the name of a FaceRecognizer
113 +++++++++++++++++++++++++++++++++++++
114
115 Since every :ocv:class:`FaceRecognizer` is a :ocv:class:`Algorithm`, you can use :ocv:func:`Algorithm::name` to get the name of a :ocv:class:`FaceRecognizer`:
116
117 .. code-block:: cpp
118
119     // Create a FaceRecognizer:
120     Ptr<FaceRecognizer> model = createEigenFaceRecognizer();
121     // And here's how to get its name:
122     std::string name = model->name();
123
124
125 FaceRecognizer::train
126 ---------------------
127
128 Trains a FaceRecognizer with given data and associated labels.
129
130 .. ocv:function:: void FaceRecognizer::train( InputArrayOfArrays src, InputArray labels ) = 0
131
132     :param src: The training images, that means the faces you want to learn. The data has to be given as a ``vector<Mat>``.
133
134     :param labels: The labels corresponding to the images have to be given either as a ``vector<int>`` or a
135
136 The following source code snippet shows you how to learn a Fisherfaces model on a given set of images. The images are read with :ocv:func:`imread` and pushed into a ``std::vector<Mat>``. The labels of each image are stored within a ``std::vector<int>`` (you could also use a :ocv:class:`Mat` of type `CV_32SC1`). Think of the label as the subject (the person) this image belongs to, so same subjects (persons) should have the same label. For the available :ocv:class:`FaceRecognizer` you don't have to pay any attention to the order of the labels, just make sure same persons have the same label:
137
138 .. code-block:: cpp
139
140     // holds images and labels
141     vector<Mat> images;
142     vector<int> labels;
143     // images for first person
144     images.push_back(imread("person0/0.jpg", CV_LOAD_IMAGE_GRAYSCALE)); labels.push_back(0);
145     images.push_back(imread("person0/1.jpg", CV_LOAD_IMAGE_GRAYSCALE)); labels.push_back(0);
146     images.push_back(imread("person0/2.jpg", CV_LOAD_IMAGE_GRAYSCALE)); labels.push_back(0);
147     // images for second person
148     images.push_back(imread("person1/0.jpg", CV_LOAD_IMAGE_GRAYSCALE)); labels.push_back(1);
149     images.push_back(imread("person1/1.jpg", CV_LOAD_IMAGE_GRAYSCALE)); labels.push_back(1);
150     images.push_back(imread("person1/2.jpg", CV_LOAD_IMAGE_GRAYSCALE)); labels.push_back(1);
151
152 Now that you have read some images, we can create a new :ocv:class:`FaceRecognizer`. In this example I'll create a Fisherfaces model and decide to keep all of the possible Fisherfaces:
153
154 .. code-block:: cpp
155
156     // Create a new Fisherfaces model and retain all available Fisherfaces,
157     // this is the most common usage of this specific FaceRecognizer:
158     //
159     Ptr<FaceRecognizer> model =  createFisherFaceRecognizer();
160
161 And finally train it on the given dataset (the face images and labels):
162
163 .. code-block:: cpp
164
165     // This is the common interface to train all of the available cv::FaceRecognizer
166     // implementations:
167     //
168     model->train(images, labels);
169
170 FaceRecognizer::update
171 ----------------------
172
173 Updates a FaceRecognizer with given data and associated labels.
174
175 .. ocv:function:: void FaceRecognizer::update( InputArrayOfArrays src, InputArray labels )
176
177     :param src: The training images, that means the faces you want to learn. The data has to be given as a ``vector<Mat>``.
178
179     :param labels: The labels corresponding to the images have to be given either as a ``vector<int>`` or a
180
181 This method updates a (probably trained) :ocv:class:`FaceRecognizer`, but only if the algorithm supports it. The Local Binary Patterns Histograms (LBPH) recognizer (see :ocv:func:`createLBPHFaceRecognizer`) can be updated. For the Eigenfaces and Fisherfaces method, this is algorithmically not possible and you have to re-estimate the model with :ocv:func:`FaceRecognizer::train`. In any case, a call to train empties the existing model and learns a new model, while update does not delete any model data.
182
183 .. code-block:: cpp
184
185     // Create a new LBPH model (it can be updated) and use the default parameters,
186     // this is the most common usage of this specific FaceRecognizer:
187     //
188     Ptr<FaceRecognizer> model =  createLBPHFaceRecognizer();
189     // This is the common interface to train all of the available cv::FaceRecognizer
190     // implementations:
191     //
192     model->train(images, labels);
193     // Some containers to hold new image:
194     vector<Mat> newImages;
195     vector<int> newLabels;
196     // You should add some images to the containers:
197     //
198     // ...
199     //
200     // Now updating the model is as easy as calling:
201     model->update(newImages,newLabels);
202     // This will preserve the old model data and extend the existing model
203     // with the new features extracted from newImages!
204
205 Calling update on an Eigenfaces model (see :ocv:func:`createEigenFaceRecognizer`), which doesn't support updating, will throw an error similar to:
206
207 .. code-block:: none
208
209     OpenCV Error: The function/feature is not implemented (This FaceRecognizer (FaceRecognizer.Eigenfaces) does not support updating, you have to use FaceRecognizer::train to update it.) in update, file /home/philipp/git/opencv/modules/contrib/src/facerec.cpp, line 305
210     terminate called after throwing an instance of 'cv::Exception'
211
212 Please note: The :ocv:class:`FaceRecognizer` does not store your training images, because this would be very memory intense and it's not the responsibility of te :ocv:class:`FaceRecognizer` to do so. The caller is responsible for maintaining the dataset, he want to work with.
213
214 FaceRecognizer::predict
215 -----------------------
216
217 .. ocv:function:: int FaceRecognizer::predict( InputArray src ) const = 0
218 .. ocv:function:: void FaceRecognizer::predict( InputArray src, int & label, double & confidence ) const = 0
219
220     Predicts a label and associated confidence (e.g. distance) for a given input image.
221
222     :param src: Sample image to get a prediction from.
223     :param label: The predicted label for the given image.
224     :param confidence: Associated confidence (e.g. distance) for the predicted label.
225
226 The suffix ``const`` means that prediction does not affect the internal model
227 state, so the method can be safely called from within different threads.
228
229 The following example shows how to get a prediction from a trained model:
230
231 .. code-block:: cpp
232
233     using namespace cv;
234     // Do your initialization here (create the cv::FaceRecognizer model) ...
235     // ...
236     // Read in a sample image:
237     Mat img = imread("person1/3.jpg", CV_LOAD_IMAGE_GRAYSCALE);
238     // And get a prediction from the cv::FaceRecognizer:
239     int predicted = model->predict(img);
240
241 Or to get a prediction and the associated confidence (e.g. distance):
242
243 .. code-block:: cpp
244
245     using namespace cv;
246     // Do your initialization here (create the cv::FaceRecognizer model) ...
247     // ...
248     Mat img = imread("person1/3.jpg", CV_LOAD_IMAGE_GRAYSCALE);
249     // Some variables for the predicted label and associated confidence (e.g. distance):
250     int predicted_label = -1;
251     double predicted_confidence = 0.0;
252     // Get the prediction and associated confidence from the model
253     model->predict(img, predicted_label, predicted_confidence);
254
255 FaceRecognizer::save
256 --------------------
257
258 Saves a :ocv:class:`FaceRecognizer` and its model state.
259
260 .. ocv:function:: void FaceRecognizer::save(const string& filename) const
261
262     Saves this model to a given filename, either as XML or YAML.
263
264     :param filename: The filename to store this :ocv:class:`FaceRecognizer` to (either XML/YAML).
265
266 .. ocv:function:: void FaceRecognizer::save(FileStorage& fs) const
267
268     Saves this model to a given :ocv:class:`FileStorage`.
269
270     :param fs: The :ocv:class:`FileStorage` to store this :ocv:class:`FaceRecognizer` to.
271
272
273 Every :ocv:class:`FaceRecognizer` overwrites ``FaceRecognizer::save(FileStorage& fs)``
274 to save the internal model state. ``FaceRecognizer::save(const string& filename)`` saves
275 the state of a model to the given filename.
276
277 The suffix ``const`` means that prediction does not affect the internal model
278 state, so the method can be safely called from within different threads.
279
280 FaceRecognizer::load
281 --------------------
282
283 Loads a :ocv:class:`FaceRecognizer` and its model state.
284
285 .. ocv:function:: void FaceRecognizer::load( const string& filename )
286 .. ocv:function:: void FaceRecognizer::load( const FileStorage& fs ) = 0
287
288 Loads a persisted model and state from a given XML or YAML file . Every
289 :ocv:class:`FaceRecognizer` has to overwrite ``FaceRecognizer::load(FileStorage& fs)``
290 to enable loading the model state. ``FaceRecognizer::load(FileStorage& fs)`` in
291 turn gets called by ``FaceRecognizer::load(const string& filename)``, to ease
292 saving a model.
293
294 createEigenFaceRecognizer
295 -------------------------
296
297 .. ocv:function:: Ptr<FaceRecognizer> createEigenFaceRecognizer(int num_components = 0, double threshold = DBL_MAX)
298
299     :param num_components: The number of components (read: Eigenfaces) kept for this Prinicpal Component Analysis. As a hint: There's no rule how many components (read: Eigenfaces) should be kept for good reconstruction capabilities. It is based on your input data, so experiment with the number. Keeping 80 components should almost always be sufficient.
300
301     :param threshold: The threshold applied in the prediciton.
302
303 Notes:
304 ++++++
305
306 * Training and prediction must be done on grayscale images, use :ocv:func:`cvtColor` to convert between the color spaces.
307 * **THE EIGENFACES METHOD MAKES THE ASSUMPTION, THAT THE TRAINING AND TEST IMAGES ARE OF EQUAL SIZE.** (caps-lock, because I got so many mails asking for this). You have to make sure your input data has the correct shape, else a meaningful exception is thrown. Use :ocv:func:`resize` to resize the images.
308 * This model does not support updating.
309
310 Model internal data:
311 ++++++++++++++++++++
312
313 * ``num_components`` see :ocv:func:`createEigenFaceRecognizer`.
314 * ``threshold`` see :ocv:func:`createEigenFaceRecognizer`.
315 * ``eigenvalues`` The eigenvalues for this Principal Component Analysis (ordered descending).
316 * ``eigenvectors`` The eigenvectors for this Principal Component Analysis (ordered by their eigenvalue).
317 * ``mean`` The sample mean calculated from the training data.
318 * ``projections`` The projections of the training data.
319 * ``labels`` The threshold applied in the prediction. If the distance to the nearest neighbor is larger than the threshold, this method returns -1.
320
321 createFisherFaceRecognizer
322 --------------------------
323
324 .. ocv:function:: Ptr<FaceRecognizer> createFisherFaceRecognizer(int num_components = 0, double threshold = DBL_MAX)
325
326     :param num_components: The number of components (read: Fisherfaces) kept for this Linear Discriminant Analysis with the Fisherfaces criterion. It's useful to keep all components, that means the number of your classes ``c`` (read: subjects, persons you want to recognize). If you leave this at the default (``0``) or set it to a value  less-equal ``0`` or greater ``(c-1)``, it will be set to the correct number ``(c-1)`` automatically.
327
328     :param threshold: The threshold applied in the prediction. If the distance to the nearest neighbor is larger than the threshold, this method returns -1.
329
330 Notes:
331 ++++++
332
333 * Training and prediction must be done on grayscale images, use :ocv:func:`cvtColor` to convert between the color spaces.
334 * **THE FISHERFACES METHOD MAKES THE ASSUMPTION, THAT THE TRAINING AND TEST IMAGES ARE OF EQUAL SIZE.** (caps-lock, because I got so many mails asking for this). You have to make sure your input data has the correct shape, else a meaningful exception is thrown. Use :ocv:func:`resize` to resize the images.
335 * This model does not support updating.
336
337 Model internal data:
338 ++++++++++++++++++++
339
340 * ``num_components`` see :ocv:func:`createFisherFaceRecognizer`.
341 * ``threshold`` see :ocv:func:`createFisherFaceRecognizer`.
342 * ``eigenvalues`` The eigenvalues for this Linear Discriminant Analysis (ordered descending).
343 * ``eigenvectors`` The eigenvectors for this Linear Discriminant Analysis (ordered by their eigenvalue).
344 * ``mean`` The sample mean calculated from the training data.
345 * ``projections`` The projections of the training data.
346 * ``labels`` The labels corresponding to the projections.
347
348
349 createLBPHFaceRecognizer
350 -------------------------
351
352 .. ocv:function:: Ptr<FaceRecognizer> createLBPHFaceRecognizer(int radius=1, int neighbors=8, int grid_x=8, int grid_y=8, double threshold = DBL_MAX)
353
354     :param radius: The radius used for building the Circular Local Binary Pattern. The greater the radius, the
355     :param neighbors: The number of sample points to build a Circular Local Binary Pattern from. An appropriate value is to use `` 8`` sample points. Keep in mind: the more sample points you include, the higher the computational cost.
356     :param grid_x: The number of cells in the horizontal direction, ``8`` is a common value used in publications. The more cells, the finer the grid, the higher the dimensionality of the resulting feature vector.
357     :param grid_y: The number of cells in the vertical direction, ``8`` is a common value used in publications. The more cells, the finer the grid, the higher the dimensionality of the resulting feature vector.
358     :param threshold: The threshold applied in the prediction. If the distance to the nearest neighbor is larger than the threshold, this method returns -1.
359
360 Notes:
361 ++++++
362
363 * The Circular Local Binary Patterns (used in training and prediction) expect the data given as grayscale images, use :ocv:func:`cvtColor` to convert between the color spaces.
364 * This model supports updating.
365
366 Model internal data:
367 ++++++++++++++++++++
368
369 * ``radius`` see :ocv:func:`createLBPHFaceRecognizer`.
370 * ``neighbors`` see :ocv:func:`createLBPHFaceRecognizer`.
371 * ``grid_x`` see :ocv:func:`createLBPHFaceRecognizer`.
372 * ``grid_y`` see :ocv:func:`createLBPHFaceRecognizer`.
373 * ``threshold`` see :ocv:func:`createLBPHFaceRecognizer`.
374 * ``histograms`` Local Binary Patterns Histograms calculated from the given training data (empty if none was given).
375 * ``labels`` Labels corresponding to the calculated Local Binary Patterns Histograms.