features2d.hpp 65 KB

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