features2d.hpp 63 KB

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