face.hpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. /*
  2. By downloading, copying, installing or using the software you agree to this
  3. license. If you do not agree to this license, do not download, install,
  4. copy or use the software.
  5. License Agreement
  6. For Open Source Computer Vision Library
  7. (3-clause BSD License)
  8. Copyright (C) 2013, OpenCV Foundation, all rights reserved.
  9. Third party copyrights are property of their respective owners.
  10. Redistribution and use in source and binary forms, with or without modification,
  11. are permitted provided that the following conditions are met:
  12. * Redistributions of source code must retain the above copyright notice,
  13. this list of conditions and the following disclaimer.
  14. * Redistributions in binary form must reproduce the above copyright notice,
  15. this list of conditions and the following disclaimer in the documentation
  16. and/or other materials provided with the distribution.
  17. * Neither the names of the copyright holders nor the names of the contributors
  18. may be used to endorse or promote products derived from this software
  19. without specific prior written permission.
  20. This software is provided by the copyright holders and contributors "as is" and
  21. any express or implied warranties, including, but not limited to, the implied
  22. warranties of merchantability and fitness for a particular purpose are
  23. disclaimed. In no event shall copyright holders or contributors be liable for
  24. any direct, indirect, incidental, special, exemplary, or consequential damages
  25. (including, but not limited to, procurement of substitute goods or services;
  26. loss of use, data, or profits; or business interruption) however caused
  27. and on any theory of liability, whether in contract, strict liability,
  28. or tort (including negligence or otherwise) arising in any way out of
  29. the use of this software, even if advised of the possibility of such damage.
  30. */
  31. #ifndef __OPENCV_FACE_HPP__
  32. #define __OPENCV_FACE_HPP__
  33. /**
  34. @defgroup face Face Analysis
  35. - @ref face_changelog
  36. - @ref tutorial_face_main
  37. */
  38. #include "opencv2/core.hpp"
  39. #include "face/predict_collector.hpp"
  40. #include <map>
  41. namespace cv { namespace face {
  42. //! @addtogroup face
  43. //! @{
  44. /** @brief Abstract base class for all face recognition models
  45. All face recognition models in OpenCV are derived from the abstract base class FaceRecognizer, which
  46. provides a unified access to all face recongition algorithms in OpenCV.
  47. ### Description
  48. I'll go a bit more into detail explaining FaceRecognizer, because it doesn't look like a powerful
  49. interface at first sight. But: Every FaceRecognizer is an Algorithm, so you can easily get/set all
  50. model internals (if allowed by the implementation). Algorithm is a relatively new OpenCV concept,
  51. which is available since the 2.4 release. I suggest you take a look at its description.
  52. Algorithm provides the following features for all derived classes:
  53. - So called "virtual constructor". That is, each Algorithm derivative is registered at program
  54. start and you can get the list of registered algorithms and create instance of a particular
  55. algorithm by its name (see Algorithm::create). If you plan to add your own algorithms, it is
  56. good practice to add a unique prefix to your algorithms to distinguish them from other
  57. algorithms.
  58. - Setting/Retrieving algorithm parameters by name. If you used video capturing functionality from
  59. OpenCV highgui module, you are probably familar with cv::cvSetCaptureProperty,
  60. ocvcvGetCaptureProperty, VideoCapture::set and VideoCapture::get. Algorithm provides similar
  61. method where instead of integer id's you specify the parameter names as text Strings. See
  62. Algorithm::set and Algorithm::get for details.
  63. - Reading and writing parameters from/to XML or YAML files. Every Algorithm derivative can store
  64. all its parameters and then read them back. There is no need to re-implement it each time.
  65. Moreover every FaceRecognizer supports the:
  66. - **Training** of a FaceRecognizer with FaceRecognizer::train on a given set of images (your face
  67. database!).
  68. - **Prediction** of a given sample image, that means a face. The image is given as a Mat.
  69. - **Loading/Saving** the model state from/to a given XML or YAML.
  70. - **Setting/Getting labels info**, that is stored as a string. String labels info is useful for
  71. keeping names of the recognized people.
  72. @note When using the FaceRecognizer interface in combination with Python, please stick to Python 2.
  73. Some underlying scripts like create_csv will not work in other versions, like Python 3. Setting the
  74. Thresholds +++++++++++++++++++++++
  75. Sometimes you run into the situation, when you want to apply a threshold on the prediction. A common
  76. scenario in face recognition is to tell, whether a face belongs to the training dataset or if it is
  77. unknown. You might wonder, why there's no public API in FaceRecognizer to set the threshold for the
  78. prediction, but rest assured: It's supported. It just means there's no generic way in an abstract
  79. class to provide an interface for setting/getting the thresholds of *every possible* FaceRecognizer
  80. algorithm. The appropriate place to set the thresholds is in the constructor of the specific
  81. FaceRecognizer and since every FaceRecognizer is a Algorithm (see above), you can get/set the
  82. thresholds at runtime!
  83. Here is an example of setting a threshold for the Eigenfaces method, when creating the model:
  84. @code
  85. // Let's say we want to keep 10 Eigenfaces and have a threshold value of 10.0
  86. int num_components = 10;
  87. double threshold = 10.0;
  88. // Then if you want to have a cv::FaceRecognizer with a confidence threshold,
  89. // create the concrete implementation with the appropriate parameters:
  90. Ptr<FaceRecognizer> model = EigenFaceRecognizer::create(num_components, threshold);
  91. @endcode
  92. Sometimes it's impossible to train the model, just to experiment with threshold values. Thanks to
  93. Algorithm it's possible to set internal model thresholds during runtime. Let's see how we would
  94. set/get the prediction for the Eigenface model, we've created above:
  95. @code
  96. // The following line reads the threshold from the Eigenfaces model:
  97. double current_threshold = model->getDouble("threshold");
  98. // And this line sets the threshold to 0.0:
  99. model->set("threshold", 0.0);
  100. @endcode
  101. If you've set the threshold to 0.0 as we did above, then:
  102. @code
  103. //
  104. Mat img = imread("person1/3.jpg", IMREAD_GRAYSCALE);
  105. // Get a prediction from the model. Note: We've set a threshold of 0.0 above,
  106. // since the distance is almost always larger than 0.0, you'll get -1 as
  107. // label, which indicates, this face is unknown
  108. int predicted_label = model->predict(img);
  109. // ...
  110. @endcode
  111. is going to yield -1 as predicted label, which states this face is unknown.
  112. ### Getting the name of a FaceRecognizer
  113. Since every FaceRecognizer is a Algorithm, you can use Algorithm::name to get the name of a
  114. FaceRecognizer:
  115. @code
  116. // Create a FaceRecognizer:
  117. Ptr<FaceRecognizer> model = EigenFaceRecognizer::create();
  118. // And here's how to get its name:
  119. String name = model->name();
  120. @endcode
  121. */
  122. class CV_EXPORTS_W FaceRecognizer : public Algorithm
  123. {
  124. public:
  125. /** @brief Trains a FaceRecognizer with given data and associated labels.
  126. @param src The training images, that means the faces you want to learn. The data has to be
  127. given as a vector\<Mat\>.
  128. @param labels The labels corresponding to the images have to be given either as a vector\<int\>
  129. or a Mat of type CV_32SC1.
  130. The following source code snippet shows you how to learn a Fisherfaces model on a given set of
  131. images. The images are read with imread and pushed into a std::vector\<Mat\>. The labels of each
  132. image are stored within a std::vector\<int\> (you could also use a Mat of type CV_32SC1). Think of
  133. the label as the subject (the person) this image belongs to, so same subjects (persons) should have
  134. the same label. For the available FaceRecognizer you don't have to pay any attention to the order of
  135. the labels, just make sure same persons have the same label:
  136. @code
  137. // holds images and labels
  138. vector<Mat> images;
  139. vector<int> labels;
  140. // using Mat of type CV_32SC1
  141. // Mat labels(number_of_samples, 1, CV_32SC1);
  142. // images for first person
  143. images.push_back(imread("person0/0.jpg", IMREAD_GRAYSCALE)); labels.push_back(0);
  144. images.push_back(imread("person0/1.jpg", IMREAD_GRAYSCALE)); labels.push_back(0);
  145. images.push_back(imread("person0/2.jpg", IMREAD_GRAYSCALE)); labels.push_back(0);
  146. // images for second person
  147. images.push_back(imread("person1/0.jpg", IMREAD_GRAYSCALE)); labels.push_back(1);
  148. images.push_back(imread("person1/1.jpg", IMREAD_GRAYSCALE)); labels.push_back(1);
  149. images.push_back(imread("person1/2.jpg", IMREAD_GRAYSCALE)); labels.push_back(1);
  150. @endcode
  151. Now that you have read some images, we can create a new FaceRecognizer. In this example I'll create
  152. a Fisherfaces model and decide to keep all of the possible Fisherfaces:
  153. @code
  154. // Create a new Fisherfaces model and retain all available Fisherfaces,
  155. // this is the most common usage of this specific FaceRecognizer:
  156. //
  157. Ptr<FaceRecognizer> model = FisherFaceRecognizer::create();
  158. @endcode
  159. And finally train it on the given dataset (the face images and labels):
  160. @code
  161. // This is the common interface to train all of the available cv::FaceRecognizer
  162. // implementations:
  163. //
  164. model->train(images, labels);
  165. @endcode
  166. */
  167. CV_WRAP virtual void train(InputArrayOfArrays src, InputArray labels) = 0;
  168. /** @brief Updates a FaceRecognizer with given data and associated labels.
  169. @param src The training images, that means the faces you want to learn. The data has to be given
  170. as a vector\<Mat\>.
  171. @param labels The labels corresponding to the images have to be given either as a vector\<int\> or
  172. a Mat of type CV_32SC1.
  173. This method updates a (probably trained) FaceRecognizer, but only if the algorithm supports it. The
  174. Local Binary Patterns Histograms (LBPH) recognizer (see createLBPHFaceRecognizer) can be updated.
  175. For the Eigenfaces and Fisherfaces method, this is algorithmically not possible and you have to
  176. re-estimate the model with FaceRecognizer::train. In any case, a call to train empties the existing
  177. model and learns a new model, while update does not delete any model data.
  178. @code
  179. // Create a new LBPH model (it can be updated) and use the default parameters,
  180. // this is the most common usage of this specific FaceRecognizer:
  181. //
  182. Ptr<FaceRecognizer> model = LBPHFaceRecognizer::create();
  183. // This is the common interface to train all of the available cv::FaceRecognizer
  184. // implementations:
  185. //
  186. model->train(images, labels);
  187. // Some containers to hold new image:
  188. vector<Mat> newImages;
  189. vector<int> newLabels;
  190. // You should add some images to the containers:
  191. //
  192. // ...
  193. //
  194. // Now updating the model is as easy as calling:
  195. model->update(newImages,newLabels);
  196. // This will preserve the old model data and extend the existing model
  197. // with the new features extracted from newImages!
  198. @endcode
  199. Calling update on an Eigenfaces model (see EigenFaceRecognizer::create), which doesn't support
  200. updating, will throw an error similar to:
  201. @code
  202. 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
  203. terminate called after throwing an instance of 'cv::Exception'
  204. @endcode
  205. @note The FaceRecognizer does not store your training images, because this would be very
  206. memory intense and it's not the responsibility of te FaceRecognizer to do so. The caller is
  207. responsible for maintaining the dataset, he want to work with.
  208. */
  209. CV_WRAP virtual void update(InputArrayOfArrays src, InputArray labels);
  210. /** @overload */
  211. CV_WRAP_AS(predict_label) int predict(InputArray src) const;
  212. /** @brief Predicts a label and associated confidence (e.g. distance) for a given input image.
  213. @param src Sample image to get a prediction from.
  214. @param label The predicted label for the given image.
  215. @param confidence Associated confidence (e.g. distance) for the predicted label.
  216. The suffix const means that prediction does not affect the internal model state, so the method can
  217. be safely called from within different threads.
  218. The following example shows how to get a prediction from a trained model:
  219. @code
  220. using namespace cv;
  221. // Do your initialization here (create the cv::FaceRecognizer model) ...
  222. // ...
  223. // Read in a sample image:
  224. Mat img = imread("person1/3.jpg", IMREAD_GRAYSCALE);
  225. // And get a prediction from the cv::FaceRecognizer:
  226. int predicted = model->predict(img);
  227. @endcode
  228. Or to get a prediction and the associated confidence (e.g. distance):
  229. @code
  230. using namespace cv;
  231. // Do your initialization here (create the cv::FaceRecognizer model) ...
  232. // ...
  233. Mat img = imread("person1/3.jpg", IMREAD_GRAYSCALE);
  234. // Some variables for the predicted label and associated confidence (e.g. distance):
  235. int predicted_label = -1;
  236. double predicted_confidence = 0.0;
  237. // Get the prediction and associated confidence from the model
  238. model->predict(img, predicted_label, predicted_confidence);
  239. @endcode
  240. */
  241. CV_WRAP void predict(InputArray src, CV_OUT int &label, CV_OUT double &confidence) const;
  242. /** @brief - if implemented - send all result of prediction to collector that can be used for somehow custom result handling
  243. @param src Sample image to get a prediction from.
  244. @param collector User-defined collector object that accepts all results
  245. To implement this method u just have to do same internal cycle as in predict(InputArray src, CV_OUT int &label, CV_OUT double &confidence) but
  246. not try to get "best@ result, just resend it to caller side with given collector
  247. */
  248. CV_WRAP_AS(predict_collect) virtual void predict(InputArray src, Ptr<PredictCollector> collector) const = 0;
  249. /** @brief Saves a FaceRecognizer and its model state.
  250. Saves this model to a given filename, either as XML or YAML.
  251. @param filename The filename to store this FaceRecognizer to (either XML/YAML).
  252. Every FaceRecognizer overwrites FaceRecognizer::save(FileStorage& fs) to save the internal model
  253. state. FaceRecognizer::save(const String& filename) saves the state of a model to the given
  254. filename.
  255. The suffix const means that prediction does not affect the internal model state, so the method can
  256. be safely called from within different threads.
  257. */
  258. CV_WRAP virtual void write(const String& filename) const;
  259. /** @brief Loads a FaceRecognizer and its model state.
  260. Loads a persisted model and state from a given XML or YAML file . Every FaceRecognizer has to
  261. overwrite FaceRecognizer::load(FileStorage& fs) to enable loading the model state.
  262. FaceRecognizer::load(FileStorage& fs) in turn gets called by
  263. FaceRecognizer::load(const String& filename), to ease saving a model.
  264. */
  265. CV_WRAP virtual void read(const String& filename);
  266. /** @overload
  267. Saves this model to a given FileStorage.
  268. @param fs The FileStorage to store this FaceRecognizer to.
  269. */
  270. virtual void write(FileStorage& fs) const CV_OVERRIDE = 0;
  271. /** @overload */
  272. virtual void read(const FileNode& fn) CV_OVERRIDE = 0;
  273. /** @overload */
  274. virtual bool empty() const CV_OVERRIDE = 0;
  275. /** @brief Sets string info for the specified model's label.
  276. The string info is replaced by the provided value if it was set before for the specified label.
  277. */
  278. CV_WRAP virtual void setLabelInfo(int label, const String& strInfo);
  279. /** @brief Gets string information by label.
  280. If an unknown label id is provided or there is no label information associated with the specified
  281. label id the method returns an empty string.
  282. */
  283. CV_WRAP virtual String getLabelInfo(int label) const;
  284. /** @brief Gets vector of labels by string.
  285. The function searches for the labels containing the specified sub-string in the associated string
  286. info.
  287. */
  288. CV_WRAP virtual std::vector<int> getLabelsByString(const String& str) const;
  289. /** @brief threshold parameter accessor - required for default BestMinDist collector */
  290. virtual double getThreshold() const = 0;
  291. /** @brief Sets threshold of model */
  292. virtual void setThreshold(double val) = 0;
  293. protected:
  294. // Stored pairs "label id - string info"
  295. std::map<int, String> _labelsInfo;
  296. };
  297. //! @}
  298. }}
  299. #include "opencv2/face/facerec.hpp"
  300. #include "opencv2/face/facemark.hpp"
  301. #include "opencv2/face/facemark_train.hpp"
  302. #include "opencv2/face/facemarkLBF.hpp"
  303. #include "opencv2/face/facemarkAAM.hpp"
  304. #include "opencv2/face/face_alignment.hpp"
  305. #include "opencv2/face/mace.hpp"
  306. #endif // __OPENCV_FACE_HPP__