features2d.hpp 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455
  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. // Third party copyrights are property of their respective owners.
  16. //
  17. // Redistribution and use in source and binary forms, with or without modification,
  18. // are permitted provided that the following conditions are met:
  19. //
  20. // * Redistribution's of source code must retain the above copyright notice,
  21. // this list of conditions and the following disclaimer.
  22. //
  23. // * Redistribution's in binary form must reproduce the above copyright notice,
  24. // this list of conditions and the following disclaimer in the documentation
  25. // and/or other materials provided with the distribution.
  26. //
  27. // * The name of the copyright holders may not be used to endorse or promote products
  28. // derived from this software without specific prior written permission.
  29. //
  30. // This software is provided by the copyright holders and contributors "as is" and
  31. // any express or implied warranties, including, but not limited to, the implied
  32. // warranties of merchantability and fitness for a particular purpose are disclaimed.
  33. // In no event shall the Intel Corporation or contributors be liable for any direct,
  34. // indirect, incidental, special, exemplary, or consequential damages
  35. // (including, but not limited to, procurement of substitute goods or services;
  36. // loss of use, data, or profits; or business interruption) however caused
  37. // and on any theory of liability, whether in contract, strict liability,
  38. // or tort (including negligence or otherwise) arising in any way out of
  39. // the use of this software, even if advised of the possibility of such damage.
  40. //
  41. //M*/
  42. #ifndef OPENCV_FEATURES_2D_HPP
  43. #define OPENCV_FEATURES_2D_HPP
  44. #include "opencv2/opencv_modules.hpp"
  45. #include "opencv2/core.hpp"
  46. #ifdef HAVE_OPENCV_FLANN
  47. #include "opencv2/flann/miniflann.hpp"
  48. #endif
  49. /**
  50. @defgroup features2d 2D Features Framework
  51. @{
  52. @defgroup features2d_main Feature Detection and Description
  53. @defgroup features2d_match Descriptor Matchers
  54. Matchers of keypoint descriptors in OpenCV have wrappers with a common interface that enables you to
  55. easily switch between different algorithms solving the same problem. This section is devoted to
  56. matching descriptors that are represented as vectors in a multidimensional space. All objects that
  57. implement vector descriptor matchers inherit the DescriptorMatcher interface.
  58. @note
  59. - An example explaining keypoint matching can be found at
  60. opencv_source_code/samples/cpp/descriptor_extractor_matcher.cpp
  61. - An example on descriptor matching evaluation can be found at
  62. opencv_source_code/samples/cpp/detector_descriptor_matcher_evaluation.cpp
  63. - An example on one to many image matching can be found at
  64. opencv_source_code/samples/cpp/matching_to_many_images.cpp
  65. @defgroup features2d_draw Drawing Function of Keypoints and Matches
  66. @defgroup features2d_category Object Categorization
  67. This section describes approaches based on local 2D features and used to categorize objects.
  68. @note
  69. - A complete Bag-Of-Words sample can be found at
  70. opencv_source_code/samples/cpp/bagofwords_classification.cpp
  71. - (Python) An example using the features2D framework to perform object categorization can be
  72. found at opencv_source_code/samples/python/find_obj.py
  73. @defgroup feature2d_hal Hardware Acceleration Layer
  74. @{
  75. @defgroup features2d_hal_interface Interface
  76. @}
  77. @}
  78. */
  79. namespace cv
  80. {
  81. //! @addtogroup features2d
  82. //! @{
  83. // //! writes vector of keypoints to the file storage
  84. // CV_EXPORTS void write(FileStorage& fs, const String& name, const std::vector<KeyPoint>& keypoints);
  85. // //! reads vector of keypoints from the specified file storage node
  86. // CV_EXPORTS void read(const FileNode& node, CV_OUT std::vector<KeyPoint>& keypoints);
  87. /** @brief A class filters a vector of keypoints.
  88. Because now it is difficult to provide a convenient interface for all usage scenarios of the
  89. keypoints filter class, it has only several needed by now static methods.
  90. */
  91. class CV_EXPORTS KeyPointsFilter
  92. {
  93. public:
  94. KeyPointsFilter(){}
  95. /*
  96. * Remove keypoints within borderPixels of an image edge.
  97. */
  98. static void runByImageBorder( std::vector<KeyPoint>& keypoints, Size imageSize, int borderSize );
  99. /*
  100. * Remove keypoints of sizes out of range.
  101. */
  102. static void runByKeypointSize( std::vector<KeyPoint>& keypoints, float minSize,
  103. float maxSize=FLT_MAX );
  104. /*
  105. * Remove keypoints from some image by mask for pixels of this image.
  106. */
  107. static void runByPixelsMask( std::vector<KeyPoint>& keypoints, const Mat& mask );
  108. /*
  109. * Remove duplicated keypoints.
  110. */
  111. static void removeDuplicated( std::vector<KeyPoint>& keypoints );
  112. /*
  113. * Remove duplicated keypoints and sort the remaining keypoints
  114. */
  115. static void removeDuplicatedSorted( std::vector<KeyPoint>& keypoints );
  116. /*
  117. * Retain the specified number of the best keypoints (according to the response)
  118. */
  119. static void retainBest( std::vector<KeyPoint>& keypoints, int npoints );
  120. };
  121. /************************************ Base Classes ************************************/
  122. /** @brief Abstract base class for 2D image feature detectors and descriptor extractors
  123. */
  124. #ifdef __EMSCRIPTEN__
  125. class CV_EXPORTS_W Feature2D : public Algorithm
  126. #else
  127. class CV_EXPORTS_W Feature2D : public virtual Algorithm
  128. #endif
  129. {
  130. public:
  131. virtual ~Feature2D();
  132. /** @brief Detects keypoints in an image (first variant) or image set (second variant).
  133. @param image Image.
  134. @param keypoints The detected keypoints. In the second variant of the method keypoints[i] is a set
  135. of keypoints detected in images[i] .
  136. @param mask Mask specifying where to look for keypoints (optional). It must be a 8-bit integer
  137. matrix with non-zero values in the region of interest.
  138. */
  139. CV_WRAP virtual void detect( InputArray image,
  140. CV_OUT std::vector<KeyPoint>& keypoints,
  141. InputArray mask=noArray() );
  142. /** @overload
  143. @param images Image set.
  144. @param keypoints The detected keypoints. In the second variant of the method keypoints[i] is a set
  145. of keypoints detected in images[i] .
  146. @param masks Masks for each input image specifying where to look for keypoints (optional).
  147. masks[i] is a mask for images[i].
  148. */
  149. CV_WRAP virtual void detect( InputArrayOfArrays images,
  150. CV_OUT std::vector<std::vector<KeyPoint> >& keypoints,
  151. InputArrayOfArrays masks=noArray() );
  152. /** @brief Computes the descriptors for a set of keypoints detected in an image (first variant) or image set
  153. (second variant).
  154. @param image Image.
  155. @param keypoints Input collection of keypoints. Keypoints for which a descriptor cannot be
  156. computed are removed. Sometimes new keypoints can be added, for example: SIFT duplicates keypoint
  157. with several dominant orientations (for each orientation).
  158. @param descriptors Computed descriptors. In the second variant of the method descriptors[i] are
  159. descriptors computed for a keypoints[i]. Row j is the keypoints (or keypoints[i]) is the
  160. descriptor for keypoint j-th keypoint.
  161. */
  162. CV_WRAP virtual void compute( InputArray image,
  163. CV_OUT CV_IN_OUT std::vector<KeyPoint>& keypoints,
  164. OutputArray descriptors );
  165. /** @overload
  166. @param images Image set.
  167. @param keypoints Input collection of keypoints. Keypoints for which a descriptor cannot be
  168. computed are removed. Sometimes new keypoints can be added, for example: SIFT duplicates keypoint
  169. with several dominant orientations (for each orientation).
  170. @param descriptors Computed descriptors. In the second variant of the method descriptors[i] are
  171. descriptors computed for a keypoints[i]. Row j is the keypoints (or keypoints[i]) is the
  172. descriptor for keypoint j-th keypoint.
  173. */
  174. CV_WRAP virtual void compute( InputArrayOfArrays images,
  175. CV_OUT CV_IN_OUT std::vector<std::vector<KeyPoint> >& keypoints,
  176. OutputArrayOfArrays descriptors );
  177. /** Detects keypoints and computes the descriptors */
  178. CV_WRAP virtual void detectAndCompute( InputArray image, InputArray mask,
  179. CV_OUT std::vector<KeyPoint>& keypoints,
  180. OutputArray descriptors,
  181. bool useProvidedKeypoints=false );
  182. CV_WRAP virtual int descriptorSize() const;
  183. CV_WRAP virtual int descriptorType() const;
  184. CV_WRAP virtual int defaultNorm() const;
  185. CV_WRAP void write( const String& fileName ) const;
  186. CV_WRAP void read( const String& fileName );
  187. virtual void write( FileStorage&) const CV_OVERRIDE;
  188. // see corresponding cv::Algorithm method
  189. CV_WRAP virtual void read( const FileNode&) CV_OVERRIDE;
  190. //! Return true if detector object is empty
  191. CV_WRAP virtual bool empty() const CV_OVERRIDE;
  192. CV_WRAP virtual String getDefaultName() const CV_OVERRIDE;
  193. // see corresponding cv::Algorithm method
  194. CV_WRAP inline void write(const Ptr<FileStorage>& fs, const String& name = String()) const { Algorithm::write(fs, name); }
  195. };
  196. /** Feature detectors in OpenCV have wrappers with a common interface that enables you to easily switch
  197. between different algorithms solving the same problem. All objects that implement keypoint detectors
  198. inherit the FeatureDetector interface. */
  199. typedef Feature2D FeatureDetector;
  200. /** Extractors of keypoint descriptors in OpenCV have wrappers with a common interface that enables you
  201. to easily switch between different algorithms solving the same problem. This section is devoted to
  202. computing descriptors represented as vectors in a multidimensional space. All objects that implement
  203. the vector descriptor extractors inherit the DescriptorExtractor interface.
  204. */
  205. typedef Feature2D DescriptorExtractor;
  206. //! @addtogroup features2d_main
  207. //! @{
  208. /** @brief Class implementing the BRISK keypoint detector and descriptor extractor, described in @cite LCS11 .
  209. */
  210. class CV_EXPORTS_W BRISK : public Feature2D
  211. {
  212. public:
  213. /** @brief The BRISK constructor
  214. @param thresh AGAST detection threshold score.
  215. @param octaves detection octaves. Use 0 to do single scale.
  216. @param patternScale apply this scale to the pattern used for sampling the neighbourhood of a
  217. keypoint.
  218. */
  219. CV_WRAP static Ptr<BRISK> create(int thresh=30, int octaves=3, float patternScale=1.0f);
  220. /** @brief The BRISK constructor for a custom pattern
  221. @param radiusList defines the radii (in pixels) where the samples around a keypoint are taken (for
  222. keypoint scale 1).
  223. @param numberList defines the number of sampling points on the sampling circle. Must be the same
  224. size as radiusList..
  225. @param dMax threshold for the short pairings used for descriptor formation (in pixels for keypoint
  226. scale 1).
  227. @param dMin threshold for the long pairings used for orientation determination (in pixels for
  228. keypoint scale 1).
  229. @param indexChange index remapping of the bits. */
  230. CV_WRAP static Ptr<BRISK> create(const std::vector<float> &radiusList, const std::vector<int> &numberList,
  231. float dMax=5.85f, float dMin=8.2f, const std::vector<int>& indexChange=std::vector<int>());
  232. /** @brief The BRISK constructor for a custom pattern, detection threshold and octaves
  233. @param thresh AGAST detection threshold score.
  234. @param octaves detection octaves. Use 0 to do single scale.
  235. @param radiusList defines the radii (in pixels) where the samples around a keypoint are taken (for
  236. keypoint scale 1).
  237. @param numberList defines the number of sampling points on the sampling circle. Must be the same
  238. size as radiusList..
  239. @param dMax threshold for the short pairings used for descriptor formation (in pixels for keypoint
  240. scale 1).
  241. @param dMin threshold for the long pairings used for orientation determination (in pixels for
  242. keypoint scale 1).
  243. @param indexChange index remapping of the bits. */
  244. CV_WRAP static Ptr<BRISK> create(int thresh, int octaves, const std::vector<float> &radiusList,
  245. const std::vector<int> &numberList, float dMax=5.85f, float dMin=8.2f,
  246. const std::vector<int>& indexChange=std::vector<int>());
  247. CV_WRAP virtual String getDefaultName() const CV_OVERRIDE;
  248. /** @brief Set detection threshold.
  249. @param threshold AGAST detection threshold score.
  250. */
  251. CV_WRAP virtual void setThreshold(int threshold) { CV_UNUSED(threshold); return; }
  252. CV_WRAP virtual int getThreshold() const { return -1; }
  253. /** @brief Set detection octaves.
  254. @param octaves detection octaves. Use 0 to do single scale.
  255. */
  256. CV_WRAP virtual void setOctaves(int octaves) { CV_UNUSED(octaves); return; }
  257. CV_WRAP virtual int getOctaves() const { return -1; }
  258. };
  259. /** @brief Class implementing the ORB (*oriented BRIEF*) keypoint detector and descriptor extractor
  260. described in @cite RRKB11 . The algorithm uses FAST in pyramids to detect stable keypoints, selects
  261. the strongest features using FAST or Harris response, finds their orientation using first-order
  262. moments and computes the descriptors using BRIEF (where the coordinates of random point pairs (or
  263. k-tuples) are rotated according to the measured orientation).
  264. */
  265. class CV_EXPORTS_W ORB : public Feature2D
  266. {
  267. public:
  268. enum ScoreType { HARRIS_SCORE=0, FAST_SCORE=1 };
  269. static const int kBytes = 32;
  270. /** @brief The ORB constructor
  271. @param nfeatures The maximum number of features to retain.
  272. @param scaleFactor Pyramid decimation ratio, greater than 1. scaleFactor==2 means the classical
  273. pyramid, where each next level has 4x less pixels than the previous, but such a big scale factor
  274. will degrade feature matching scores dramatically. On the other hand, too close to 1 scale factor
  275. will mean that to cover certain scale range you will need more pyramid levels and so the speed
  276. will suffer.
  277. @param nlevels The number of pyramid levels. The smallest level will have linear size equal to
  278. input_image_linear_size/pow(scaleFactor, nlevels - firstLevel).
  279. @param edgeThreshold This is size of the border where the features are not detected. It should
  280. roughly match the patchSize parameter.
  281. @param firstLevel The level of pyramid to put source image to. Previous layers are filled
  282. with upscaled source image.
  283. @param WTA_K The number of points that produce each element of the oriented BRIEF descriptor. The
  284. default value 2 means the BRIEF where we take a random point pair and compare their brightnesses,
  285. so we get 0/1 response. Other possible values are 3 and 4. For example, 3 means that we take 3
  286. random points (of course, those point coordinates are random, but they are generated from the
  287. pre-defined seed, so each element of BRIEF descriptor is computed deterministically from the pixel
  288. rectangle), find point of maximum brightness and output index of the winner (0, 1 or 2). Such
  289. output will occupy 2 bits, and therefore it will need a special variant of Hamming distance,
  290. denoted as NORM_HAMMING2 (2 bits per bin). When WTA_K=4, we take 4 random points to compute each
  291. bin (that will also occupy 2 bits with possible values 0, 1, 2 or 3).
  292. @param scoreType The default HARRIS_SCORE means that Harris algorithm is used to rank features
  293. (the score is written to KeyPoint::score and is used to retain best nfeatures features);
  294. FAST_SCORE is alternative value of the parameter that produces slightly less stable keypoints,
  295. but it is a little faster to compute.
  296. @param patchSize size of the patch used by the oriented BRIEF descriptor. Of course, on smaller
  297. pyramid layers the perceived image area covered by a feature will be larger.
  298. @param fastThreshold the fast threshold
  299. */
  300. CV_WRAP static Ptr<ORB> create(int nfeatures=500, float scaleFactor=1.2f, int nlevels=8, int edgeThreshold=31,
  301. int firstLevel=0, int WTA_K=2, ORB::ScoreType scoreType=ORB::HARRIS_SCORE, int patchSize=31, int fastThreshold=20);
  302. CV_WRAP virtual void setMaxFeatures(int maxFeatures) = 0;
  303. CV_WRAP virtual int getMaxFeatures() const = 0;
  304. CV_WRAP virtual void setScaleFactor(double scaleFactor) = 0;
  305. CV_WRAP virtual double getScaleFactor() const = 0;
  306. CV_WRAP virtual void setNLevels(int nlevels) = 0;
  307. CV_WRAP virtual int getNLevels() const = 0;
  308. CV_WRAP virtual void setEdgeThreshold(int edgeThreshold) = 0;
  309. CV_WRAP virtual int getEdgeThreshold() const = 0;
  310. CV_WRAP virtual void setFirstLevel(int firstLevel) = 0;
  311. CV_WRAP virtual int getFirstLevel() const = 0;
  312. CV_WRAP virtual void setWTA_K(int wta_k) = 0;
  313. CV_WRAP virtual int getWTA_K() const = 0;
  314. CV_WRAP virtual void setScoreType(ORB::ScoreType scoreType) = 0;
  315. CV_WRAP virtual ORB::ScoreType getScoreType() const = 0;
  316. CV_WRAP virtual void setPatchSize(int patchSize) = 0;
  317. CV_WRAP virtual int getPatchSize() const = 0;
  318. CV_WRAP virtual void setFastThreshold(int fastThreshold) = 0;
  319. CV_WRAP virtual int getFastThreshold() const = 0;
  320. CV_WRAP virtual String getDefaultName() const CV_OVERRIDE;
  321. };
  322. /** @brief Maximally stable extremal region extractor
  323. The class encapsulates all the parameters of the %MSER extraction algorithm (see [wiki
  324. article](http://en.wikipedia.org/wiki/Maximally_stable_extremal_regions)).
  325. - there are two different implementation of %MSER: one for grey image, one for color image
  326. - the grey image algorithm is taken from: @cite nister2008linear ; the paper claims to be faster
  327. than union-find method; it actually get 1.5~2m/s on my centrino L7200 1.2GHz laptop.
  328. - the color image algorithm is taken from: @cite forssen2007maximally ; it should be much slower
  329. than grey image method ( 3~4 times ); the chi_table.h file is taken directly from paper's source
  330. code which is distributed under GPL.
  331. - (Python) A complete example showing the use of the %MSER detector can be found at samples/python/mser.py
  332. */
  333. class CV_EXPORTS_W MSER : public Feature2D
  334. {
  335. public:
  336. /** @brief Full constructor for %MSER detector
  337. @param _delta it compares \f$(size_{i}-size_{i-delta})/size_{i-delta}\f$
  338. @param _min_area prune the area which smaller than minArea
  339. @param _max_area prune the area which bigger than maxArea
  340. @param _max_variation prune the area have similar size to its children
  341. @param _min_diversity for color image, trace back to cut off mser with diversity less than min_diversity
  342. @param _max_evolution for color image, the evolution steps
  343. @param _area_threshold for color image, the area threshold to cause re-initialize
  344. @param _min_margin for color image, ignore too small margin
  345. @param _edge_blur_size for color image, the aperture size for edge blur
  346. */
  347. CV_WRAP static Ptr<MSER> create( int _delta=5, int _min_area=60, int _max_area=14400,
  348. double _max_variation=0.25, double _min_diversity=.2,
  349. int _max_evolution=200, double _area_threshold=1.01,
  350. double _min_margin=0.003, int _edge_blur_size=5 );
  351. /** @brief Detect %MSER regions
  352. @param image input image (8UC1, 8UC3 or 8UC4, must be greater or equal than 3x3)
  353. @param msers resulting list of point sets
  354. @param bboxes resulting bounding boxes
  355. */
  356. CV_WRAP virtual void detectRegions( InputArray image,
  357. CV_OUT std::vector<std::vector<Point> >& msers,
  358. CV_OUT std::vector<Rect>& bboxes ) = 0;
  359. CV_WRAP virtual void setDelta(int delta) = 0;
  360. CV_WRAP virtual int getDelta() const = 0;
  361. CV_WRAP virtual void setMinArea(int minArea) = 0;
  362. CV_WRAP virtual int getMinArea() const = 0;
  363. CV_WRAP virtual void setMaxArea(int maxArea) = 0;
  364. CV_WRAP virtual int getMaxArea() const = 0;
  365. CV_WRAP virtual void setPass2Only(bool f) = 0;
  366. CV_WRAP virtual bool getPass2Only() const = 0;
  367. CV_WRAP virtual String getDefaultName() const CV_OVERRIDE;
  368. };
  369. //! @} features2d_main
  370. //! @addtogroup features2d_main
  371. //! @{
  372. /** @brief Wrapping class for feature detection using the FAST method. :
  373. */
  374. class CV_EXPORTS_W FastFeatureDetector : public Feature2D
  375. {
  376. public:
  377. enum DetectorType
  378. {
  379. TYPE_5_8 = 0, TYPE_7_12 = 1, TYPE_9_16 = 2
  380. };
  381. enum
  382. {
  383. THRESHOLD = 10000, NONMAX_SUPPRESSION=10001, FAST_N=10002
  384. };
  385. CV_WRAP static Ptr<FastFeatureDetector> create( int threshold=10,
  386. bool nonmaxSuppression=true,
  387. FastFeatureDetector::DetectorType type=FastFeatureDetector::TYPE_9_16 );
  388. CV_WRAP virtual void setThreshold(int threshold) = 0;
  389. CV_WRAP virtual int getThreshold() const = 0;
  390. CV_WRAP virtual void setNonmaxSuppression(bool f) = 0;
  391. CV_WRAP virtual bool getNonmaxSuppression() const = 0;
  392. CV_WRAP virtual void setType(FastFeatureDetector::DetectorType type) = 0;
  393. CV_WRAP virtual FastFeatureDetector::DetectorType getType() const = 0;
  394. CV_WRAP virtual String getDefaultName() const CV_OVERRIDE;
  395. };
  396. /** @overload */
  397. CV_EXPORTS void FAST( InputArray image, CV_OUT std::vector<KeyPoint>& keypoints,
  398. int threshold, bool nonmaxSuppression=true );
  399. /** @brief Detects corners using the FAST algorithm
  400. @param image grayscale image where keypoints (corners) are detected.
  401. @param keypoints keypoints detected on the image.
  402. @param threshold threshold on difference between intensity of the central pixel and pixels of a
  403. circle around this pixel.
  404. @param nonmaxSuppression if true, non-maximum suppression is applied to detected corners
  405. (keypoints).
  406. @param type one of the three neighborhoods as defined in the paper:
  407. FastFeatureDetector::TYPE_9_16, FastFeatureDetector::TYPE_7_12,
  408. FastFeatureDetector::TYPE_5_8
  409. Detects corners using the FAST algorithm by @cite Rosten06 .
  410. @note In Python API, types are given as cv.FAST_FEATURE_DETECTOR_TYPE_5_8,
  411. cv.FAST_FEATURE_DETECTOR_TYPE_7_12 and cv.FAST_FEATURE_DETECTOR_TYPE_9_16. For corner
  412. detection, use cv.FAST.detect() method.
  413. */
  414. CV_EXPORTS void FAST( InputArray image, CV_OUT std::vector<KeyPoint>& keypoints,
  415. int threshold, bool nonmaxSuppression, FastFeatureDetector::DetectorType type );
  416. //! @} features2d_main
  417. //! @addtogroup features2d_main
  418. //! @{
  419. /** @brief Wrapping class for feature detection using the AGAST method. :
  420. */
  421. class CV_EXPORTS_W AgastFeatureDetector : public Feature2D
  422. {
  423. public:
  424. enum DetectorType
  425. {
  426. AGAST_5_8 = 0, AGAST_7_12d = 1, AGAST_7_12s = 2, OAST_9_16 = 3,
  427. };
  428. enum
  429. {
  430. THRESHOLD = 10000, NONMAX_SUPPRESSION = 10001,
  431. };
  432. CV_WRAP static Ptr<AgastFeatureDetector> create( int threshold=10,
  433. bool nonmaxSuppression=true,
  434. AgastFeatureDetector::DetectorType type = AgastFeatureDetector::OAST_9_16);
  435. CV_WRAP virtual void setThreshold(int threshold) = 0;
  436. CV_WRAP virtual int getThreshold() const = 0;
  437. CV_WRAP virtual void setNonmaxSuppression(bool f) = 0;
  438. CV_WRAP virtual bool getNonmaxSuppression() const = 0;
  439. CV_WRAP virtual void setType(AgastFeatureDetector::DetectorType type) = 0;
  440. CV_WRAP virtual AgastFeatureDetector::DetectorType getType() const = 0;
  441. CV_WRAP virtual String getDefaultName() const CV_OVERRIDE;
  442. };
  443. /** @overload */
  444. CV_EXPORTS void AGAST( InputArray image, CV_OUT std::vector<KeyPoint>& keypoints,
  445. int threshold, bool nonmaxSuppression=true );
  446. /** @brief Detects corners using the AGAST algorithm
  447. @param image grayscale image where keypoints (corners) are detected.
  448. @param keypoints keypoints detected on the image.
  449. @param threshold threshold on difference between intensity of the central pixel and pixels of a
  450. circle around this pixel.
  451. @param nonmaxSuppression if true, non-maximum suppression is applied to detected corners
  452. (keypoints).
  453. @param type one of the four neighborhoods as defined in the paper:
  454. AgastFeatureDetector::AGAST_5_8, AgastFeatureDetector::AGAST_7_12d,
  455. AgastFeatureDetector::AGAST_7_12s, AgastFeatureDetector::OAST_9_16
  456. For non-Intel platforms, there is a tree optimised variant of AGAST with same numerical results.
  457. The 32-bit binary tree tables were generated automatically from original code using perl script.
  458. The perl script and examples of tree generation are placed in features2d/doc folder.
  459. Detects corners using the AGAST algorithm by @cite mair2010_agast .
  460. */
  461. CV_EXPORTS void AGAST( InputArray image, CV_OUT std::vector<KeyPoint>& keypoints,
  462. int threshold, bool nonmaxSuppression, AgastFeatureDetector::DetectorType type );
  463. /** @brief Wrapping class for feature detection using the goodFeaturesToTrack function. :
  464. */
  465. class CV_EXPORTS_W GFTTDetector : public Feature2D
  466. {
  467. public:
  468. CV_WRAP static Ptr<GFTTDetector> create( int maxCorners=1000, double qualityLevel=0.01, double minDistance=1,
  469. int blockSize=3, bool useHarrisDetector=false, double k=0.04 );
  470. CV_WRAP static Ptr<GFTTDetector> create( int maxCorners, double qualityLevel, double minDistance,
  471. int blockSize, int gradiantSize, bool useHarrisDetector=false, double k=0.04 );
  472. CV_WRAP virtual void setMaxFeatures(int maxFeatures) = 0;
  473. CV_WRAP virtual int getMaxFeatures() const = 0;
  474. CV_WRAP virtual void setQualityLevel(double qlevel) = 0;
  475. CV_WRAP virtual double getQualityLevel() const = 0;
  476. CV_WRAP virtual void setMinDistance(double minDistance) = 0;
  477. CV_WRAP virtual double getMinDistance() const = 0;
  478. CV_WRAP virtual void setBlockSize(int blockSize) = 0;
  479. CV_WRAP virtual int getBlockSize() const = 0;
  480. CV_WRAP virtual void setHarrisDetector(bool val) = 0;
  481. CV_WRAP virtual bool getHarrisDetector() const = 0;
  482. CV_WRAP virtual void setK(double k) = 0;
  483. CV_WRAP virtual double getK() const = 0;
  484. CV_WRAP virtual String getDefaultName() const CV_OVERRIDE;
  485. };
  486. /** @brief Class for extracting blobs from an image. :
  487. The class implements a simple algorithm for extracting blobs from an image:
  488. 1. Convert the source image to binary images by applying thresholding with several thresholds from
  489. minThreshold (inclusive) to maxThreshold (exclusive) with distance thresholdStep between
  490. neighboring thresholds.
  491. 2. Extract connected components from every binary image by findContours and calculate their
  492. centers.
  493. 3. Group centers from several binary images by their coordinates. Close centers form one group that
  494. corresponds to one blob, which is controlled by the minDistBetweenBlobs parameter.
  495. 4. From the groups, estimate final centers of blobs and their radiuses and return as locations and
  496. sizes of keypoints.
  497. This class performs several filtrations of returned blobs. You should set filterBy\* to true/false
  498. to turn on/off corresponding filtration. Available filtrations:
  499. - **By color**. This filter compares the intensity of a binary image at the center of a blob to
  500. blobColor. If they differ, the blob is filtered out. Use blobColor = 0 to extract dark blobs
  501. and blobColor = 255 to extract light blobs.
  502. - **By area**. Extracted blobs have an area between minArea (inclusive) and maxArea (exclusive).
  503. - **By circularity**. Extracted blobs have circularity
  504. (\f$\frac{4*\pi*Area}{perimeter * perimeter}\f$) between minCircularity (inclusive) and
  505. maxCircularity (exclusive).
  506. - **By ratio of the minimum inertia to maximum inertia**. Extracted blobs have this ratio
  507. between minInertiaRatio (inclusive) and maxInertiaRatio (exclusive).
  508. - **By convexity**. Extracted blobs have convexity (area / area of blob convex hull) between
  509. minConvexity (inclusive) and maxConvexity (exclusive).
  510. Default values of parameters are tuned to extract dark circular blobs.
  511. */
  512. class CV_EXPORTS_W SimpleBlobDetector : public Feature2D
  513. {
  514. public:
  515. struct CV_EXPORTS_W_SIMPLE Params
  516. {
  517. CV_WRAP Params();
  518. CV_PROP_RW float thresholdStep;
  519. CV_PROP_RW float minThreshold;
  520. CV_PROP_RW float maxThreshold;
  521. CV_PROP_RW size_t minRepeatability;
  522. CV_PROP_RW float minDistBetweenBlobs;
  523. CV_PROP_RW bool filterByColor;
  524. CV_PROP_RW uchar blobColor;
  525. CV_PROP_RW bool filterByArea;
  526. CV_PROP_RW float minArea, maxArea;
  527. CV_PROP_RW bool filterByCircularity;
  528. CV_PROP_RW float minCircularity, maxCircularity;
  529. CV_PROP_RW bool filterByInertia;
  530. CV_PROP_RW float minInertiaRatio, maxInertiaRatio;
  531. CV_PROP_RW bool filterByConvexity;
  532. CV_PROP_RW float minConvexity, maxConvexity;
  533. void read( const FileNode& fn );
  534. void write( FileStorage& fs ) const;
  535. };
  536. CV_WRAP static Ptr<SimpleBlobDetector>
  537. create(const SimpleBlobDetector::Params &parameters = SimpleBlobDetector::Params());
  538. CV_WRAP virtual String getDefaultName() const CV_OVERRIDE;
  539. };
  540. //! @} features2d_main
  541. //! @addtogroup features2d_main
  542. //! @{
  543. /** @brief Class implementing the KAZE keypoint detector and descriptor extractor, described in @cite ABD12 .
  544. @note AKAZE descriptor can only be used with KAZE or AKAZE keypoints .. [ABD12] KAZE Features. Pablo
  545. F. Alcantarilla, Adrien Bartoli and Andrew J. Davison. In European Conference on Computer Vision
  546. (ECCV), Fiorenze, Italy, October 2012.
  547. */
  548. class CV_EXPORTS_W KAZE : public Feature2D
  549. {
  550. public:
  551. enum DiffusivityType
  552. {
  553. DIFF_PM_G1 = 0,
  554. DIFF_PM_G2 = 1,
  555. DIFF_WEICKERT = 2,
  556. DIFF_CHARBONNIER = 3
  557. };
  558. /** @brief The KAZE constructor
  559. @param extended Set to enable extraction of extended (128-byte) descriptor.
  560. @param upright Set to enable use of upright descriptors (non rotation-invariant).
  561. @param threshold Detector response threshold to accept point
  562. @param nOctaves Maximum octave evolution of the image
  563. @param nOctaveLayers Default number of sublevels per scale level
  564. @param diffusivity Diffusivity type. DIFF_PM_G1, DIFF_PM_G2, DIFF_WEICKERT or
  565. DIFF_CHARBONNIER
  566. */
  567. CV_WRAP static Ptr<KAZE> create(bool extended=false, bool upright=false,
  568. float threshold = 0.001f,
  569. int nOctaves = 4, int nOctaveLayers = 4,
  570. KAZE::DiffusivityType diffusivity = KAZE::DIFF_PM_G2);
  571. CV_WRAP virtual void setExtended(bool extended) = 0;
  572. CV_WRAP virtual bool getExtended() const = 0;
  573. CV_WRAP virtual void setUpright(bool upright) = 0;
  574. CV_WRAP virtual bool getUpright() const = 0;
  575. CV_WRAP virtual void setThreshold(double threshold) = 0;
  576. CV_WRAP virtual double getThreshold() const = 0;
  577. CV_WRAP virtual void setNOctaves(int octaves) = 0;
  578. CV_WRAP virtual int getNOctaves() const = 0;
  579. CV_WRAP virtual void setNOctaveLayers(int octaveLayers) = 0;
  580. CV_WRAP virtual int getNOctaveLayers() const = 0;
  581. CV_WRAP virtual void setDiffusivity(KAZE::DiffusivityType diff) = 0;
  582. CV_WRAP virtual KAZE::DiffusivityType getDiffusivity() const = 0;
  583. CV_WRAP virtual String getDefaultName() const CV_OVERRIDE;
  584. };
  585. /** @brief Class implementing the AKAZE keypoint detector and descriptor extractor, described in @cite ANB13.
  586. @details AKAZE descriptors can only be used with KAZE or AKAZE keypoints. This class is thread-safe.
  587. @note When you need descriptors use Feature2D::detectAndCompute, which
  588. provides better performance. When using Feature2D::detect followed by
  589. Feature2D::compute scale space pyramid is computed twice.
  590. @note AKAZE implements T-API. When image is passed as UMat some parts of the algorithm
  591. will use OpenCL.
  592. @note [ANB13] Fast Explicit Diffusion for Accelerated Features in Nonlinear
  593. Scale Spaces. Pablo F. Alcantarilla, Jesús Nuevo and Adrien Bartoli. In
  594. British Machine Vision Conference (BMVC), Bristol, UK, September 2013.
  595. */
  596. class CV_EXPORTS_W AKAZE : public Feature2D
  597. {
  598. public:
  599. // AKAZE descriptor type
  600. enum DescriptorType
  601. {
  602. DESCRIPTOR_KAZE_UPRIGHT = 2, ///< Upright descriptors, not invariant to rotation
  603. DESCRIPTOR_KAZE = 3,
  604. DESCRIPTOR_MLDB_UPRIGHT = 4, ///< Upright descriptors, not invariant to rotation
  605. DESCRIPTOR_MLDB = 5
  606. };
  607. /** @brief The AKAZE constructor
  608. @param descriptor_type Type of the extracted descriptor: DESCRIPTOR_KAZE,
  609. DESCRIPTOR_KAZE_UPRIGHT, DESCRIPTOR_MLDB or DESCRIPTOR_MLDB_UPRIGHT.
  610. @param descriptor_size Size of the descriptor in bits. 0 -\> Full size
  611. @param descriptor_channels Number of channels in the descriptor (1, 2, 3)
  612. @param threshold Detector response threshold to accept point
  613. @param nOctaves Maximum octave evolution of the image
  614. @param nOctaveLayers Default number of sublevels per scale level
  615. @param diffusivity Diffusivity type. DIFF_PM_G1, DIFF_PM_G2, DIFF_WEICKERT or
  616. DIFF_CHARBONNIER
  617. */
  618. CV_WRAP static Ptr<AKAZE> create(AKAZE::DescriptorType descriptor_type = AKAZE::DESCRIPTOR_MLDB,
  619. int descriptor_size = 0, int descriptor_channels = 3,
  620. float threshold = 0.001f, int nOctaves = 4,
  621. int nOctaveLayers = 4, KAZE::DiffusivityType diffusivity = KAZE::DIFF_PM_G2);
  622. CV_WRAP virtual void setDescriptorType(AKAZE::DescriptorType dtype) = 0;
  623. CV_WRAP virtual AKAZE::DescriptorType getDescriptorType() const = 0;
  624. CV_WRAP virtual void setDescriptorSize(int dsize) = 0;
  625. CV_WRAP virtual int getDescriptorSize() const = 0;
  626. CV_WRAP virtual void setDescriptorChannels(int dch) = 0;
  627. CV_WRAP virtual int getDescriptorChannels() const = 0;
  628. CV_WRAP virtual void setThreshold(double threshold) = 0;
  629. CV_WRAP virtual double getThreshold() const = 0;
  630. CV_WRAP virtual void setNOctaves(int octaves) = 0;
  631. CV_WRAP virtual int getNOctaves() const = 0;
  632. CV_WRAP virtual void setNOctaveLayers(int octaveLayers) = 0;
  633. CV_WRAP virtual int getNOctaveLayers() const = 0;
  634. CV_WRAP virtual void setDiffusivity(KAZE::DiffusivityType diff) = 0;
  635. CV_WRAP virtual KAZE::DiffusivityType getDiffusivity() const = 0;
  636. CV_WRAP virtual String getDefaultName() const CV_OVERRIDE;
  637. };
  638. //! @} features2d_main
  639. /****************************************************************************************\
  640. * Distance *
  641. \****************************************************************************************/
  642. template<typename T>
  643. struct CV_EXPORTS Accumulator
  644. {
  645. typedef T Type;
  646. };
  647. template<> struct Accumulator<unsigned char> { typedef float Type; };
  648. template<> struct Accumulator<unsigned short> { typedef float Type; };
  649. template<> struct Accumulator<char> { typedef float Type; };
  650. template<> struct Accumulator<short> { typedef float Type; };
  651. /*
  652. * Squared Euclidean distance functor
  653. */
  654. template<class T>
  655. struct CV_EXPORTS SL2
  656. {
  657. static const NormTypes normType = NORM_L2SQR;
  658. typedef T ValueType;
  659. typedef typename Accumulator<T>::Type ResultType;
  660. ResultType operator()( const T* a, const T* b, int size ) const
  661. {
  662. return normL2Sqr<ValueType, ResultType>(a, b, size);
  663. }
  664. };
  665. /*
  666. * Euclidean distance functor
  667. */
  668. template<class T>
  669. struct L2
  670. {
  671. static const NormTypes normType = NORM_L2;
  672. typedef T ValueType;
  673. typedef typename Accumulator<T>::Type ResultType;
  674. ResultType operator()( const T* a, const T* b, int size ) const
  675. {
  676. return (ResultType)std::sqrt((double)normL2Sqr<ValueType, ResultType>(a, b, size));
  677. }
  678. };
  679. /*
  680. * Manhattan distance (city block distance) functor
  681. */
  682. template<class T>
  683. struct L1
  684. {
  685. static const NormTypes normType = NORM_L1;
  686. typedef T ValueType;
  687. typedef typename Accumulator<T>::Type ResultType;
  688. ResultType operator()( const T* a, const T* b, int size ) const
  689. {
  690. return normL1<ValueType, ResultType>(a, b, size);
  691. }
  692. };
  693. /****************************************************************************************\
  694. * DescriptorMatcher *
  695. \****************************************************************************************/
  696. //! @addtogroup features2d_match
  697. //! @{
  698. /** @brief Abstract base class for matching keypoint descriptors.
  699. It has two groups of match methods: for matching descriptors of an image with another image or with
  700. an image set.
  701. */
  702. class CV_EXPORTS_W DescriptorMatcher : public Algorithm
  703. {
  704. public:
  705. enum MatcherType
  706. {
  707. FLANNBASED = 1,
  708. BRUTEFORCE = 2,
  709. BRUTEFORCE_L1 = 3,
  710. BRUTEFORCE_HAMMING = 4,
  711. BRUTEFORCE_HAMMINGLUT = 5,
  712. BRUTEFORCE_SL2 = 6
  713. };
  714. virtual ~DescriptorMatcher();
  715. /** @brief Adds descriptors to train a CPU(trainDescCollectionis) or GPU(utrainDescCollectionis) descriptor
  716. collection.
  717. If the collection is not empty, the new descriptors are added to existing train descriptors.
  718. @param descriptors Descriptors to add. Each descriptors[i] is a set of descriptors from the same
  719. train image.
  720. */
  721. CV_WRAP virtual void add( InputArrayOfArrays descriptors );
  722. /** @brief Returns a constant link to the train descriptor collection trainDescCollection .
  723. */
  724. CV_WRAP const std::vector<Mat>& getTrainDescriptors() const;
  725. /** @brief Clears the train descriptor collections.
  726. */
  727. CV_WRAP virtual void clear() CV_OVERRIDE;
  728. /** @brief Returns true if there are no train descriptors in the both collections.
  729. */
  730. CV_WRAP virtual bool empty() const CV_OVERRIDE;
  731. /** @brief Returns true if the descriptor matcher supports masking permissible matches.
  732. */
  733. CV_WRAP virtual bool isMaskSupported() const = 0;
  734. /** @brief Trains a descriptor matcher
  735. Trains a descriptor matcher (for example, the flann index). In all methods to match, the method
  736. train() is run every time before matching. Some descriptor matchers (for example, BruteForceMatcher)
  737. have an empty implementation of this method. Other matchers really train their inner structures (for
  738. example, FlannBasedMatcher trains flann::Index ).
  739. */
  740. CV_WRAP virtual void train();
  741. /** @brief Finds the best match for each descriptor from a query set.
  742. @param queryDescriptors Query set of descriptors.
  743. @param trainDescriptors Train set of descriptors. This set is not added to the train descriptors
  744. collection stored in the class object.
  745. @param matches Matches. If a query descriptor is masked out in mask , no match is added for this
  746. descriptor. So, matches size may be smaller than the query descriptors count.
  747. @param mask Mask specifying permissible matches between an input query and train matrices of
  748. descriptors.
  749. In the first variant of this method, the train descriptors are passed as an input argument. In the
  750. second variant of the method, train descriptors collection that was set by DescriptorMatcher::add is
  751. used. Optional mask (or masks) can be passed to specify which query and training descriptors can be
  752. matched. Namely, queryDescriptors[i] can be matched with trainDescriptors[j] only if
  753. mask.at\<uchar\>(i,j) is non-zero.
  754. */
  755. CV_WRAP void match( InputArray queryDescriptors, InputArray trainDescriptors,
  756. CV_OUT std::vector<DMatch>& matches, InputArray mask=noArray() ) const;
  757. /** @brief Finds the k best matches for each descriptor from a query set.
  758. @param queryDescriptors Query set of descriptors.
  759. @param trainDescriptors Train set of descriptors. This set is not added to the train descriptors
  760. collection stored in the class object.
  761. @param mask Mask specifying permissible matches between an input query and train matrices of
  762. descriptors.
  763. @param matches Matches. Each matches[i] is k or less matches for the same query descriptor.
  764. @param k Count of best matches found per each query descriptor or less if a query descriptor has
  765. less than k possible matches in total.
  766. @param compactResult Parameter used when the mask (or masks) is not empty. If compactResult is
  767. false, the matches vector has the same size as queryDescriptors rows. If compactResult is true,
  768. the matches vector does not contain matches for fully masked-out query descriptors.
  769. These extended variants of DescriptorMatcher::match methods find several best matches for each query
  770. descriptor. The matches are returned in the distance increasing order. See DescriptorMatcher::match
  771. for the details about query and train descriptors.
  772. */
  773. CV_WRAP void knnMatch( InputArray queryDescriptors, InputArray trainDescriptors,
  774. CV_OUT std::vector<std::vector<DMatch> >& matches, int k,
  775. InputArray mask=noArray(), bool compactResult=false ) const;
  776. /** @brief For each query descriptor, finds the training descriptors not farther than the specified distance.
  777. @param queryDescriptors Query set of descriptors.
  778. @param trainDescriptors Train set of descriptors. This set is not added to the train descriptors
  779. collection stored in the class object.
  780. @param matches Found matches.
  781. @param compactResult Parameter used when the mask (or masks) is not empty. If compactResult is
  782. false, the matches vector has the same size as queryDescriptors rows. If compactResult is true,
  783. the matches vector does not contain matches for fully masked-out query descriptors.
  784. @param maxDistance Threshold for the distance between matched descriptors. Distance means here
  785. metric distance (e.g. Hamming distance), not the distance between coordinates (which is measured
  786. in Pixels)!
  787. @param mask Mask specifying permissible matches between an input query and train matrices of
  788. descriptors.
  789. For each query descriptor, the methods find such training descriptors that the distance between the
  790. query descriptor and the training descriptor is equal or smaller than maxDistance. Found matches are
  791. returned in the distance increasing order.
  792. */
  793. CV_WRAP void radiusMatch( InputArray queryDescriptors, InputArray trainDescriptors,
  794. CV_OUT std::vector<std::vector<DMatch> >& matches, float maxDistance,
  795. InputArray mask=noArray(), bool compactResult=false ) const;
  796. /** @overload
  797. @param queryDescriptors Query set of descriptors.
  798. @param matches Matches. If a query descriptor is masked out in mask , no match is added for this
  799. descriptor. So, matches size may be smaller than the query descriptors count.
  800. @param masks Set of masks. Each masks[i] specifies permissible matches between the input query
  801. descriptors and stored train descriptors from the i-th image trainDescCollection[i].
  802. */
  803. CV_WRAP void match( InputArray queryDescriptors, CV_OUT std::vector<DMatch>& matches,
  804. InputArrayOfArrays masks=noArray() );
  805. /** @overload
  806. @param queryDescriptors Query set of descriptors.
  807. @param matches Matches. Each matches[i] is k or less matches for the same query descriptor.
  808. @param k Count of best matches found per each query descriptor or less if a query descriptor has
  809. less than k possible matches in total.
  810. @param masks Set of masks. Each masks[i] specifies permissible matches between the input query
  811. descriptors and stored train descriptors from the i-th image trainDescCollection[i].
  812. @param compactResult Parameter used when the mask (or masks) is not empty. If compactResult is
  813. false, the matches vector has the same size as queryDescriptors rows. If compactResult is true,
  814. the matches vector does not contain matches for fully masked-out query descriptors.
  815. */
  816. CV_WRAP void knnMatch( InputArray queryDescriptors, CV_OUT std::vector<std::vector<DMatch> >& matches, int k,
  817. InputArrayOfArrays masks=noArray(), bool compactResult=false );
  818. /** @overload
  819. @param queryDescriptors Query set of descriptors.
  820. @param matches Found matches.
  821. @param maxDistance Threshold for the distance between matched descriptors. Distance means here
  822. metric distance (e.g. Hamming distance), not the distance between coordinates (which is measured
  823. in Pixels)!
  824. @param masks Set of masks. Each masks[i] specifies permissible matches between the input query
  825. descriptors and stored train descriptors from the i-th image trainDescCollection[i].
  826. @param compactResult Parameter used when the mask (or masks) is not empty. If compactResult is
  827. false, the matches vector has the same size as queryDescriptors rows. If compactResult is true,
  828. the matches vector does not contain matches for fully masked-out query descriptors.
  829. */
  830. CV_WRAP void radiusMatch( InputArray queryDescriptors, CV_OUT std::vector<std::vector<DMatch> >& matches, float maxDistance,
  831. InputArrayOfArrays masks=noArray(), bool compactResult=false );
  832. CV_WRAP void write( const String& fileName ) const
  833. {
  834. FileStorage fs(fileName, FileStorage::WRITE);
  835. write(fs);
  836. }
  837. CV_WRAP void read( const String& fileName )
  838. {
  839. FileStorage fs(fileName, FileStorage::READ);
  840. read(fs.root());
  841. }
  842. // Reads matcher object from a file node
  843. // see corresponding cv::Algorithm method
  844. CV_WRAP virtual void read( const FileNode& ) CV_OVERRIDE;
  845. // Writes matcher object to a file storage
  846. virtual void write( FileStorage& ) const CV_OVERRIDE;
  847. /** @brief Clones the matcher.
  848. @param emptyTrainData If emptyTrainData is false, the method creates a deep copy of the object,
  849. that is, copies both parameters and train data. If emptyTrainData is true, the method creates an
  850. object copy with the current parameters but with empty train data.
  851. */
  852. CV_WRAP virtual Ptr<DescriptorMatcher> clone( bool emptyTrainData=false ) const = 0;
  853. /** @brief Creates a descriptor matcher of a given type with the default parameters (using default
  854. constructor).
  855. @param descriptorMatcherType Descriptor matcher type. Now the following matcher types are
  856. supported:
  857. - `BruteForce` (it uses L2 )
  858. - `BruteForce-L1`
  859. - `BruteForce-Hamming`
  860. - `BruteForce-Hamming(2)`
  861. - `FlannBased`
  862. */
  863. CV_WRAP static Ptr<DescriptorMatcher> create( const String& descriptorMatcherType );
  864. CV_WRAP static Ptr<DescriptorMatcher> create( const DescriptorMatcher::MatcherType& matcherType );
  865. // see corresponding cv::Algorithm method
  866. CV_WRAP inline void write(const Ptr<FileStorage>& fs, const String& name = String()) const { Algorithm::write(fs, name); }
  867. protected:
  868. /**
  869. * Class to work with descriptors from several images as with one merged matrix.
  870. * It is used e.g. in FlannBasedMatcher.
  871. */
  872. class CV_EXPORTS DescriptorCollection
  873. {
  874. public:
  875. DescriptorCollection();
  876. DescriptorCollection( const DescriptorCollection& collection );
  877. virtual ~DescriptorCollection();
  878. // Vector of matrices "descriptors" will be merged to one matrix "mergedDescriptors" here.
  879. void set( const std::vector<Mat>& descriptors );
  880. virtual void clear();
  881. const Mat& getDescriptors() const;
  882. const Mat getDescriptor( int imgIdx, int localDescIdx ) const;
  883. const Mat getDescriptor( int globalDescIdx ) const;
  884. void getLocalIdx( int globalDescIdx, int& imgIdx, int& localDescIdx ) const;
  885. int size() const;
  886. protected:
  887. Mat mergedDescriptors;
  888. std::vector<int> startIdxs;
  889. };
  890. //! In fact the matching is implemented only by the following two methods. These methods suppose
  891. //! that the class object has been trained already. Public match methods call these methods
  892. //! after calling train().
  893. virtual void knnMatchImpl( InputArray queryDescriptors, std::vector<std::vector<DMatch> >& matches, int k,
  894. InputArrayOfArrays masks=noArray(), bool compactResult=false ) = 0;
  895. virtual void radiusMatchImpl( InputArray queryDescriptors, std::vector<std::vector<DMatch> >& matches, float maxDistance,
  896. InputArrayOfArrays masks=noArray(), bool compactResult=false ) = 0;
  897. static bool isPossibleMatch( InputArray mask, int queryIdx, int trainIdx );
  898. static bool isMaskedOut( InputArrayOfArrays masks, int queryIdx );
  899. static Mat clone_op( Mat m ) { return m.clone(); }
  900. void checkMasks( InputArrayOfArrays masks, int queryDescriptorsCount ) const;
  901. //! Collection of descriptors from train images.
  902. std::vector<Mat> trainDescCollection;
  903. std::vector<UMat> utrainDescCollection;
  904. };
  905. /** @brief Brute-force descriptor matcher.
  906. For each descriptor in the first set, this matcher finds the closest descriptor in the second set
  907. by trying each one. This descriptor matcher supports masking permissible matches of descriptor
  908. sets.
  909. */
  910. class CV_EXPORTS_W BFMatcher : public DescriptorMatcher
  911. {
  912. public:
  913. /** @brief Brute-force matcher constructor (obsolete). Please use BFMatcher.create()
  914. *
  915. *
  916. */
  917. CV_WRAP BFMatcher( int normType=NORM_L2, bool crossCheck=false );
  918. virtual ~BFMatcher() {}
  919. virtual bool isMaskSupported() const CV_OVERRIDE { return true; }
  920. /** @brief Brute-force matcher create method.
  921. @param normType One of NORM_L1, NORM_L2, NORM_HAMMING, NORM_HAMMING2. L1 and L2 norms are
  922. preferable choices for SIFT and SURF descriptors, NORM_HAMMING should be used with ORB, BRISK and
  923. BRIEF, NORM_HAMMING2 should be used with ORB when WTA_K==3 or 4 (see ORB::ORB constructor
  924. description).
  925. @param crossCheck If it is false, this is will be default BFMatcher behaviour when it finds the k
  926. nearest neighbors for each query descriptor. If crossCheck==true, then the knnMatch() method with
  927. k=1 will only return pairs (i,j) such that for i-th query descriptor the j-th descriptor in the
  928. matcher's collection is the nearest and vice versa, i.e. the BFMatcher will only return consistent
  929. pairs. Such technique usually produces best results with minimal number of outliers when there are
  930. enough matches. This is alternative to the ratio test, used by D. Lowe in SIFT paper.
  931. */
  932. CV_WRAP static Ptr<BFMatcher> create( int normType=NORM_L2, bool crossCheck=false ) ;
  933. virtual Ptr<DescriptorMatcher> clone( bool emptyTrainData=false ) const CV_OVERRIDE;
  934. protected:
  935. virtual void knnMatchImpl( InputArray queryDescriptors, std::vector<std::vector<DMatch> >& matches, int k,
  936. InputArrayOfArrays masks=noArray(), bool compactResult=false ) CV_OVERRIDE;
  937. virtual void radiusMatchImpl( InputArray queryDescriptors, std::vector<std::vector<DMatch> >& matches, float maxDistance,
  938. InputArrayOfArrays masks=noArray(), bool compactResult=false ) CV_OVERRIDE;
  939. int normType;
  940. bool crossCheck;
  941. };
  942. #if defined(HAVE_OPENCV_FLANN) || defined(CV_DOXYGEN)
  943. /** @brief Flann-based descriptor matcher.
  944. This matcher trains cv::flann::Index on a train descriptor collection and calls its nearest search
  945. methods to find the best matches. So, this matcher may be faster when matching a large train
  946. collection than the brute force matcher. FlannBasedMatcher does not support masking permissible
  947. matches of descriptor sets because flann::Index does not support this. :
  948. */
  949. class CV_EXPORTS_W FlannBasedMatcher : public DescriptorMatcher
  950. {
  951. public:
  952. CV_WRAP FlannBasedMatcher( const Ptr<flann::IndexParams>& indexParams=makePtr<flann::KDTreeIndexParams>(),
  953. const Ptr<flann::SearchParams>& searchParams=makePtr<flann::SearchParams>() );
  954. virtual void add( InputArrayOfArrays descriptors ) CV_OVERRIDE;
  955. virtual void clear() CV_OVERRIDE;
  956. // Reads matcher object from a file node
  957. virtual void read( const FileNode& ) CV_OVERRIDE;
  958. // Writes matcher object to a file storage
  959. virtual void write( FileStorage& ) const CV_OVERRIDE;
  960. virtual void train() CV_OVERRIDE;
  961. virtual bool isMaskSupported() const CV_OVERRIDE;
  962. CV_WRAP static Ptr<FlannBasedMatcher> create();
  963. virtual Ptr<DescriptorMatcher> clone( bool emptyTrainData=false ) const CV_OVERRIDE;
  964. protected:
  965. static void convertToDMatches( const DescriptorCollection& descriptors,
  966. const Mat& indices, const Mat& distances,
  967. std::vector<std::vector<DMatch> >& matches );
  968. virtual void knnMatchImpl( InputArray queryDescriptors, std::vector<std::vector<DMatch> >& matches, int k,
  969. InputArrayOfArrays masks=noArray(), bool compactResult=false ) CV_OVERRIDE;
  970. virtual void radiusMatchImpl( InputArray queryDescriptors, std::vector<std::vector<DMatch> >& matches, float maxDistance,
  971. InputArrayOfArrays masks=noArray(), bool compactResult=false ) CV_OVERRIDE;
  972. Ptr<flann::IndexParams> indexParams;
  973. Ptr<flann::SearchParams> searchParams;
  974. Ptr<flann::Index> flannIndex;
  975. DescriptorCollection mergedDescriptors;
  976. int addedDescCount;
  977. };
  978. #endif
  979. //! @} features2d_match
  980. /****************************************************************************************\
  981. * Drawing functions *
  982. \****************************************************************************************/
  983. //! @addtogroup features2d_draw
  984. //! @{
  985. enum struct DrawMatchesFlags
  986. {
  987. DEFAULT = 0, //!< Output image matrix will be created (Mat::create),
  988. //!< i.e. existing memory of output image may be reused.
  989. //!< Two source image, matches and single keypoints will be drawn.
  990. //!< For each keypoint only the center point will be drawn (without
  991. //!< the circle around keypoint with keypoint size and orientation).
  992. DRAW_OVER_OUTIMG = 1, //!< Output image matrix will not be created (Mat::create).
  993. //!< Matches will be drawn on existing content of output image.
  994. NOT_DRAW_SINGLE_POINTS = 2, //!< Single keypoints will not be drawn.
  995. DRAW_RICH_KEYPOINTS = 4 //!< For each keypoint the circle around keypoint with keypoint size and
  996. //!< orientation will be drawn.
  997. };
  998. CV_ENUM_FLAGS(DrawMatchesFlags)
  999. /** @brief Draws keypoints.
  1000. @param image Source image.
  1001. @param keypoints Keypoints from the source image.
  1002. @param outImage Output image. Its content depends on the flags value defining what is drawn in the
  1003. output image. See possible flags bit values below.
  1004. @param color Color of keypoints.
  1005. @param flags Flags setting drawing features. Possible flags bit values are defined by
  1006. DrawMatchesFlags. See details above in drawMatches .
  1007. @note
  1008. For Python API, flags are modified as cv.DRAW_MATCHES_FLAGS_DEFAULT,
  1009. cv.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS, cv.DRAW_MATCHES_FLAGS_DRAW_OVER_OUTIMG,
  1010. cv.DRAW_MATCHES_FLAGS_NOT_DRAW_SINGLE_POINTS
  1011. */
  1012. CV_EXPORTS_W void drawKeypoints( InputArray image, const std::vector<KeyPoint>& keypoints, InputOutputArray outImage,
  1013. const Scalar& color=Scalar::all(-1), DrawMatchesFlags flags=DrawMatchesFlags::DEFAULT );
  1014. /** @brief Draws the found matches of keypoints from two images.
  1015. @param img1 First source image.
  1016. @param keypoints1 Keypoints from the first source image.
  1017. @param img2 Second source image.
  1018. @param keypoints2 Keypoints from the second source image.
  1019. @param matches1to2 Matches from the first image to the second one, which means that keypoints1[i]
  1020. has a corresponding point in keypoints2[matches[i]] .
  1021. @param outImg Output image. Its content depends on the flags value defining what is drawn in the
  1022. output image. See possible flags bit values below.
  1023. @param matchColor Color of matches (lines and connected keypoints). If matchColor==Scalar::all(-1)
  1024. , the color is generated randomly.
  1025. @param singlePointColor Color of single keypoints (circles), which means that keypoints do not
  1026. have the matches. If singlePointColor==Scalar::all(-1) , the color is generated randomly.
  1027. @param matchesMask Mask determining which matches are drawn. If the mask is empty, all matches are
  1028. drawn.
  1029. @param flags Flags setting drawing features. Possible flags bit values are defined by
  1030. DrawMatchesFlags.
  1031. This function draws matches of keypoints from two images in the output image. Match is a line
  1032. connecting two keypoints (circles). See cv::DrawMatchesFlags.
  1033. */
  1034. CV_EXPORTS_W void drawMatches( InputArray img1, const std::vector<KeyPoint>& keypoints1,
  1035. InputArray img2, const std::vector<KeyPoint>& keypoints2,
  1036. const std::vector<DMatch>& matches1to2, InputOutputArray outImg,
  1037. const Scalar& matchColor=Scalar::all(-1), const Scalar& singlePointColor=Scalar::all(-1),
  1038. const std::vector<char>& matchesMask=std::vector<char>(), DrawMatchesFlags flags=DrawMatchesFlags::DEFAULT );
  1039. /** @overload */
  1040. CV_EXPORTS_AS(drawMatchesKnn) void drawMatches( InputArray img1, const std::vector<KeyPoint>& keypoints1,
  1041. InputArray img2, const std::vector<KeyPoint>& keypoints2,
  1042. const std::vector<std::vector<DMatch> >& matches1to2, InputOutputArray outImg,
  1043. const Scalar& matchColor=Scalar::all(-1), const Scalar& singlePointColor=Scalar::all(-1),
  1044. const std::vector<std::vector<char> >& matchesMask=std::vector<std::vector<char> >(), DrawMatchesFlags flags=DrawMatchesFlags::DEFAULT );
  1045. //! @} features2d_draw
  1046. /****************************************************************************************\
  1047. * Functions to evaluate the feature detectors and [generic] descriptor extractors *
  1048. \****************************************************************************************/
  1049. CV_EXPORTS void evaluateFeatureDetector( const Mat& img1, const Mat& img2, const Mat& H1to2,
  1050. std::vector<KeyPoint>* keypoints1, std::vector<KeyPoint>* keypoints2,
  1051. float& repeatability, int& correspCount,
  1052. const Ptr<FeatureDetector>& fdetector=Ptr<FeatureDetector>() );
  1053. CV_EXPORTS void computeRecallPrecisionCurve( const std::vector<std::vector<DMatch> >& matches1to2,
  1054. const std::vector<std::vector<uchar> >& correctMatches1to2Mask,
  1055. std::vector<Point2f>& recallPrecisionCurve );
  1056. CV_EXPORTS float getRecall( const std::vector<Point2f>& recallPrecisionCurve, float l_precision );
  1057. CV_EXPORTS int getNearestPoint( const std::vector<Point2f>& recallPrecisionCurve, float l_precision );
  1058. /****************************************************************************************\
  1059. * Bag of visual words *
  1060. \****************************************************************************************/
  1061. //! @addtogroup features2d_category
  1062. //! @{
  1063. /** @brief Abstract base class for training the *bag of visual words* vocabulary from a set of descriptors.
  1064. For details, see, for example, *Visual Categorization with Bags of Keypoints* by Gabriella Csurka,
  1065. Christopher R. Dance, Lixin Fan, Jutta Willamowski, Cedric Bray, 2004. :
  1066. */
  1067. class CV_EXPORTS_W BOWTrainer
  1068. {
  1069. public:
  1070. BOWTrainer();
  1071. virtual ~BOWTrainer();
  1072. /** @brief Adds descriptors to a training set.
  1073. @param descriptors Descriptors to add to a training set. Each row of the descriptors matrix is a
  1074. descriptor.
  1075. The training set is clustered using clustermethod to construct the vocabulary.
  1076. */
  1077. CV_WRAP void add( const Mat& descriptors );
  1078. /** @brief Returns a training set of descriptors.
  1079. */
  1080. CV_WRAP const std::vector<Mat>& getDescriptors() const;
  1081. /** @brief Returns the count of all descriptors stored in the training set.
  1082. */
  1083. CV_WRAP int descriptorsCount() const;
  1084. CV_WRAP virtual void clear();
  1085. /** @overload */
  1086. CV_WRAP virtual Mat cluster() const = 0;
  1087. /** @brief Clusters train descriptors.
  1088. @param descriptors Descriptors to cluster. Each row of the descriptors matrix is a descriptor.
  1089. Descriptors are not added to the inner train descriptor set.
  1090. The vocabulary consists of cluster centers. So, this method returns the vocabulary. In the first
  1091. variant of the method, train descriptors stored in the object are clustered. In the second variant,
  1092. input descriptors are clustered.
  1093. */
  1094. CV_WRAP virtual Mat cluster( const Mat& descriptors ) const = 0;
  1095. protected:
  1096. std::vector<Mat> descriptors;
  1097. int size;
  1098. };
  1099. /** @brief kmeans -based class to train visual vocabulary using the *bag of visual words* approach. :
  1100. */
  1101. class CV_EXPORTS_W BOWKMeansTrainer : public BOWTrainer
  1102. {
  1103. public:
  1104. /** @brief The constructor.
  1105. @see cv::kmeans
  1106. */
  1107. CV_WRAP BOWKMeansTrainer( int clusterCount, const TermCriteria& termcrit=TermCriteria(),
  1108. int attempts=3, int flags=KMEANS_PP_CENTERS );
  1109. virtual ~BOWKMeansTrainer();
  1110. // Returns trained vocabulary (i.e. cluster centers).
  1111. CV_WRAP virtual Mat cluster() const CV_OVERRIDE;
  1112. CV_WRAP virtual Mat cluster( const Mat& descriptors ) const CV_OVERRIDE;
  1113. protected:
  1114. int clusterCount;
  1115. TermCriteria termcrit;
  1116. int attempts;
  1117. int flags;
  1118. };
  1119. /** @brief Class to compute an image descriptor using the *bag of visual words*.
  1120. Such a computation consists of the following steps:
  1121. 1. Compute descriptors for a given image and its keypoints set.
  1122. 2. Find the nearest visual words from the vocabulary for each keypoint descriptor.
  1123. 3. Compute the bag-of-words image descriptor as is a normalized histogram of vocabulary words
  1124. encountered in the image. The i-th bin of the histogram is a frequency of i-th word of the
  1125. vocabulary in the given image.
  1126. */
  1127. class CV_EXPORTS_W BOWImgDescriptorExtractor
  1128. {
  1129. public:
  1130. /** @brief The constructor.
  1131. @param dextractor Descriptor extractor that is used to compute descriptors for an input image and
  1132. its keypoints.
  1133. @param dmatcher Descriptor matcher that is used to find the nearest word of the trained vocabulary
  1134. for each keypoint descriptor of the image.
  1135. */
  1136. CV_WRAP BOWImgDescriptorExtractor( const Ptr<DescriptorExtractor>& dextractor,
  1137. const Ptr<DescriptorMatcher>& dmatcher );
  1138. /** @overload */
  1139. BOWImgDescriptorExtractor( const Ptr<DescriptorMatcher>& dmatcher );
  1140. virtual ~BOWImgDescriptorExtractor();
  1141. /** @brief Sets a visual vocabulary.
  1142. @param vocabulary Vocabulary (can be trained using the inheritor of BOWTrainer ). Each row of the
  1143. vocabulary is a visual word (cluster center).
  1144. */
  1145. CV_WRAP void setVocabulary( const Mat& vocabulary );
  1146. /** @brief Returns the set vocabulary.
  1147. */
  1148. CV_WRAP const Mat& getVocabulary() const;
  1149. /** @brief Computes an image descriptor using the set visual vocabulary.
  1150. @param image Image, for which the descriptor is computed.
  1151. @param keypoints Keypoints detected in the input image.
  1152. @param imgDescriptor Computed output image descriptor.
  1153. @param pointIdxsOfClusters Indices of keypoints that belong to the cluster. This means that
  1154. pointIdxsOfClusters[i] are keypoint indices that belong to the i -th cluster (word of vocabulary)
  1155. returned if it is non-zero.
  1156. @param descriptors Descriptors of the image keypoints that are returned if they are non-zero.
  1157. */
  1158. void compute( InputArray image, std::vector<KeyPoint>& keypoints, OutputArray imgDescriptor,
  1159. std::vector<std::vector<int> >* pointIdxsOfClusters=0, Mat* descriptors=0 );
  1160. /** @overload
  1161. @param keypointDescriptors Computed descriptors to match with vocabulary.
  1162. @param imgDescriptor Computed output image descriptor.
  1163. @param pointIdxsOfClusters Indices of keypoints that belong to the cluster. This means that
  1164. pointIdxsOfClusters[i] are keypoint indices that belong to the i -th cluster (word of vocabulary)
  1165. returned if it is non-zero.
  1166. */
  1167. void compute( InputArray keypointDescriptors, OutputArray imgDescriptor,
  1168. std::vector<std::vector<int> >* pointIdxsOfClusters=0 );
  1169. // compute() is not constant because DescriptorMatcher::match is not constant
  1170. CV_WRAP_AS(compute) void compute2( const Mat& image, std::vector<KeyPoint>& keypoints, CV_OUT Mat& imgDescriptor )
  1171. { compute(image,keypoints,imgDescriptor); }
  1172. /** @brief Returns an image descriptor size if the vocabulary is set. Otherwise, it returns 0.
  1173. */
  1174. CV_WRAP int descriptorSize() const;
  1175. /** @brief Returns an image descriptor type.
  1176. */
  1177. CV_WRAP int descriptorType() const;
  1178. protected:
  1179. Mat vocabulary;
  1180. Ptr<DescriptorExtractor> dextractor;
  1181. Ptr<DescriptorMatcher> dmatcher;
  1182. };
  1183. //! @} features2d_category
  1184. //! @} features2d
  1185. } /* namespace cv */
  1186. #endif