objdetect.hpp 42 KB

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