objdetect.hpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845
  1. /*M///////////////////////////////////////////////////////////////////////////////////////
  2. //
  3. // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
  4. //
  5. // By downloading, copying, installing or using the software you agree to this license.
  6. // If you do not agree to this license, do not download, install,
  7. // copy or use the software.
  8. //
  9. //
  10. // License Agreement
  11. // For Open Source Computer Vision Library
  12. //
  13. // Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
  14. // Copyright (C) 2009, Willow Garage Inc., all rights reserved.
  15. // Copyright (C) 2013, OpenCV Foundation, all rights reserved.
  16. // Third party copyrights are property of their respective owners.
  17. //
  18. // Redistribution and use in source and binary forms, with or without modification,
  19. // are permitted provided that the following conditions are met:
  20. //
  21. // * Redistribution's of source code must retain the above copyright notice,
  22. // this list of conditions and the following disclaimer.
  23. //
  24. // * Redistribution's in binary form must reproduce the above copyright notice,
  25. // this list of conditions and the following disclaimer in the documentation
  26. // and/or other materials provided with the distribution.
  27. //
  28. // * The name of the copyright holders may not be used to endorse or promote products
  29. // derived from this software without specific prior written permission.
  30. //
  31. // This software is provided by the copyright holders and contributors "as is" and
  32. // any express or implied warranties, including, but not limited to, the implied
  33. // warranties of merchantability and fitness for a particular purpose are disclaimed.
  34. // In no event shall the Intel Corporation or contributors be liable for any direct,
  35. // indirect, incidental, special, exemplary, or consequential damages
  36. // (including, but not limited to, procurement of substitute goods or services;
  37. // loss of use, data, or profits; or business interruption) however caused
  38. // and on any theory of liability, whether in contract, strict liability,
  39. // or tort (including negligence or otherwise) arising in any way out of
  40. // the use of this software, even if advised of the possibility of such damage.
  41. //
  42. //M*/
  43. #ifndef OPENCV_OBJDETECT_HPP
  44. #define OPENCV_OBJDETECT_HPP
  45. #include "opencv2/core.hpp"
  46. /**
  47. @defgroup objdetect Object Detection
  48. @{
  49. @defgroup objdetect_cascade_classifier Cascade Classifier for Object Detection
  50. The object detector described below has been initially proposed by Paul Viola @cite Viola01 and
  51. improved by Rainer Lienhart @cite Lienhart02 .
  52. First, a classifier (namely a *cascade of boosted classifiers working with haar-like features*) is
  53. trained with a few hundred sample views of a particular object (i.e., a face or a car), called
  54. positive examples, that are scaled to the same size (say, 20x20), and negative examples - arbitrary
  55. images of the same size.
  56. After a classifier is trained, it can be applied to a region of interest (of the same size as used
  57. during the training) in an input image. The classifier outputs a "1" if the region is likely to show
  58. the object (i.e., face/car), and "0" otherwise. To search for the object in the whole image one can
  59. move the search window across the image and check every location using the classifier. The
  60. classifier is designed so that it can be easily "resized" in order to be able to find the objects of
  61. interest at different sizes, which is more efficient than resizing the image itself. So, to find an
  62. object of an unknown size in the image the scan procedure should be done several times at different
  63. scales.
  64. The word "cascade" in the classifier name means that the resultant classifier consists of several
  65. simpler classifiers (*stages*) that are applied subsequently to a region of interest until at some
  66. stage the candidate is rejected or all the stages are passed. The word "boosted" means that the
  67. classifiers at every stage of the cascade are complex themselves and they are built out of basic
  68. classifiers using one of four different boosting techniques (weighted voting). Currently Discrete
  69. Adaboost, Real Adaboost, Gentle Adaboost and Logitboost are supported. The basic classifiers are
  70. decision-tree classifiers with at least 2 leaves. Haar-like features are the input to the basic
  71. classifiers, and are calculated as described below. The current algorithm uses the following
  72. Haar-like features:
  73. ![image](pics/haarfeatures.png)
  74. The feature used in a particular classifier is specified by its shape (1a, 2b etc.), position within
  75. the region of interest and the scale (this scale is not the same as the scale used at the detection
  76. stage, though these two scales are multiplied). For example, in the case of the third line feature
  77. (2c) the response is calculated as the difference between the sum of image pixels under the
  78. rectangle covering the whole feature (including the two white stripes and the black stripe in the
  79. middle) and the sum of the image pixels under the black stripe multiplied by 3 in order to
  80. compensate for the differences in the size of areas. The sums of pixel values over a rectangular
  81. regions are calculated rapidly using integral images (see below and the integral description).
  82. Check @ref tutorial_cascade_classifier "the corresponding tutorial" for more details.
  83. The following reference is for the detection part only. There is a separate application called
  84. opencv_traincascade that can train a cascade of boosted classifiers from a set of samples.
  85. @note In the new C++ interface it is also possible to use LBP (local binary pattern) features in
  86. addition to Haar-like features. .. [Viola01] Paul Viola and Michael J. Jones. Rapid Object Detection
  87. using a Boosted Cascade of Simple Features. IEEE CVPR, 2001. The paper is available online at
  88. <https://github.com/SvHey/thesis/blob/master/Literature/ObjectDetection/violaJones_CVPR2001.pdf>
  89. @defgroup objdetect_hog HOG (Histogram of Oriented Gradients) descriptor and object detector
  90. @defgroup objdetect_qrcode QRCode detection and encoding
  91. @defgroup objdetect_dnn_face DNN-based face detection and recognition
  92. Check @ref tutorial_dnn_face "the corresponding tutorial" for more details.
  93. @defgroup objdetect_common Common functions and classes
  94. @}
  95. */
  96. typedef struct CvHaarClassifierCascade CvHaarClassifierCascade;
  97. namespace cv
  98. {
  99. //! @addtogroup objdetect_common
  100. //! @{
  101. ///////////////////////////// Object Detection ////////////////////////////
  102. /** @brief This class is used for grouping object candidates detected by Cascade Classifier, HOG etc.
  103. instance of the class is to be passed to cv::partition
  104. */
  105. class CV_EXPORTS SimilarRects
  106. {
  107. public:
  108. SimilarRects(double _eps) : eps(_eps) {}
  109. inline bool operator()(const Rect& r1, const Rect& r2) const
  110. {
  111. double delta = eps * ((std::min)(r1.width, r2.width) + (std::min)(r1.height, r2.height)) * 0.5;
  112. return std::abs(r1.x - r2.x) <= delta &&
  113. std::abs(r1.y - r2.y) <= delta &&
  114. std::abs(r1.x + r1.width - r2.x - r2.width) <= delta &&
  115. std::abs(r1.y + r1.height - r2.y - r2.height) <= delta;
  116. }
  117. double eps;
  118. };
  119. /** @brief Groups the object candidate rectangles.
  120. @param rectList Input/output vector of rectangles. Output vector includes retained and grouped
  121. rectangles. (The Python list is not modified in place.)
  122. @param groupThreshold Minimum possible number of rectangles minus 1. The threshold is used in a
  123. group of rectangles to retain it.
  124. @param eps Relative difference between sides of the rectangles to merge them into a group.
  125. The function is a wrapper for the generic function partition . It clusters all the input rectangles
  126. using the rectangle equivalence criteria that combines rectangles with similar sizes and similar
  127. locations. The similarity is defined by eps. When eps=0 , no clustering is done at all. If
  128. \f$\texttt{eps}\rightarrow +\inf\f$ , all the rectangles are put in one cluster. Then, the small
  129. clusters containing less than or equal to groupThreshold rectangles are rejected. In each other
  130. cluster, the average rectangle is computed and put into the output rectangle list.
  131. */
  132. CV_EXPORTS void groupRectangles(std::vector<Rect>& rectList, int groupThreshold, double eps = 0.2);
  133. /** @overload */
  134. CV_EXPORTS_W void groupRectangles(CV_IN_OUT std::vector<Rect>& rectList, CV_OUT std::vector<int>& weights,
  135. int groupThreshold, double eps = 0.2);
  136. /** @overload */
  137. CV_EXPORTS void groupRectangles(std::vector<Rect>& rectList, int groupThreshold,
  138. double eps, std::vector<int>* weights, std::vector<double>* levelWeights );
  139. /** @overload */
  140. CV_EXPORTS void groupRectangles(std::vector<Rect>& rectList, std::vector<int>& rejectLevels,
  141. std::vector<double>& levelWeights, int groupThreshold, double eps = 0.2);
  142. /** @overload */
  143. CV_EXPORTS void groupRectangles_meanshift(std::vector<Rect>& rectList, std::vector<double>& foundWeights,
  144. std::vector<double>& foundScales,
  145. double detectThreshold = 0.0, Size winDetSize = Size(64, 128));
  146. //! @}
  147. //! @addtogroup objdetect_cascade_classifier
  148. //! @{
  149. template<> struct DefaultDeleter<CvHaarClassifierCascade>{ CV_EXPORTS void operator ()(CvHaarClassifierCascade* obj) const; };
  150. enum { CASCADE_DO_CANNY_PRUNING = 1,
  151. CASCADE_SCALE_IMAGE = 2,
  152. CASCADE_FIND_BIGGEST_OBJECT = 4,
  153. CASCADE_DO_ROUGH_SEARCH = 8
  154. };
  155. class CV_EXPORTS_W BaseCascadeClassifier : public Algorithm
  156. {
  157. public:
  158. virtual ~BaseCascadeClassifier();
  159. virtual bool empty() const CV_OVERRIDE = 0;
  160. virtual bool load( const String& filename ) = 0;
  161. virtual void detectMultiScale( InputArray image,
  162. CV_OUT std::vector<Rect>& objects,
  163. double scaleFactor,
  164. int minNeighbors, int flags,
  165. Size minSize, Size maxSize ) = 0;
  166. virtual void detectMultiScale( InputArray image,
  167. CV_OUT std::vector<Rect>& objects,
  168. CV_OUT std::vector<int>& numDetections,
  169. double scaleFactor,
  170. int minNeighbors, int flags,
  171. Size minSize, Size maxSize ) = 0;
  172. virtual void detectMultiScale( InputArray image,
  173. CV_OUT std::vector<Rect>& objects,
  174. CV_OUT std::vector<int>& rejectLevels,
  175. CV_OUT std::vector<double>& levelWeights,
  176. double scaleFactor,
  177. int minNeighbors, int flags,
  178. Size minSize, Size maxSize,
  179. bool outputRejectLevels ) = 0;
  180. virtual bool isOldFormatCascade() const = 0;
  181. virtual Size getOriginalWindowSize() const = 0;
  182. virtual int getFeatureType() const = 0;
  183. virtual void* getOldCascade() = 0;
  184. class CV_EXPORTS MaskGenerator
  185. {
  186. public:
  187. virtual ~MaskGenerator() {}
  188. virtual Mat generateMask(const Mat& src)=0;
  189. virtual void initializeMask(const Mat& /*src*/) { }
  190. };
  191. virtual void setMaskGenerator(const Ptr<MaskGenerator>& maskGenerator) = 0;
  192. virtual Ptr<MaskGenerator> getMaskGenerator() = 0;
  193. };
  194. /** @example samples/cpp/facedetect.cpp
  195. This program demonstrates usage of the Cascade classifier class
  196. \image html Cascade_Classifier_Tutorial_Result_Haar.jpg "Sample screenshot" width=321 height=254
  197. */
  198. /** @brief Cascade classifier class for object detection.
  199. */
  200. class CV_EXPORTS_W CascadeClassifier
  201. {
  202. public:
  203. CV_WRAP CascadeClassifier();
  204. /** @brief Loads a classifier from a file.
  205. @param filename Name of the file from which the classifier is loaded.
  206. */
  207. CV_WRAP CascadeClassifier(const String& filename);
  208. ~CascadeClassifier();
  209. /** @brief Checks whether the classifier has been loaded.
  210. */
  211. CV_WRAP bool empty() const;
  212. /** @brief Loads a classifier from a file.
  213. @param filename Name of the file from which the classifier is loaded. The file may contain an old
  214. HAAR classifier trained by the haartraining application or a new cascade classifier trained by the
  215. traincascade application.
  216. */
  217. CV_WRAP bool load( const String& filename );
  218. /** @brief Reads a classifier from a FileStorage node.
  219. @note The file may contain a new cascade classifier (trained by the traincascade application) only.
  220. */
  221. CV_WRAP bool read( const FileNode& node );
  222. /** @brief Detects objects of different sizes in the input image. The detected objects are returned as a list
  223. of rectangles.
  224. @param image Matrix of the type CV_8U containing an image where objects are detected.
  225. @param objects Vector of rectangles where each rectangle contains the detected object, the
  226. rectangles may be partially outside the original image.
  227. @param scaleFactor Parameter specifying how much the image size is reduced at each image scale.
  228. @param minNeighbors Parameter specifying how many neighbors each candidate rectangle should have
  229. to retain it.
  230. @param flags Parameter with the same meaning for an old cascade as in the function
  231. cvHaarDetectObjects. It is not used for a new cascade.
  232. @param minSize Minimum possible object size. Objects smaller than that are ignored.
  233. @param maxSize Maximum possible object size. Objects larger than that are ignored. If `maxSize == minSize` model is evaluated on single scale.
  234. */
  235. CV_WRAP void detectMultiScale( InputArray image,
  236. CV_OUT std::vector<Rect>& objects,
  237. double scaleFactor = 1.1,
  238. int minNeighbors = 3, int flags = 0,
  239. Size minSize = Size(),
  240. Size maxSize = Size() );
  241. /** @overload
  242. @param image Matrix of the type CV_8U containing an image where objects are detected.
  243. @param objects Vector of rectangles where each rectangle contains the detected object, the
  244. rectangles may be partially outside the original image.
  245. @param numDetections Vector of detection numbers for the corresponding objects. An object's number
  246. of detections is the number of neighboring positively classified rectangles that were joined
  247. together to form the object.
  248. @param scaleFactor Parameter specifying how much the image size is reduced at each image scale.
  249. @param minNeighbors Parameter specifying how many neighbors each candidate rectangle should have
  250. to retain it.
  251. @param flags Parameter with the same meaning for an old cascade as in the function
  252. cvHaarDetectObjects. It is not used for a new cascade.
  253. @param minSize Minimum possible object size. Objects smaller than that are ignored.
  254. @param maxSize Maximum possible object size. Objects larger than that are ignored. If `maxSize == minSize` model is evaluated on single scale.
  255. */
  256. CV_WRAP_AS(detectMultiScale2) void detectMultiScale( InputArray image,
  257. CV_OUT std::vector<Rect>& objects,
  258. CV_OUT std::vector<int>& numDetections,
  259. double scaleFactor=1.1,
  260. int minNeighbors=3, int flags=0,
  261. Size minSize=Size(),
  262. Size maxSize=Size() );
  263. /** @overload
  264. This function allows you to retrieve the final stage decision certainty of classification.
  265. For this, one needs to set `outputRejectLevels` on true and provide the `rejectLevels` and `levelWeights` parameter.
  266. For each resulting detection, `levelWeights` will then contain the certainty of classification at the final stage.
  267. This value can then be used to separate strong from weaker classifications.
  268. A code sample on how to use it efficiently can be found below:
  269. @code
  270. Mat img;
  271. vector<double> weights;
  272. vector<int> levels;
  273. vector<Rect> detections;
  274. CascadeClassifier model("/path/to/your/model.xml");
  275. model.detectMultiScale(img, detections, levels, weights, 1.1, 3, 0, Size(), Size(), true);
  276. cerr << "Detection " << detections[0] << " with weight " << weights[0] << endl;
  277. @endcode
  278. */
  279. CV_WRAP_AS(detectMultiScale3) void detectMultiScale( InputArray image,
  280. CV_OUT std::vector<Rect>& objects,
  281. CV_OUT std::vector<int>& rejectLevels,
  282. CV_OUT std::vector<double>& levelWeights,
  283. double scaleFactor = 1.1,
  284. int minNeighbors = 3, int flags = 0,
  285. Size minSize = Size(),
  286. Size maxSize = Size(),
  287. bool outputRejectLevels = false );
  288. CV_WRAP bool isOldFormatCascade() const;
  289. CV_WRAP Size getOriginalWindowSize() const;
  290. CV_WRAP int getFeatureType() const;
  291. void* getOldCascade();
  292. CV_WRAP static bool convert(const String& oldcascade, const String& newcascade);
  293. void setMaskGenerator(const Ptr<BaseCascadeClassifier::MaskGenerator>& maskGenerator);
  294. Ptr<BaseCascadeClassifier::MaskGenerator> getMaskGenerator();
  295. Ptr<BaseCascadeClassifier> cc;
  296. };
  297. CV_EXPORTS Ptr<BaseCascadeClassifier::MaskGenerator> createFaceDetectionMaskGenerator();
  298. //! @}
  299. //! @addtogroup objdetect_hog
  300. //! @{
  301. //////////////// HOG (Histogram-of-Oriented-Gradients) Descriptor and Object Detector //////////////
  302. //! struct for detection region of interest (ROI)
  303. struct DetectionROI
  304. {
  305. //! scale(size) of the bounding box
  306. double scale;
  307. //! set of requested locations to be evaluated
  308. std::vector<cv::Point> locations;
  309. //! vector that will contain confidence values for each location
  310. std::vector<double> confidences;
  311. };
  312. /**@brief Implementation of HOG (Histogram of Oriented Gradients) descriptor and object detector.
  313. the HOG descriptor algorithm introduced by Navneet Dalal and Bill Triggs @cite Dalal2005 .
  314. useful links:
  315. https://hal.inria.fr/inria-00548512/document/
  316. https://en.wikipedia.org/wiki/Histogram_of_oriented_gradients
  317. https://software.intel.com/en-us/ipp-dev-reference-histogram-of-oriented-gradients-hog-descriptor
  318. http://www.learnopencv.com/histogram-of-oriented-gradients
  319. http://www.learnopencv.com/handwritten-digits-classification-an-opencv-c-python-tutorial
  320. */
  321. struct CV_EXPORTS_W HOGDescriptor
  322. {
  323. public:
  324. enum HistogramNormType { L2Hys = 0 //!< Default histogramNormType
  325. };
  326. enum { DEFAULT_NLEVELS = 64 //!< Default nlevels value.
  327. };
  328. enum DescriptorStorageFormat { DESCR_FORMAT_COL_BY_COL, DESCR_FORMAT_ROW_BY_ROW };
  329. /**@brief Creates the HOG descriptor and detector with default params.
  330. aqual to HOGDescriptor(Size(64,128), Size(16,16), Size(8,8), Size(8,8), 9 )
  331. */
  332. CV_WRAP HOGDescriptor() : winSize(64,128), blockSize(16,16), blockStride(8,8),
  333. cellSize(8,8), nbins(9), derivAperture(1), winSigma(-1),
  334. histogramNormType(HOGDescriptor::L2Hys), L2HysThreshold(0.2), gammaCorrection(true),
  335. free_coef(-1.f), nlevels(HOGDescriptor::DEFAULT_NLEVELS), signedGradient(false)
  336. {}
  337. /** @overload
  338. @param _winSize sets winSize with given value.
  339. @param _blockSize sets blockSize with given value.
  340. @param _blockStride sets blockStride with given value.
  341. @param _cellSize sets cellSize with given value.
  342. @param _nbins sets nbins with given value.
  343. @param _derivAperture sets derivAperture with given value.
  344. @param _winSigma sets winSigma with given value.
  345. @param _histogramNormType sets histogramNormType with given value.
  346. @param _L2HysThreshold sets L2HysThreshold with given value.
  347. @param _gammaCorrection sets gammaCorrection with given value.
  348. @param _nlevels sets nlevels with given value.
  349. @param _signedGradient sets signedGradient with given value.
  350. */
  351. CV_WRAP HOGDescriptor(Size _winSize, Size _blockSize, Size _blockStride,
  352. Size _cellSize, int _nbins, int _derivAperture=1, double _winSigma=-1,
  353. HOGDescriptor::HistogramNormType _histogramNormType=HOGDescriptor::L2Hys,
  354. double _L2HysThreshold=0.2, bool _gammaCorrection=false,
  355. int _nlevels=HOGDescriptor::DEFAULT_NLEVELS, bool _signedGradient=false)
  356. : winSize(_winSize), blockSize(_blockSize), blockStride(_blockStride), cellSize(_cellSize),
  357. nbins(_nbins), derivAperture(_derivAperture), winSigma(_winSigma),
  358. histogramNormType(_histogramNormType), L2HysThreshold(_L2HysThreshold),
  359. gammaCorrection(_gammaCorrection), free_coef(-1.f), nlevels(_nlevels), signedGradient(_signedGradient)
  360. {}
  361. /** @overload
  362. @param filename The file name containing HOGDescriptor properties and coefficients for the linear SVM classifier.
  363. */
  364. CV_WRAP HOGDescriptor(const String& filename)
  365. {
  366. load(filename);
  367. }
  368. /** @overload
  369. @param d the HOGDescriptor which cloned to create a new one.
  370. */
  371. HOGDescriptor(const HOGDescriptor& d)
  372. {
  373. d.copyTo(*this);
  374. }
  375. /**@brief Default destructor.
  376. */
  377. virtual ~HOGDescriptor() {}
  378. /**@brief Returns the number of coefficients required for the classification.
  379. */
  380. CV_WRAP size_t getDescriptorSize() const;
  381. /** @brief Checks if detector size equal to descriptor size.
  382. */
  383. CV_WRAP bool checkDetectorSize() const;
  384. /** @brief Returns winSigma value
  385. */
  386. CV_WRAP double getWinSigma() const;
  387. /**@example samples/cpp/peopledetect.cpp
  388. */
  389. /**@brief Sets coefficients for the linear SVM classifier.
  390. @param svmdetector coefficients for the linear SVM classifier.
  391. */
  392. CV_WRAP virtual void setSVMDetector(InputArray svmdetector);
  393. /** @brief Reads HOGDescriptor parameters from a cv::FileNode.
  394. @param fn File node
  395. */
  396. virtual bool read(FileNode& fn);
  397. /** @brief Stores HOGDescriptor parameters in a cv::FileStorage.
  398. @param fs File storage
  399. @param objname Object name
  400. */
  401. virtual void write(FileStorage& fs, const String& objname) const;
  402. /** @brief loads HOGDescriptor parameters and coefficients for the linear SVM classifier from a file.
  403. @param filename Path of the file to read.
  404. @param objname The optional name of the node to read (if empty, the first top-level node will be used).
  405. */
  406. CV_WRAP virtual bool load(const String& filename, const String& objname = String());
  407. /** @brief saves HOGDescriptor parameters and coefficients for the linear SVM classifier to a file
  408. @param filename File name
  409. @param objname Object name
  410. */
  411. CV_WRAP virtual void save(const String& filename, const String& objname = String()) const;
  412. /** @brief clones the HOGDescriptor
  413. @param c cloned HOGDescriptor
  414. */
  415. virtual void copyTo(HOGDescriptor& c) const;
  416. /**@example samples/cpp/train_HOG.cpp
  417. */
  418. /** @brief Computes HOG descriptors of given image.
  419. @param img Matrix of the type CV_8U containing an image where HOG features will be calculated.
  420. @param descriptors Matrix of the type CV_32F
  421. @param winStride Window stride. It must be a multiple of block stride.
  422. @param padding Padding
  423. @param locations Vector of Point
  424. */
  425. CV_WRAP virtual void compute(InputArray img,
  426. CV_OUT std::vector<float>& descriptors,
  427. Size winStride = Size(), Size padding = Size(),
  428. const std::vector<Point>& locations = std::vector<Point>()) const;
  429. /** @brief Performs object detection without a multi-scale window.
  430. @param img Matrix of the type CV_8U or CV_8UC3 containing an image where objects are detected.
  431. @param foundLocations Vector of point where each point contains left-top corner point of detected object boundaries.
  432. @param weights Vector that will contain confidence values for each detected object.
  433. @param hitThreshold Threshold for the distance between features and SVM classifying plane.
  434. Usually it is 0 and should be specified in the detector coefficients (as the last free coefficient).
  435. But if the free coefficient is omitted (which is allowed), you can specify it manually here.
  436. @param winStride Window stride. It must be a multiple of block stride.
  437. @param padding Padding
  438. @param searchLocations Vector of Point includes set of requested locations to be evaluated.
  439. */
  440. CV_WRAP virtual void detect(InputArray img, CV_OUT std::vector<Point>& foundLocations,
  441. CV_OUT std::vector<double>& weights,
  442. double hitThreshold = 0, Size winStride = Size(),
  443. Size padding = Size(),
  444. const std::vector<Point>& searchLocations = std::vector<Point>()) const;
  445. /** @brief Performs object detection without a multi-scale window.
  446. @param img Matrix of the type CV_8U or CV_8UC3 containing an image where objects are detected.
  447. @param foundLocations Vector of point where each point contains left-top corner point of detected object boundaries.
  448. @param hitThreshold Threshold for the distance between features and SVM classifying plane.
  449. Usually it is 0 and should be specified in the detector coefficients (as the last free coefficient).
  450. But if the free coefficient is omitted (which is allowed), you can specify it manually here.
  451. @param winStride Window stride. It must be a multiple of block stride.
  452. @param padding Padding
  453. @param searchLocations Vector of Point includes locations to search.
  454. */
  455. virtual void detect(InputArray img, CV_OUT std::vector<Point>& foundLocations,
  456. double hitThreshold = 0, Size winStride = Size(),
  457. Size padding = Size(),
  458. const std::vector<Point>& searchLocations=std::vector<Point>()) const;
  459. /** @brief Detects objects of different sizes in the input image. The detected objects are returned as a list
  460. of rectangles.
  461. @param img Matrix of the type CV_8U or CV_8UC3 containing an image where objects are detected.
  462. @param foundLocations Vector of rectangles where each rectangle contains the detected object.
  463. @param foundWeights Vector that will contain confidence values for each detected object.
  464. @param hitThreshold Threshold for the distance between features and SVM classifying plane.
  465. Usually it is 0 and should be specified in the detector coefficients (as the last free coefficient).
  466. But if the free coefficient is omitted (which is allowed), you can specify it manually here.
  467. @param winStride Window stride. It must be a multiple of block stride.
  468. @param padding Padding
  469. @param scale Coefficient of the detection window increase.
  470. @param finalThreshold Final threshold
  471. @param useMeanshiftGrouping indicates grouping algorithm
  472. */
  473. CV_WRAP virtual void detectMultiScale(InputArray img, CV_OUT std::vector<Rect>& foundLocations,
  474. CV_OUT std::vector<double>& foundWeights, double hitThreshold = 0,
  475. Size winStride = Size(), Size padding = Size(), double scale = 1.05,
  476. double finalThreshold = 2.0,bool useMeanshiftGrouping = false) const;
  477. /** @brief Detects objects of different sizes in the input image. The detected objects are returned as a list
  478. of rectangles.
  479. @param img Matrix of the type CV_8U or CV_8UC3 containing an image where objects are detected.
  480. @param foundLocations Vector of rectangles where each rectangle contains the detected object.
  481. @param hitThreshold Threshold for the distance between features and SVM classifying plane.
  482. Usually it is 0 and should be specified in the detector coefficients (as the last free coefficient).
  483. But if the free coefficient is omitted (which is allowed), you can specify it manually here.
  484. @param winStride Window stride. It must be a multiple of block stride.
  485. @param padding Padding
  486. @param scale Coefficient of the detection window increase.
  487. @param finalThreshold Final threshold
  488. @param useMeanshiftGrouping indicates grouping algorithm
  489. */
  490. virtual void detectMultiScale(InputArray img, CV_OUT std::vector<Rect>& foundLocations,
  491. double hitThreshold = 0, Size winStride = Size(),
  492. Size padding = Size(), double scale = 1.05,
  493. double finalThreshold = 2.0, bool useMeanshiftGrouping = false) const;
  494. /** @brief Computes gradients and quantized gradient orientations.
  495. @param img Matrix contains the image to be computed
  496. @param grad Matrix of type CV_32FC2 contains computed gradients
  497. @param angleOfs Matrix of type CV_8UC2 contains quantized gradient orientations
  498. @param paddingTL Padding from top-left
  499. @param paddingBR Padding from bottom-right
  500. */
  501. CV_WRAP virtual void computeGradient(InputArray img, InputOutputArray grad, InputOutputArray angleOfs,
  502. Size paddingTL = Size(), Size paddingBR = Size()) const;
  503. /** @brief Returns coefficients of the classifier trained for people detection (for 64x128 windows).
  504. */
  505. CV_WRAP static std::vector<float> getDefaultPeopleDetector();
  506. /**@example samples/tapi/hog.cpp
  507. */
  508. /** @brief Returns coefficients of the classifier trained for people detection (for 48x96 windows).
  509. */
  510. CV_WRAP static std::vector<float> getDaimlerPeopleDetector();
  511. //! Detection window size. Align to block size and block stride. Default value is Size(64,128).
  512. CV_PROP Size winSize;
  513. //! Block size in pixels. Align to cell size. Default value is Size(16,16).
  514. CV_PROP Size blockSize;
  515. //! Block stride. It must be a multiple of cell size. Default value is Size(8,8).
  516. CV_PROP Size blockStride;
  517. //! Cell size. Default value is Size(8,8).
  518. CV_PROP Size cellSize;
  519. //! Number of bins used in the calculation of histogram of gradients. Default value is 9.
  520. CV_PROP int nbins;
  521. //! not documented
  522. CV_PROP int derivAperture;
  523. //! Gaussian smoothing window parameter.
  524. CV_PROP double winSigma;
  525. //! histogramNormType
  526. CV_PROP HOGDescriptor::HistogramNormType histogramNormType;
  527. //! L2-Hys normalization method shrinkage.
  528. CV_PROP double L2HysThreshold;
  529. //! Flag to specify whether the gamma correction preprocessing is required or not.
  530. CV_PROP bool gammaCorrection;
  531. //! coefficients for the linear SVM classifier.
  532. CV_PROP std::vector<float> svmDetector;
  533. //! coefficients for the linear SVM classifier used when OpenCL is enabled
  534. UMat oclSvmDetector;
  535. //! not documented
  536. float free_coef;
  537. //! Maximum number of detection window increases. Default value is 64
  538. CV_PROP int nlevels;
  539. //! Indicates signed gradient will be used or not
  540. CV_PROP bool signedGradient;
  541. /** @brief evaluate specified ROI and return confidence value for each location
  542. @param img Matrix of the type CV_8U or CV_8UC3 containing an image where objects are detected.
  543. @param locations Vector of Point
  544. @param foundLocations Vector of Point where each Point is detected object's top-left point.
  545. @param confidences confidences
  546. @param hitThreshold Threshold for the distance between features and SVM classifying plane. Usually
  547. it is 0 and should be specified in the detector coefficients (as the last free coefficient). But if
  548. the free coefficient is omitted (which is allowed), you can specify it manually here
  549. @param winStride winStride
  550. @param padding padding
  551. */
  552. virtual void detectROI(InputArray img, const std::vector<cv::Point> &locations,
  553. CV_OUT std::vector<cv::Point>& foundLocations, CV_OUT std::vector<double>& confidences,
  554. double hitThreshold = 0, cv::Size winStride = Size(),
  555. cv::Size padding = Size()) const;
  556. /** @brief evaluate specified ROI and return confidence value for each location in multiple scales
  557. @param img Matrix of the type CV_8U or CV_8UC3 containing an image where objects are detected.
  558. @param foundLocations Vector of rectangles where each rectangle contains the detected object.
  559. @param locations Vector of DetectionROI
  560. @param hitThreshold Threshold for the distance between features and SVM classifying plane. Usually it is 0 and should be specified
  561. in the detector coefficients (as the last free coefficient). But if the free coefficient is omitted (which is allowed), you can specify it manually here.
  562. @param groupThreshold Minimum possible number of rectangles minus 1. The threshold is used in a group of rectangles to retain it.
  563. */
  564. virtual void detectMultiScaleROI(InputArray img,
  565. CV_OUT std::vector<cv::Rect>& foundLocations,
  566. std::vector<DetectionROI>& locations,
  567. double hitThreshold = 0,
  568. int groupThreshold = 0) const;
  569. /** @brief Groups the object candidate rectangles.
  570. @param rectList Input/output vector of rectangles. Output vector includes retained and grouped rectangles. (The Python list is not modified in place.)
  571. @param weights Input/output vector of weights of rectangles. Output vector includes weights of retained and grouped rectangles. (The Python list is not modified in place.)
  572. @param groupThreshold Minimum possible number of rectangles minus 1. The threshold is used in a group of rectangles to retain it.
  573. @param eps Relative difference between sides of the rectangles to merge them into a group.
  574. */
  575. void groupRectangles(std::vector<cv::Rect>& rectList, std::vector<double>& weights, int groupThreshold, double eps) const;
  576. };
  577. //! @}
  578. //! @addtogroup objdetect_qrcode
  579. //! @{
  580. class CV_EXPORTS_W QRCodeEncoder {
  581. protected:
  582. QRCodeEncoder(); // use ::create()
  583. public:
  584. virtual ~QRCodeEncoder();
  585. enum EncodeMode {
  586. MODE_AUTO = -1,
  587. MODE_NUMERIC = 1, // 0b0001
  588. MODE_ALPHANUMERIC = 2, // 0b0010
  589. MODE_BYTE = 4, // 0b0100
  590. MODE_ECI = 7, // 0b0111
  591. MODE_KANJI = 8, // 0b1000
  592. MODE_STRUCTURED_APPEND = 3 // 0b0011
  593. };
  594. enum CorrectionLevel {
  595. CORRECT_LEVEL_L = 0,
  596. CORRECT_LEVEL_M = 1,
  597. CORRECT_LEVEL_Q = 2,
  598. CORRECT_LEVEL_H = 3
  599. };
  600. enum ECIEncodings {
  601. ECI_UTF8 = 26
  602. };
  603. /** @brief QR code encoder parameters.
  604. @param version The optional version of QR code (by default - maximum possible depending on
  605. the length of the string).
  606. @param correction_level The optional level of error correction (by default - the lowest).
  607. @param mode The optional encoding mode - Numeric, Alphanumeric, Byte, Kanji, ECI or Structured Append.
  608. @param structure_number The optional number of QR codes to generate in Structured Append mode.
  609. */
  610. struct CV_EXPORTS_W_SIMPLE Params
  611. {
  612. CV_WRAP Params();
  613. CV_PROP_RW int version;
  614. CV_PROP_RW CorrectionLevel correction_level;
  615. CV_PROP_RW EncodeMode mode;
  616. CV_PROP_RW int structure_number;
  617. };
  618. /** @brief Constructor
  619. @param parameters QR code encoder parameters QRCodeEncoder::Params
  620. */
  621. static CV_WRAP
  622. Ptr<QRCodeEncoder> create(const QRCodeEncoder::Params& parameters = QRCodeEncoder::Params());
  623. /** @brief Generates QR code from input string.
  624. @param encoded_info Input string to encode.
  625. @param qrcode Generated QR code.
  626. */
  627. CV_WRAP virtual void encode(const String& encoded_info, OutputArray qrcode) = 0;
  628. /** @brief Generates QR code from input string in Structured Append mode. The encoded message is splitting over a number of QR codes.
  629. @param encoded_info Input string to encode.
  630. @param qrcodes Vector of generated QR codes.
  631. */
  632. CV_WRAP virtual void encodeStructuredAppend(const String& encoded_info, OutputArrayOfArrays qrcodes) = 0;
  633. };
  634. class CV_EXPORTS_W QRCodeDetector
  635. {
  636. public:
  637. CV_WRAP QRCodeDetector();
  638. ~QRCodeDetector();
  639. /** @brief sets the epsilon used during the horizontal scan of QR code stop marker detection.
  640. @param epsX Epsilon neighborhood, which allows you to determine the horizontal pattern
  641. of the scheme 1:1:3:1:1 according to QR code standard.
  642. */
  643. CV_WRAP void setEpsX(double epsX);
  644. /** @brief sets the epsilon used during the vertical scan of QR code stop marker detection.
  645. @param epsY Epsilon neighborhood, which allows you to determine the vertical pattern
  646. of the scheme 1:1:3:1:1 according to QR code standard.
  647. */
  648. CV_WRAP void setEpsY(double epsY);
  649. /** @brief Detects QR code in image and returns the quadrangle containing the code.
  650. @param img grayscale or color (BGR) image containing (or not) QR code.
  651. @param points Output vector of vertices of the minimum-area quadrangle containing the code.
  652. */
  653. CV_WRAP bool detect(InputArray img, OutputArray points) const;
  654. /** @brief Decodes QR code in image once it's found by the detect() method.
  655. Returns UTF8-encoded output string or empty string if the code cannot be decoded.
  656. @param img grayscale or color (BGR) image containing QR code.
  657. @param points Quadrangle vertices found by detect() method (or some other algorithm).
  658. @param straight_qrcode The optional output image containing rectified and binarized QR code
  659. */
  660. CV_WRAP std::string decode(InputArray img, InputArray points, OutputArray straight_qrcode = noArray());
  661. /** @brief Decodes QR code on a curved surface in image once it's found by the detect() method.
  662. Returns UTF8-encoded output string or empty string if the code cannot be decoded.
  663. @param img grayscale or color (BGR) image containing QR code.
  664. @param points Quadrangle vertices found by detect() method (or some other algorithm).
  665. @param straight_qrcode The optional output image containing rectified and binarized QR code
  666. */
  667. CV_WRAP cv::String decodeCurved(InputArray img, InputArray points, OutputArray straight_qrcode = noArray());
  668. /** @brief Both detects and decodes QR code
  669. @param img grayscale or color (BGR) image containing QR code.
  670. @param points optional output array of vertices of the found QR code quadrangle. Will be empty if not found.
  671. @param straight_qrcode The optional output image containing rectified and binarized QR code
  672. */
  673. CV_WRAP std::string detectAndDecode(InputArray img, OutputArray points=noArray(),
  674. OutputArray straight_qrcode = noArray());
  675. /** @brief Both detects and decodes QR code on a curved surface
  676. @param img grayscale or color (BGR) image containing QR code.
  677. @param points optional output array of vertices of the found QR code quadrangle. Will be empty if not found.
  678. @param straight_qrcode The optional output image containing rectified and binarized QR code
  679. */
  680. CV_WRAP std::string detectAndDecodeCurved(InputArray img, OutputArray points=noArray(),
  681. OutputArray straight_qrcode = noArray());
  682. /** @brief Detects QR codes in image and returns the vector of the quadrangles containing the codes.
  683. @param img grayscale or color (BGR) image containing (or not) QR codes.
  684. @param points Output vector of vector of vertices of the minimum-area quadrangle containing the codes.
  685. */
  686. CV_WRAP
  687. bool detectMulti(InputArray img, OutputArray points) const;
  688. /** @brief Decodes QR codes in image once it's found by the detect() method.
  689. @param img grayscale or color (BGR) image containing QR codes.
  690. @param decoded_info UTF8-encoded output vector of string or empty vector of string if the codes cannot be decoded.
  691. @param points vector of Quadrangle vertices found by detect() method (or some other algorithm).
  692. @param straight_qrcode The optional output vector of images containing rectified and binarized QR codes
  693. */
  694. CV_WRAP
  695. bool decodeMulti(
  696. InputArray img, InputArray points,
  697. CV_OUT std::vector<std::string>& decoded_info,
  698. OutputArrayOfArrays straight_qrcode = noArray()
  699. ) const;
  700. /** @brief Both detects and decodes QR codes
  701. @param img grayscale or color (BGR) image containing QR codes.
  702. @param decoded_info UTF8-encoded output vector of string or empty vector of string if the codes cannot be decoded.
  703. @param points optional output vector of vertices of the found QR code quadrangles. Will be empty if not found.
  704. @param straight_qrcode The optional output vector of images containing rectified and binarized QR codes
  705. */
  706. CV_WRAP
  707. bool detectAndDecodeMulti(
  708. InputArray img, CV_OUT std::vector<std::string>& decoded_info,
  709. OutputArray points = noArray(),
  710. OutputArrayOfArrays straight_qrcode = noArray()
  711. ) const;
  712. protected:
  713. struct Impl;
  714. Ptr<Impl> p;
  715. };
  716. //! @}
  717. }
  718. #include "opencv2/objdetect/detection_based_tracker.hpp"
  719. #include "opencv2/objdetect/face.hpp"
  720. #endif