features2d.hpp 68 KB

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