some more changes
[profile/ivi/opencv.git] / modules / features2d / include / opencv2 / features2d.hpp
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
43 #ifndef __OPENCV_FEATURES_2D_HPP__
44 #define __OPENCV_FEATURES_2D_HPP__
45
46 #include "opencv2/core.hpp"
47 #include "opencv2/flann/miniflann.hpp"
48
49 namespace cv
50 {
51
52 CV_EXPORTS bool initModule_features2d();
53
54 // //! writes vector of keypoints to the file storage
55 // CV_EXPORTS void write(FileStorage& fs, const String& name, const std::vector<KeyPoint>& keypoints);
56 // //! reads vector of keypoints from the specified file storage node
57 // CV_EXPORTS void read(const FileNode& node, CV_OUT std::vector<KeyPoint>& keypoints);
58
59 /*
60  * A class filters a vector of keypoints.
61  * Because now it is difficult to provide a convenient interface for all usage scenarios of the keypoints filter class,
62  * it has only several needed by now static methods.
63  */
64 class CV_EXPORTS KeyPointsFilter
65 {
66 public:
67     KeyPointsFilter(){}
68
69     /*
70      * Remove keypoints within borderPixels of an image edge.
71      */
72     static void runByImageBorder( std::vector<KeyPoint>& keypoints, Size imageSize, int borderSize );
73     /*
74      * Remove keypoints of sizes out of range.
75      */
76     static void runByKeypointSize( std::vector<KeyPoint>& keypoints, float minSize,
77                                    float maxSize=FLT_MAX );
78     /*
79      * Remove keypoints from some image by mask for pixels of this image.
80      */
81     static void runByPixelsMask( std::vector<KeyPoint>& keypoints, const Mat& mask );
82     /*
83      * Remove duplicated keypoints.
84      */
85     static void removeDuplicated( std::vector<KeyPoint>& keypoints );
86
87     /*
88      * Retain the specified number of the best keypoints (according to the response)
89      */
90     static void retainBest( std::vector<KeyPoint>& keypoints, int npoints );
91 };
92
93
94 /************************************ Base Classes ************************************/
95
96 /*
97  * Abstract base class for 2D image feature detectors.
98  */
99 class CV_EXPORTS_W FeatureDetector : public virtual Algorithm
100 {
101 public:
102     virtual ~FeatureDetector();
103
104     /*
105      * Detect keypoints in an image.
106      * image        The image.
107      * keypoints    The detected keypoints.
108      * mask         Mask specifying where to look for keypoints (optional). Must be a char
109      *              matrix with non-zero values in the region of interest.
110      */
111     CV_WRAP void detect( InputArray image, CV_OUT std::vector<KeyPoint>& keypoints, InputArray mask=noArray() ) const;
112
113     /*
114      * Detect keypoints in an image set.
115      * images       Image collection.
116      * keypoints    Collection of keypoints detected in an input images. keypoints[i] is a set of keypoints detected in an images[i].
117      * masks        Masks for image set. masks[i] is a mask for images[i].
118      */
119     void detect( InputArrayOfArrays images, std::vector<std::vector<KeyPoint> >& keypoints, InputArrayOfArrays masks=noArray() ) const;
120
121     // Return true if detector object is empty
122     CV_WRAP virtual bool empty() const;
123
124     // Create feature detector by detector name.
125     CV_WRAP static Ptr<FeatureDetector> create( const String& detectorType );
126
127 protected:
128     virtual void detectImpl( InputArray image, std::vector<KeyPoint>& keypoints, InputArray mask=noArray() ) const = 0;
129
130     /*
131      * Remove keypoints that are not in the mask.
132      * Helper function, useful when wrapping a library call for keypoint detection that
133      * does not support a mask argument.
134      */
135     static void removeInvalidPoints( const Mat & mask, std::vector<KeyPoint>& keypoints );
136 };
137
138
139 /*
140  * Abstract base class for computing descriptors for image keypoints.
141  *
142  * In this interface we assume a keypoint descriptor can be represented as a
143  * dense, fixed-dimensional vector of some basic type. Most descriptors used
144  * in practice follow this pattern, as it makes it very easy to compute
145  * distances between descriptors. Therefore we represent a collection of
146  * descriptors as a Mat, where each row is one keypoint descriptor.
147  */
148 class CV_EXPORTS_W DescriptorExtractor : public virtual Algorithm
149 {
150 public:
151     virtual ~DescriptorExtractor();
152
153     /*
154      * Compute the descriptors for a set of keypoints in an image.
155      * image        The image.
156      * keypoints    The input keypoints. Keypoints for which a descriptor cannot be computed are removed.
157      * descriptors  Copmputed descriptors. Row i is the descriptor for keypoint i.
158      */
159     CV_WRAP void compute( InputArray image, CV_OUT CV_IN_OUT std::vector<KeyPoint>& keypoints, OutputArray descriptors ) const;
160
161     /*
162      * Compute the descriptors for a keypoints collection detected in image collection.
163      * images       Image collection.
164      * keypoints    Input keypoints collection. keypoints[i] is keypoints detected in images[i].
165      *              Keypoints for which a descriptor cannot be computed are removed.
166      * descriptors  Descriptor collection. descriptors[i] are descriptors computed for set keypoints[i].
167      */
168     void compute( InputArrayOfArrays images, std::vector<std::vector<KeyPoint> >& keypoints, OutputArrayOfArrays descriptors ) const;
169
170     CV_WRAP virtual int descriptorSize() const = 0;
171     CV_WRAP virtual int descriptorType() const = 0;
172     CV_WRAP virtual int defaultNorm() const = 0;
173
174     CV_WRAP virtual bool empty() const;
175
176     CV_WRAP static Ptr<DescriptorExtractor> create( const String& descriptorExtractorType );
177
178 protected:
179     virtual void computeImpl( InputArray image, std::vector<KeyPoint>& keypoints, OutputArray descriptors ) const = 0;
180
181     /*
182      * Remove keypoints within borderPixels of an image edge.
183      */
184     static void removeBorderKeypoints( std::vector<KeyPoint>& keypoints,
185                                       Size imageSize, int borderSize );
186 };
187
188
189
190 /*
191  * Abstract base class for simultaneous 2D feature detection descriptor extraction.
192  */
193 class CV_EXPORTS_W Feature2D : public FeatureDetector, public DescriptorExtractor
194 {
195 public:
196     /*
197      * Detect keypoints in an image.
198      * image        The image.
199      * keypoints    The detected keypoints.
200      * mask         Mask specifying where to look for keypoints (optional). Must be a char
201      *              matrix with non-zero values in the region of interest.
202      * useProvidedKeypoints If true, the method will skip the detection phase and will compute
203      *                      descriptors for the provided keypoints
204      */
205     CV_WRAP_AS(detectAndCompute) virtual void operator()( InputArray image, InputArray mask,
206                                      CV_OUT std::vector<KeyPoint>& keypoints,
207                                      OutputArray descriptors,
208                                      bool useProvidedKeypoints=false ) const = 0;
209
210     CV_WRAP void compute( InputArray image, CV_OUT CV_IN_OUT std::vector<KeyPoint>& keypoints, OutputArray descriptors ) const;
211
212     // Create feature detector and descriptor extractor by name.
213     CV_WRAP static Ptr<Feature2D> create( const String& name );
214 };
215
216 /*!
217   BRISK implementation
218 */
219 class CV_EXPORTS_W BRISK : public Feature2D
220 {
221 public:
222     CV_WRAP explicit BRISK(int thresh=30, int octaves=3, float patternScale=1.0f);
223
224     virtual ~BRISK();
225
226     // returns the descriptor size in bytes
227     int descriptorSize() const;
228     // returns the descriptor type
229     int descriptorType() const;
230     // returns the default norm type
231     int defaultNorm() const;
232
233     // Compute the BRISK features on an image
234     void operator()(InputArray image, InputArray mask, std::vector<KeyPoint>& keypoints) const;
235
236     // Compute the BRISK features and descriptors on an image
237     void operator()( InputArray image, InputArray mask, std::vector<KeyPoint>& keypoints,
238                      OutputArray descriptors, bool useProvidedKeypoints=false ) const;
239
240     AlgorithmInfo* info() const;
241
242     // custom setup
243     CV_WRAP explicit BRISK(std::vector<float> &radiusList, std::vector<int> &numberList,
244         float dMax=5.85f, float dMin=8.2f, std::vector<int> indexChange=std::vector<int>());
245
246     // call this to generate the kernel:
247     // circle of radius r (pixels), with n points;
248     // short pairings with dMax, long pairings with dMin
249     CV_WRAP void generateKernel(std::vector<float> &radiusList,
250         std::vector<int> &numberList, float dMax=5.85f, float dMin=8.2f,
251         std::vector<int> indexChange=std::vector<int>());
252
253 protected:
254
255     void computeImpl( InputArray image, std::vector<KeyPoint>& keypoints, OutputArray descriptors ) const;
256     void detectImpl( InputArray image, std::vector<KeyPoint>& keypoints, InputArray mask=noArray() ) const;
257
258     void computeKeypointsNoOrientation(InputArray image, InputArray mask, std::vector<KeyPoint>& keypoints) const;
259     void computeDescriptorsAndOrOrientation(InputArray image, InputArray mask, std::vector<KeyPoint>& keypoints,
260                                        OutputArray descriptors, bool doDescriptors, bool doOrientation,
261                                        bool useProvidedKeypoints) const;
262
263     // Feature parameters
264     CV_PROP_RW int threshold;
265     CV_PROP_RW int octaves;
266
267     // some helper structures for the Brisk pattern representation
268     struct BriskPatternPoint{
269         float x;         // x coordinate relative to center
270         float y;         // x coordinate relative to center
271         float sigma;     // Gaussian smoothing sigma
272     };
273     struct BriskShortPair{
274         unsigned int i;  // index of the first pattern point
275         unsigned int j;  // index of other pattern point
276     };
277     struct BriskLongPair{
278         unsigned int i;  // index of the first pattern point
279         unsigned int j;  // index of other pattern point
280         int weighted_dx; // 1024.0/dx
281         int weighted_dy; // 1024.0/dy
282     };
283     inline int smoothedIntensity(const cv::Mat& image,
284                 const cv::Mat& integral,const float key_x,
285                 const float key_y, const unsigned int scale,
286                 const unsigned int rot, const unsigned int point) const;
287     // pattern properties
288     BriskPatternPoint* patternPoints_;     //[i][rotation][scale]
289     unsigned int points_;                 // total number of collocation points
290     float* scaleList_;                     // lists the scaling per scale index [scale]
291     unsigned int* sizeList_;             // lists the total pattern size per scale index [scale]
292     static const unsigned int scales_;    // scales discretization
293     static const float scalerange_;     // span of sizes 40->4 Octaves - else, this needs to be adjusted...
294     static const unsigned int n_rot_;    // discretization of the rotation look-up
295
296     // pairs
297     int strings_;                        // number of uchars the descriptor consists of
298     float dMax_;                         // short pair maximum distance
299     float dMin_;                         // long pair maximum distance
300     BriskShortPair* shortPairs_;         // d<_dMax
301     BriskLongPair* longPairs_;             // d>_dMin
302     unsigned int noShortPairs_;         // number of shortParis
303     unsigned int noLongPairs_;             // number of longParis
304
305     // general
306     static const float basicSize_;
307 };
308
309
310 /*!
311  ORB implementation.
312 */
313 class CV_EXPORTS_W ORB : public Feature2D
314 {
315 public:
316     // the size of the signature in bytes
317     enum { kBytes = 32, HARRIS_SCORE=0, FAST_SCORE=1 };
318
319     CV_WRAP explicit ORB(int nfeatures = 500, float scaleFactor = 1.2f, int nlevels = 8, int edgeThreshold = 31,
320         int firstLevel = 0, int WTA_K=2, int scoreType=ORB::HARRIS_SCORE, int patchSize=31 );
321
322     // returns the descriptor size in bytes
323     int descriptorSize() const;
324     // returns the descriptor type
325     int descriptorType() const;
326     // returns the default norm type
327     int defaultNorm() const;
328
329     // Compute the ORB features and descriptors on an image
330     void operator()(InputArray image, InputArray mask, std::vector<KeyPoint>& keypoints) const;
331
332     // Compute the ORB features and descriptors on an image
333     void operator()( InputArray image, InputArray mask, std::vector<KeyPoint>& keypoints,
334                      OutputArray descriptors, bool useProvidedKeypoints=false ) const;
335
336     AlgorithmInfo* info() const;
337
338 protected:
339
340     void computeImpl( InputArray image, std::vector<KeyPoint>& keypoints, OutputArray descriptors ) const;
341     void detectImpl( InputArray image, std::vector<KeyPoint>& keypoints, InputArray mask=noArray() ) const;
342
343     CV_PROP_RW int nfeatures;
344     CV_PROP_RW double scaleFactor;
345     CV_PROP_RW int nlevels;
346     CV_PROP_RW int edgeThreshold;
347     CV_PROP_RW int firstLevel;
348     CV_PROP_RW int WTA_K;
349     CV_PROP_RW int scoreType;
350     CV_PROP_RW int patchSize;
351 };
352
353 typedef ORB OrbFeatureDetector;
354 typedef ORB OrbDescriptorExtractor;
355
356 /*!
357   FREAK implementation
358 */
359 class CV_EXPORTS FREAK : public DescriptorExtractor
360 {
361 public:
362     /** Constructor
363          * @param orientationNormalized enable orientation normalization
364          * @param scaleNormalized enable scale normalization
365          * @param patternScale scaling of the description pattern
366          * @param nbOctave number of octaves covered by the detected keypoints
367          * @param selectedPairs (optional) user defined selected pairs
368     */
369     explicit FREAK( bool orientationNormalized = true,
370            bool scaleNormalized = true,
371            float patternScale = 22.0f,
372            int nOctaves = 4,
373            const std::vector<int>& selectedPairs = std::vector<int>());
374     FREAK( const FREAK& rhs );
375     FREAK& operator=( const FREAK& );
376
377     virtual ~FREAK();
378
379     /** returns the descriptor length in bytes */
380     virtual int descriptorSize() const;
381
382     /** returns the descriptor type */
383     virtual int descriptorType() const;
384
385     /** returns the default norm type */
386     virtual int defaultNorm() const;
387
388     /** select the 512 "best description pairs"
389          * @param images grayscale images set
390          * @param keypoints set of detected keypoints
391          * @param corrThresh correlation threshold
392          * @param verbose print construction information
393          * @return list of best pair indexes
394     */
395     std::vector<int> selectPairs( const std::vector<Mat>& images, std::vector<std::vector<KeyPoint> >& keypoints,
396                       const double corrThresh = 0.7, bool verbose = true );
397
398     AlgorithmInfo* info() const;
399
400     enum
401     {
402         NB_SCALES = 64, NB_PAIRS = 512, NB_ORIENPAIRS = 45
403     };
404
405 protected:
406     virtual void computeImpl( InputArray image, std::vector<KeyPoint>& keypoints, OutputArray descriptors ) const;
407     void buildPattern();
408     uchar meanIntensity( InputArray image, InputArray integral, const float kp_x, const float kp_y,
409                          const unsigned int scale, const unsigned int rot, const unsigned int point ) const;
410
411     bool orientationNormalized; //true if the orientation is normalized, false otherwise
412     bool scaleNormalized; //true if the scale is normalized, false otherwise
413     double patternScale; //scaling of the pattern
414     int nOctaves; //number of octaves
415     bool extAll; // true if all pairs need to be extracted for pairs selection
416
417     double patternScale0;
418     int nOctaves0;
419     std::vector<int> selectedPairs0;
420
421     struct PatternPoint
422     {
423         float x; // x coordinate relative to center
424         float y; // x coordinate relative to center
425         float sigma; // Gaussian smoothing sigma
426     };
427
428     struct DescriptionPair
429     {
430         uchar i; // index of the first point
431         uchar j; // index of the second point
432     };
433
434     struct OrientationPair
435     {
436         uchar i; // index of the first point
437         uchar j; // index of the second point
438         int weight_dx; // dx/(norm_sq))*4096
439         int weight_dy; // dy/(norm_sq))*4096
440     };
441
442     std::vector<PatternPoint> patternLookup; // look-up table for the pattern points (position+sigma of all points at all scales and orientation)
443     int patternSizes[NB_SCALES]; // size of the pattern at a specific scale (used to check if a point is within image boundaries)
444     DescriptionPair descriptionPairs[NB_PAIRS];
445     OrientationPair orientationPairs[NB_ORIENPAIRS];
446 };
447
448
449 /*!
450  Maximal Stable Extremal Regions class.
451
452  The class implements MSER algorithm introduced by J. Matas.
453  Unlike SIFT, SURF and many other detectors in OpenCV, this is salient region detector,
454  not the salient point detector.
455
456  It returns the regions, each of those is encoded as a contour.
457 */
458 class CV_EXPORTS_W MSER : public FeatureDetector
459 {
460 public:
461     //! the full constructor
462     CV_WRAP explicit MSER( int _delta=5, int _min_area=60, int _max_area=14400,
463           double _max_variation=0.25, double _min_diversity=.2,
464           int _max_evolution=200, double _area_threshold=1.01,
465           double _min_margin=0.003, int _edge_blur_size=5 );
466
467     //! the operator that extracts the MSERs from the image or the specific part of it
468     CV_WRAP_AS(detect) void operator()( InputArray image, CV_OUT std::vector<std::vector<Point> >& msers,
469                                         InputArray mask=noArray() ) const;
470     AlgorithmInfo* info() const;
471
472 protected:
473     void detectImpl( InputArray image, std::vector<KeyPoint>& keypoints, InputArray mask=noArray() ) const;
474
475     int delta;
476     int minArea;
477     int maxArea;
478     double maxVariation;
479     double minDiversity;
480     int maxEvolution;
481     double areaThreshold;
482     double minMargin;
483     int edgeBlurSize;
484 };
485
486 typedef MSER MserFeatureDetector;
487
488 /*!
489  The "Star" Detector.
490
491  The class implements the keypoint detector introduced by K. Konolige.
492 */
493 class CV_EXPORTS_W StarDetector : public FeatureDetector
494 {
495 public:
496     //! the full constructor
497     CV_WRAP StarDetector(int _maxSize=45, int _responseThreshold=30,
498                  int _lineThresholdProjected=10,
499                  int _lineThresholdBinarized=8,
500                  int _suppressNonmaxSize=5);
501
502     //! finds the keypoints in the image
503     CV_WRAP_AS(detect) void operator()(const Mat& image,
504                 CV_OUT std::vector<KeyPoint>& keypoints) const;
505
506     AlgorithmInfo* info() const;
507
508 protected:
509     void detectImpl( InputArray image, std::vector<KeyPoint>& keypoints, InputArray mask=noArray() ) const;
510
511     int maxSize;
512     int responseThreshold;
513     int lineThresholdProjected;
514     int lineThresholdBinarized;
515     int suppressNonmaxSize;
516 };
517
518 //! detects corners using FAST algorithm by E. Rosten
519 CV_EXPORTS void FAST( InputArray image, CV_OUT std::vector<KeyPoint>& keypoints,
520                       int threshold, bool nonmaxSupression=true );
521
522 CV_EXPORTS void FAST( InputArray image, CV_OUT std::vector<KeyPoint>& keypoints,
523                       int threshold, bool nonmaxSupression, int type );
524
525 class CV_EXPORTS_W FastFeatureDetector : public FeatureDetector
526 {
527 public:
528     enum Type
529     {
530       TYPE_5_8 = 0, TYPE_7_12 = 1, TYPE_9_16 = 2
531     };
532
533     CV_WRAP FastFeatureDetector( int threshold=10, bool nonmaxSuppression=true);
534     CV_WRAP FastFeatureDetector( int threshold, bool nonmaxSuppression, int type);
535     AlgorithmInfo* info() const;
536
537 protected:
538     virtual void detectImpl( InputArray image, std::vector<KeyPoint>& keypoints, InputArray mask=noArray() ) const;
539
540     int threshold;
541     bool nonmaxSuppression;
542     int type;
543 };
544
545
546 class CV_EXPORTS_W GFTTDetector : public FeatureDetector
547 {
548 public:
549     CV_WRAP GFTTDetector( int maxCorners=1000, double qualityLevel=0.01, double minDistance=1,
550                           int blockSize=3, bool useHarrisDetector=false, double k=0.04 );
551     AlgorithmInfo* info() const;
552
553 protected:
554     virtual void detectImpl( InputArray image, std::vector<KeyPoint>& keypoints, InputArray mask=noArray() ) const;
555
556     int nfeatures;
557     double qualityLevel;
558     double minDistance;
559     int blockSize;
560     bool useHarrisDetector;
561     double k;
562 };
563
564 typedef GFTTDetector GoodFeaturesToTrackDetector;
565 typedef StarDetector StarFeatureDetector;
566
567 class CV_EXPORTS_W SimpleBlobDetector : public FeatureDetector
568 {
569 public:
570   struct CV_EXPORTS_W_SIMPLE Params
571   {
572       CV_WRAP Params();
573       CV_PROP_RW float thresholdStep;
574       CV_PROP_RW float minThreshold;
575       CV_PROP_RW float maxThreshold;
576       CV_PROP_RW size_t minRepeatability;
577       CV_PROP_RW float minDistBetweenBlobs;
578
579       CV_PROP_RW bool filterByColor;
580       CV_PROP_RW uchar blobColor;
581
582       CV_PROP_RW bool filterByArea;
583       CV_PROP_RW float minArea, maxArea;
584
585       CV_PROP_RW bool filterByCircularity;
586       CV_PROP_RW float minCircularity, maxCircularity;
587
588       CV_PROP_RW bool filterByInertia;
589       CV_PROP_RW float minInertiaRatio, maxInertiaRatio;
590
591       CV_PROP_RW bool filterByConvexity;
592       CV_PROP_RW float minConvexity, maxConvexity;
593
594       void read( const FileNode& fn );
595       void write( FileStorage& fs ) const;
596   };
597
598   CV_WRAP SimpleBlobDetector(const SimpleBlobDetector::Params &parameters = SimpleBlobDetector::Params());
599
600   virtual void read( const FileNode& fn );
601   virtual void write( FileStorage& fs ) const;
602
603 protected:
604   struct CV_EXPORTS Center
605   {
606       Point2d location;
607       double radius;
608       double confidence;
609   };
610
611   virtual void detectImpl( InputArray image, std::vector<KeyPoint>& keypoints, InputArray mask=noArray() ) const;
612   virtual void findBlobs(InputArray image, InputArray binaryImage, std::vector<Center> &centers) const;
613
614   Params params;
615   AlgorithmInfo* info() const;
616 };
617
618
619 class CV_EXPORTS DenseFeatureDetector : public FeatureDetector
620 {
621 public:
622     explicit DenseFeatureDetector( float initFeatureScale=1.f, int featureScaleLevels=1,
623                                    float featureScaleMul=0.1f,
624                                    int initXyStep=6, int initImgBound=0,
625                                    bool varyXyStepWithScale=true,
626                                    bool varyImgBoundWithScale=false );
627     AlgorithmInfo* info() const;
628
629 protected:
630     virtual void detectImpl( InputArray image, std::vector<KeyPoint>& keypoints, InputArray mask=noArray() ) const;
631
632     double initFeatureScale;
633     int featureScaleLevels;
634     double featureScaleMul;
635
636     int initXyStep;
637     int initImgBound;
638
639     bool varyXyStepWithScale;
640     bool varyImgBoundWithScale;
641 };
642
643 /*
644  * Adapts a detector to partition the source image into a grid and detect
645  * points in each cell.
646  */
647 class CV_EXPORTS_W GridAdaptedFeatureDetector : public FeatureDetector
648 {
649 public:
650     /*
651      * detector            Detector that will be adapted.
652      * maxTotalKeypoints   Maximum count of keypoints detected on the image. Only the strongest keypoints
653      *                      will be keeped.
654      * gridRows            Grid rows count.
655      * gridCols            Grid column count.
656      */
657     CV_WRAP GridAdaptedFeatureDetector( const Ptr<FeatureDetector>& detector=Ptr<FeatureDetector>(),
658                                         int maxTotalKeypoints=1000,
659                                         int gridRows=4, int gridCols=4 );
660
661     // TODO implement read/write
662     virtual bool empty() const;
663
664     AlgorithmInfo* info() const;
665
666 protected:
667     virtual void detectImpl( InputArray image, std::vector<KeyPoint>& keypoints, InputArray mask=noArray() ) const;
668
669     Ptr<FeatureDetector> detector;
670     int maxTotalKeypoints;
671     int gridRows;
672     int gridCols;
673 };
674
675 /*
676  * Adapts a detector to detect points over multiple levels of a Gaussian
677  * pyramid. Useful for detectors that are not inherently scaled.
678  */
679 class CV_EXPORTS_W PyramidAdaptedFeatureDetector : public FeatureDetector
680 {
681 public:
682     // maxLevel - The 0-based index of the last pyramid layer
683     CV_WRAP PyramidAdaptedFeatureDetector( const Ptr<FeatureDetector>& detector, int maxLevel=2 );
684
685     // TODO implement read/write
686     virtual bool empty() const;
687
688 protected:
689     virtual void detectImpl( InputArray image, std::vector<KeyPoint>& keypoints, InputArray mask=noArray() ) const;
690
691     Ptr<FeatureDetector> detector;
692     int maxLevel;
693 };
694
695 /** \brief A feature detector parameter adjuster, this is used by the DynamicAdaptedFeatureDetector
696  *  and is a wrapper for FeatureDetector that allow them to be adjusted after a detection
697  */
698 class CV_EXPORTS AdjusterAdapter: public FeatureDetector
699 {
700 public:
701     /** pure virtual interface
702      */
703     virtual ~AdjusterAdapter() {}
704     /** too few features were detected so, adjust the detector params accordingly
705      * \param min the minimum number of desired features
706      * \param n_detected the number previously detected
707      */
708     virtual void tooFew(int min, int n_detected) = 0;
709     /** too many features were detected so, adjust the detector params accordingly
710      * \param max the maximum number of desired features
711      * \param n_detected the number previously detected
712      */
713     virtual void tooMany(int max, int n_detected) = 0;
714     /** are params maxed out or still valid?
715      * \return false if the parameters can't be adjusted any more
716      */
717     virtual bool good() const = 0;
718
719     virtual Ptr<AdjusterAdapter> clone() const = 0;
720
721     static Ptr<AdjusterAdapter> create( const String& detectorType );
722 };
723 /** \brief an adaptively adjusting detector that iteratively detects until the desired number
724  * of features are detected.
725  *  Beware that this is not thread safe - as the adjustment of parameters breaks the const
726  *  of the detection routine...
727  *  /TODO Make this const correct and thread safe
728  *
729  *  sample usage:
730  //will create a detector that attempts to find 100 - 110 FAST Keypoints, and will at most run
731  //FAST feature detection 10 times until that number of keypoints are found
732  Ptr<FeatureDetector> detector(new DynamicAdaptedFeatureDetector(new FastAdjuster(20,true),100, 110, 10));
733
734  */
735 class CV_EXPORTS DynamicAdaptedFeatureDetector: public FeatureDetector
736 {
737 public:
738
739     /** \param adjuster an AdjusterAdapter that will do the detection and parameter adjustment
740      *  \param max_features the maximum desired number of features
741      *  \param max_iters the maximum number of times to try to adjust the feature detector params
742      *          for the FastAdjuster this can be high, but with Star or Surf this can get time consuming
743      *  \param min_features the minimum desired features
744      */
745     DynamicAdaptedFeatureDetector( const Ptr<AdjusterAdapter>& adjuster, int min_features=400, int max_features=500, int max_iters=5 );
746
747     virtual bool empty() const;
748
749 protected:
750     virtual void detectImpl( InputArray image, std::vector<KeyPoint>& keypoints, InputArray mask=noArray() ) const;
751
752 private:
753     DynamicAdaptedFeatureDetector& operator=(const DynamicAdaptedFeatureDetector&);
754     DynamicAdaptedFeatureDetector(const DynamicAdaptedFeatureDetector&);
755
756     int escape_iters_;
757     int min_features_, max_features_;
758     const Ptr<AdjusterAdapter> adjuster_;
759 };
760
761 /**\brief an adjust for the FAST detector. This will basically decrement or increment the
762  * threshold by 1
763  */
764 class CV_EXPORTS FastAdjuster: public AdjusterAdapter
765 {
766 public:
767     /**\param init_thresh the initial threshold to start with, default = 20
768      * \param nonmax whether to use non max or not for fast feature detection
769      */
770     FastAdjuster(int init_thresh=20, bool nonmax=true, int min_thresh=1, int max_thresh=200);
771
772     virtual void tooFew(int minv, int n_detected);
773     virtual void tooMany(int maxv, int n_detected);
774     virtual bool good() const;
775
776     virtual Ptr<AdjusterAdapter> clone() const;
777
778 protected:
779     virtual void detectImpl( InputArray image, std::vector<KeyPoint>& keypoints, InputArray mask=noArray() ) const;
780
781     int thresh_;
782     bool nonmax_;
783     int init_thresh_, min_thresh_, max_thresh_;
784 };
785
786
787 /** An adjuster for StarFeatureDetector, this one adjusts the responseThreshold for now
788  * TODO find a faster way to converge the parameters for Star - use CvStarDetectorParams
789  */
790 class CV_EXPORTS StarAdjuster: public AdjusterAdapter
791 {
792 public:
793     StarAdjuster(double initial_thresh=30.0, double min_thresh=2., double max_thresh=200.);
794
795     virtual void tooFew(int minv, int n_detected);
796     virtual void tooMany(int maxv, int n_detected);
797     virtual bool good() const;
798
799     virtual Ptr<AdjusterAdapter> clone() const;
800
801 protected:
802     virtual void detectImpl(InputArray image, std::vector<KeyPoint>& keypoints, InputArray mask=noArray() ) const;
803
804     double thresh_, init_thresh_, min_thresh_, max_thresh_;
805 };
806
807 class CV_EXPORTS SurfAdjuster: public AdjusterAdapter
808 {
809 public:
810     SurfAdjuster( double initial_thresh=400.f, double min_thresh=2, double max_thresh=1000 );
811
812     virtual void tooFew(int minv, int n_detected);
813     virtual void tooMany(int maxv, int n_detected);
814     virtual bool good() const;
815
816     virtual Ptr<AdjusterAdapter> clone() const;
817
818 protected:
819     virtual void detectImpl( InputArray image, std::vector<KeyPoint>& keypoints, InputArray mask=noArray() ) const;
820
821     double thresh_, init_thresh_, min_thresh_, max_thresh_;
822 };
823
824 CV_EXPORTS Mat windowedMatchingMask( const std::vector<KeyPoint>& keypoints1, const std::vector<KeyPoint>& keypoints2,
825                                      float maxDeltaX, float maxDeltaY );
826
827
828
829 /*
830  * OpponentColorDescriptorExtractor
831  *
832  * Adapts a descriptor extractor to compute descripors in Opponent Color Space
833  * (refer to van de Sande et al., CGIV 2008 "Color Descriptors for Object Category Recognition").
834  * Input RGB image is transformed in Opponent Color Space. Then unadapted descriptor extractor
835  * (set in constructor) computes descriptors on each of the three channel and concatenate
836  * them into a single color descriptor.
837  */
838 class CV_EXPORTS OpponentColorDescriptorExtractor : public DescriptorExtractor
839 {
840 public:
841     OpponentColorDescriptorExtractor( const Ptr<DescriptorExtractor>& descriptorExtractor );
842
843     virtual void read( const FileNode& );
844     virtual void write( FileStorage& ) const;
845
846     virtual int descriptorSize() const;
847     virtual int descriptorType() const;
848     virtual int defaultNorm() const;
849
850     virtual bool empty() const;
851
852 protected:
853     virtual void computeImpl( InputArray image, std::vector<KeyPoint>& keypoints, OutputArray descriptors ) const;
854
855     Ptr<DescriptorExtractor> descriptorExtractor;
856 };
857
858 /*
859  * BRIEF Descriptor
860  */
861 class CV_EXPORTS BriefDescriptorExtractor : public DescriptorExtractor
862 {
863 public:
864     static const int PATCH_SIZE = 48;
865     static const int KERNEL_SIZE = 9;
866
867     // bytes is a length of descriptor in bytes. It can be equal 16, 32 or 64 bytes.
868     BriefDescriptorExtractor( int bytes = 32 );
869
870     virtual void read( const FileNode& );
871     virtual void write( FileStorage& ) const;
872
873     virtual int descriptorSize() const;
874     virtual int descriptorType() const;
875     virtual int defaultNorm() const;
876
877     /// @todo read and write for brief
878
879     AlgorithmInfo* info() const;
880
881 protected:
882     virtual void computeImpl(InputArray image, std::vector<KeyPoint>& keypoints, OutputArray descriptors) const;
883
884     typedef void(*PixelTestFn)(InputArray, const std::vector<KeyPoint>&, OutputArray);
885
886     int bytes_;
887     PixelTestFn test_fn_;
888 };
889
890
891 /****************************************************************************************\
892 *                                      Distance                                          *
893 \****************************************************************************************/
894
895 template<typename T>
896 struct CV_EXPORTS Accumulator
897 {
898     typedef T Type;
899 };
900
901 template<> struct Accumulator<unsigned char>  { typedef float Type; };
902 template<> struct Accumulator<unsigned short> { typedef float Type; };
903 template<> struct Accumulator<char>   { typedef float Type; };
904 template<> struct Accumulator<short>  { typedef float Type; };
905
906 /*
907  * Squared Euclidean distance functor
908  */
909 template<class T>
910 struct CV_EXPORTS SL2
911 {
912     enum { normType = NORM_L2SQR };
913     typedef T ValueType;
914     typedef typename Accumulator<T>::Type ResultType;
915
916     ResultType operator()( const T* a, const T* b, int size ) const
917     {
918         return normL2Sqr<ValueType, ResultType>(a, b, size);
919     }
920 };
921
922 /*
923  * Euclidean distance functor
924  */
925 template<class T>
926 struct CV_EXPORTS L2
927 {
928     enum { normType = NORM_L2 };
929     typedef T ValueType;
930     typedef typename Accumulator<T>::Type ResultType;
931
932     ResultType operator()( const T* a, const T* b, int size ) const
933     {
934         return (ResultType)std::sqrt((double)normL2Sqr<ValueType, ResultType>(a, b, size));
935     }
936 };
937
938 /*
939  * Manhattan distance (city block distance) functor
940  */
941 template<class T>
942 struct CV_EXPORTS L1
943 {
944     enum { normType = NORM_L1 };
945     typedef T ValueType;
946     typedef typename Accumulator<T>::Type ResultType;
947
948     ResultType operator()( const T* a, const T* b, int size ) const
949     {
950         return normL1<ValueType, ResultType>(a, b, size);
951     }
952 };
953
954 /*
955  * Hamming distance functor - counts the bit differences between two strings - useful for the Brief descriptor
956  * bit count of A exclusive XOR'ed with B
957  */
958 struct CV_EXPORTS Hamming
959 {
960     enum { normType = NORM_HAMMING };
961     typedef unsigned char ValueType;
962     typedef int ResultType;
963
964     /** this will count the bits in a ^ b
965      */
966     ResultType operator()( const unsigned char* a, const unsigned char* b, int size ) const
967     {
968         return normHamming(a, b, size);
969     }
970 };
971
972 typedef Hamming HammingLUT;
973
974 template<int cellsize> struct HammingMultilevel
975 {
976     enum { normType = NORM_HAMMING + (cellsize>1) };
977     typedef unsigned char ValueType;
978     typedef int ResultType;
979
980     ResultType operator()( const unsigned char* a, const unsigned char* b, int size ) const
981     {
982         return normHamming(a, b, size, cellsize);
983     }
984 };
985
986 /****************************************************************************************\
987 *                                  DescriptorMatcher                                     *
988 \****************************************************************************************/
989 /*
990  * Abstract base class for matching two sets of descriptors.
991  */
992 class CV_EXPORTS_W DescriptorMatcher : public Algorithm
993 {
994 public:
995     virtual ~DescriptorMatcher();
996
997     /*
998      * Add descriptors to train descriptor collection.
999      * descriptors      Descriptors to add. Each descriptors[i] is a descriptors set from one image.
1000      */
1001     CV_WRAP virtual void add( InputArrayOfArrays descriptors );
1002     /*
1003      * Get train descriptors collection.
1004      */
1005     CV_WRAP const std::vector<Mat>& getTrainDescriptors() const;
1006     /*
1007      * Clear train descriptors collection.
1008      */
1009     CV_WRAP virtual void clear();
1010
1011     /*
1012      * Return true if there are not train descriptors in collection.
1013      */
1014     CV_WRAP virtual bool empty() const;
1015     /*
1016      * Return true if the matcher supports mask in match methods.
1017      */
1018     CV_WRAP virtual bool isMaskSupported() const = 0;
1019
1020     /*
1021      * Train matcher (e.g. train flann index).
1022      * In all methods to match the method train() is run every time before matching.
1023      * Some descriptor matchers (e.g. BruteForceMatcher) have empty implementation
1024      * of this method, other matchers really train their inner structures
1025      * (e.g. FlannBasedMatcher trains flann::Index). So nonempty implementation
1026      * of train() should check the class object state and do traing/retraining
1027      * only if the state requires that (e.g. FlannBasedMatcher trains flann::Index
1028      * if it has not trained yet or if new descriptors have been added to the train
1029      * collection).
1030      */
1031     CV_WRAP virtual void train();
1032     /*
1033      * Group of methods to match descriptors from image pair.
1034      * Method train() is run in this methods.
1035      */
1036     // Find one best match for each query descriptor (if mask is empty).
1037     CV_WRAP void match( InputArray queryDescriptors, InputArray trainDescriptors,
1038                 CV_OUT std::vector<DMatch>& matches, InputArray mask=noArray() ) const;
1039     // Find k best matches for each query descriptor (in increasing order of distances).
1040     // compactResult is used when mask is not empty. If compactResult is false matches
1041     // vector will have the same size as queryDescriptors rows. If compactResult is true
1042     // matches vector will not contain matches for fully masked out query descriptors.
1043     CV_WRAP void knnMatch( InputArray queryDescriptors, InputArray trainDescriptors,
1044                    CV_OUT std::vector<std::vector<DMatch> >& matches, int k,
1045                    InputArray mask=noArray(), bool compactResult=false ) const;
1046     // Find best matches for each query descriptor which have distance less than
1047     // maxDistance (in increasing order of distances).
1048     void radiusMatch( InputArray queryDescriptors, InputArray trainDescriptors,
1049                       std::vector<std::vector<DMatch> >& matches, float maxDistance,
1050                       InputArray mask=noArray(), bool compactResult=false ) const;
1051     /*
1052      * Group of methods to match descriptors from one image to image set.
1053      * See description of similar methods for matching image pair above.
1054      */
1055     CV_WRAP void match( InputArray queryDescriptors, CV_OUT std::vector<DMatch>& matches,
1056                         InputArrayOfArrays masks=noArray() );
1057     CV_WRAP void knnMatch( InputArray queryDescriptors, CV_OUT std::vector<std::vector<DMatch> >& matches, int k,
1058                            InputArrayOfArrays masks=noArray(), bool compactResult=false );
1059     void radiusMatch( InputArray queryDescriptors, std::vector<std::vector<DMatch> >& matches, float maxDistance,
1060                       InputArrayOfArrays masks=noArray(), bool compactResult=false );
1061
1062     // Reads matcher object from a file node
1063     virtual void read( const FileNode& );
1064     // Writes matcher object to a file storage
1065     virtual void write( FileStorage& ) const;
1066
1067     // Clone the matcher. If emptyTrainData is false the method create deep copy of the object, i.e. copies
1068     // both parameters and train data. If emptyTrainData is true the method create object copy with current parameters
1069     // but with empty train data.
1070     virtual Ptr<DescriptorMatcher> clone( bool emptyTrainData=false ) const = 0;
1071
1072     CV_WRAP static Ptr<DescriptorMatcher> create( const String& descriptorMatcherType );
1073 protected:
1074     /*
1075      * Class to work with descriptors from several images as with one merged matrix.
1076      * It is used e.g. in FlannBasedMatcher.
1077      */
1078     class CV_EXPORTS DescriptorCollection
1079     {
1080     public:
1081         DescriptorCollection();
1082         DescriptorCollection( const DescriptorCollection& collection );
1083         virtual ~DescriptorCollection();
1084
1085         // Vector of matrices "descriptors" will be merged to one matrix "mergedDescriptors" here.
1086         void set( const std::vector<Mat>& descriptors );
1087         virtual void clear();
1088
1089         const Mat& getDescriptors() const;
1090         const Mat getDescriptor( int imgIdx, int localDescIdx ) const;
1091         const Mat getDescriptor( int globalDescIdx ) const;
1092         void getLocalIdx( int globalDescIdx, int& imgIdx, int& localDescIdx ) const;
1093
1094         int size() const;
1095
1096     protected:
1097         Mat mergedDescriptors;
1098         std::vector<int> startIdxs;
1099     };
1100
1101     // In fact the matching is implemented only by the following two methods. These methods suppose
1102     // that the class object has been trained already. Public match methods call these methods
1103     // after calling train().
1104     virtual void knnMatchImpl( InputArray queryDescriptors, std::vector<std::vector<DMatch> >& matches, int k,
1105         InputArrayOfArrays masks=noArray(), bool compactResult=false ) = 0;
1106     virtual void radiusMatchImpl( InputArray queryDescriptors, std::vector<std::vector<DMatch> >& matches, float maxDistance,
1107         InputArrayOfArrays masks=noArray(), bool compactResult=false ) = 0;
1108
1109     static bool isPossibleMatch( InputArray mask, int queryIdx, int trainIdx );
1110     static bool isMaskedOut( InputArrayOfArrays masks, int queryIdx );
1111
1112     static Mat clone_op( Mat m ) { return m.clone(); }
1113     void checkMasks( InputArrayOfArrays masks, int queryDescriptorsCount ) const;
1114
1115     // Collection of descriptors from train images.
1116     std::vector<Mat> trainDescCollection;
1117     std::vector<UMat> utrainDescCollection;
1118 };
1119
1120 /*
1121  * Brute-force descriptor matcher.
1122  *
1123  * For each descriptor in the first set, this matcher finds the closest
1124  * descriptor in the second set by trying each one.
1125  *
1126  * For efficiency, BruteForceMatcher is templated on the distance metric.
1127  * For float descriptors, a common choice would be cv::L2<float>.
1128  */
1129 class CV_EXPORTS_W BFMatcher : public DescriptorMatcher
1130 {
1131 public:
1132     CV_WRAP BFMatcher( int normType=NORM_L2, bool crossCheck=false );
1133     virtual ~BFMatcher() {}
1134
1135     virtual bool isMaskSupported() const { return true; }
1136
1137     virtual Ptr<DescriptorMatcher> clone( bool emptyTrainData=false ) const;
1138
1139     AlgorithmInfo* info() const;
1140 protected:
1141     virtual void knnMatchImpl( InputArray queryDescriptors, std::vector<std::vector<DMatch> >& matches, int k,
1142         InputArrayOfArrays masks=noArray(), bool compactResult=false );
1143     virtual void radiusMatchImpl( InputArray queryDescriptors, std::vector<std::vector<DMatch> >& matches, float maxDistance,
1144         InputArrayOfArrays masks=noArray(), bool compactResult=false );
1145
1146     int normType;
1147     bool crossCheck;
1148 };
1149
1150
1151 /*
1152  * Flann based matcher
1153  */
1154 class CV_EXPORTS_W FlannBasedMatcher : public DescriptorMatcher
1155 {
1156 public:
1157     CV_WRAP FlannBasedMatcher( const Ptr<flann::IndexParams>& indexParams=makePtr<flann::KDTreeIndexParams>(),
1158                        const Ptr<flann::SearchParams>& searchParams=makePtr<flann::SearchParams>() );
1159
1160     virtual void add( InputArrayOfArrays descriptors );
1161     virtual void clear();
1162
1163     // Reads matcher object from a file node
1164     virtual void read( const FileNode& );
1165     // Writes matcher object to a file storage
1166     virtual void write( FileStorage& ) const;
1167
1168     virtual void train();
1169     virtual bool isMaskSupported() const;
1170
1171     virtual Ptr<DescriptorMatcher> clone( bool emptyTrainData=false ) const;
1172
1173     AlgorithmInfo* info() const;
1174 protected:
1175     static void convertToDMatches( const DescriptorCollection& descriptors,
1176                                    const Mat& indices, const Mat& distances,
1177                                    std::vector<std::vector<DMatch> >& matches );
1178
1179     virtual void knnMatchImpl( InputArray queryDescriptors, std::vector<std::vector<DMatch> >& matches, int k,
1180         InputArrayOfArrays masks=noArray(), bool compactResult=false );
1181     virtual void radiusMatchImpl( InputArray queryDescriptors, std::vector<std::vector<DMatch> >& matches, float maxDistance,
1182         InputArrayOfArrays masks=noArray(), bool compactResult=false );
1183
1184     Ptr<flann::IndexParams> indexParams;
1185     Ptr<flann::SearchParams> searchParams;
1186     Ptr<flann::Index> flannIndex;
1187
1188     DescriptorCollection mergedDescriptors;
1189     int addedDescCount;
1190 };
1191
1192 /****************************************************************************************\
1193 *                                GenericDescriptorMatcher                                *
1194 \****************************************************************************************/
1195 /*
1196  *   Abstract interface for a keypoint descriptor and matcher
1197  */
1198 class GenericDescriptorMatcher;
1199 typedef GenericDescriptorMatcher GenericDescriptorMatch;
1200
1201 class CV_EXPORTS GenericDescriptorMatcher
1202 {
1203 public:
1204     GenericDescriptorMatcher();
1205     virtual ~GenericDescriptorMatcher();
1206
1207     /*
1208      * Add train collection: images and keypoints from them.
1209      * images       A set of train images.
1210      * ketpoints    Keypoint collection that have been detected on train images.
1211      *
1212      * Keypoints for which a descriptor cannot be computed are removed. Such keypoints
1213      * must be filtered in this method befor adding keypoints to train collection "trainPointCollection".
1214      * If inheritor class need perform such prefiltering the method add() must be overloaded.
1215      * In the other class methods programmer has access to the train keypoints by a constant link.
1216      */
1217     virtual void add( InputArrayOfArrays images,
1218                       std::vector<std::vector<KeyPoint> >& keypoints );
1219
1220     const std::vector<Mat>& getTrainImages() const;
1221     const std::vector<std::vector<KeyPoint> >& getTrainKeypoints() const;
1222
1223     /*
1224      * Clear images and keypoints storing in train collection.
1225      */
1226     virtual void clear();
1227     /*
1228      * Returns true if matcher supports mask to match descriptors.
1229      */
1230     virtual bool isMaskSupported() = 0;
1231     /*
1232      * Train some inner structures (e.g. flann index or decision trees).
1233      * train() methods is run every time in matching methods. So the method implementation
1234      * should has a check whether these inner structures need be trained/retrained or not.
1235      */
1236     virtual void train();
1237
1238     /*
1239      * Classifies query keypoints.
1240      * queryImage    The query image
1241      * queryKeypoints   Keypoints from the query image
1242      * trainImage    The train image
1243      * trainKeypoints   Keypoints from the train image
1244      */
1245     // Classify keypoints from query image under one train image.
1246     void classify( InputArray queryImage, std::vector<KeyPoint>& queryKeypoints,
1247                            InputArray trainImage, std::vector<KeyPoint>& trainKeypoints ) const;
1248     // Classify keypoints from query image under train image collection.
1249     void classify( InputArray queryImage, std::vector<KeyPoint>& queryKeypoints );
1250
1251     /*
1252      * Group of methods to match keypoints from image pair.
1253      * Keypoints for which a descriptor cannot be computed are removed.
1254      * train() method is called here.
1255      */
1256     // Find one best match for each query descriptor (if mask is empty).
1257     void match( InputArray queryImage, std::vector<KeyPoint>& queryKeypoints,
1258                 InputArray trainImage, std::vector<KeyPoint>& trainKeypoints,
1259                 std::vector<DMatch>& matches, InputArray mask=noArray() ) const;
1260     // Find k best matches for each query keypoint (in increasing order of distances).
1261     // compactResult is used when mask is not empty. If compactResult is false matches
1262     // vector will have the same size as queryDescriptors rows.
1263     // If compactResult is true matches vector will not contain matches for fully masked out query descriptors.
1264     void knnMatch( InputArray queryImage, std::vector<KeyPoint>& queryKeypoints,
1265                    InputArray trainImage, std::vector<KeyPoint>& trainKeypoints,
1266                    std::vector<std::vector<DMatch> >& matches, int k,
1267                    InputArray mask=noArray(), bool compactResult=false ) const;
1268     // Find best matches for each query descriptor which have distance less than maxDistance (in increasing order of distances).
1269     void radiusMatch( InputArray queryImage, std::vector<KeyPoint>& queryKeypoints,
1270                       InputArray trainImage, std::vector<KeyPoint>& trainKeypoints,
1271                       std::vector<std::vector<DMatch> >& matches, float maxDistance,
1272                       InputArray mask=noArray(), bool compactResult=false ) const;
1273     /*
1274      * Group of methods to match keypoints from one image to image set.
1275      * See description of similar methods for matching image pair above.
1276      */
1277     void match( InputArray queryImage, std::vector<KeyPoint>& queryKeypoints,
1278                 std::vector<DMatch>& matches, InputArrayOfArrays masks=noArray() );
1279     void knnMatch( InputArray queryImage, std::vector<KeyPoint>& queryKeypoints,
1280                    std::vector<std::vector<DMatch> >& matches, int k,
1281                    InputArrayOfArrays masks=noArray(), bool compactResult=false );
1282     void radiusMatch(InputArray queryImage, std::vector<KeyPoint>& queryKeypoints,
1283                       std::vector<std::vector<DMatch> >& matches, float maxDistance,
1284                       InputArrayOfArrays masks=noArray(), bool compactResult=false );
1285
1286     // Reads matcher object from a file node
1287     virtual void read( const FileNode& fn );
1288     // Writes matcher object to a file storage
1289     virtual void write( FileStorage& fs ) const;
1290
1291     // Return true if matching object is empty (e.g. feature detector or descriptor matcher are empty)
1292     virtual bool empty() const;
1293
1294     // Clone the matcher. If emptyTrainData is false the method create deep copy of the object, i.e. copies
1295     // both parameters and train data. If emptyTrainData is true the method create object copy with current parameters
1296     // but with empty train data.
1297     virtual Ptr<GenericDescriptorMatcher> clone( bool emptyTrainData=false ) const = 0;
1298
1299     static Ptr<GenericDescriptorMatcher> create( const String& genericDescritptorMatcherType,
1300                                                  const String &paramsFilename=String() );
1301
1302 protected:
1303     // In fact the matching is implemented only by the following two methods. These methods suppose
1304     // that the class object has been trained already. Public match methods call these methods
1305     // after calling train().
1306     virtual void knnMatchImpl( InputArray queryImage, std::vector<KeyPoint>& queryKeypoints,
1307                                std::vector<std::vector<DMatch> >& matches, int k,
1308                                InputArrayOfArrays masks, bool compactResult ) = 0;
1309     virtual void radiusMatchImpl( InputArray queryImage, std::vector<KeyPoint>& queryKeypoints,
1310                                   std::vector<std::vector<DMatch> >& matches, float maxDistance,
1311                                   InputArrayOfArrays masks, bool compactResult ) = 0;
1312     /*
1313      * A storage for sets of keypoints together with corresponding images and class IDs
1314      */
1315     class CV_EXPORTS KeyPointCollection
1316     {
1317     public:
1318         KeyPointCollection();
1319         KeyPointCollection( const KeyPointCollection& collection );
1320         void add( const std::vector<Mat>& images, const std::vector<std::vector<KeyPoint> >& keypoints );
1321         void clear();
1322
1323         // Returns the total number of keypoints in the collection
1324         size_t keypointCount() const;
1325         size_t imageCount() const;
1326
1327         const std::vector<std::vector<KeyPoint> >& getKeypoints() const;
1328         const std::vector<KeyPoint>& getKeypoints( int imgIdx ) const;
1329         const KeyPoint& getKeyPoint( int imgIdx, int localPointIdx ) const;
1330         const KeyPoint& getKeyPoint( int globalPointIdx ) const;
1331         void getLocalIdx( int globalPointIdx, int& imgIdx, int& localPointIdx ) const;
1332
1333         const std::vector<Mat>& getImages() const;
1334         const Mat& getImage( int imgIdx ) const;
1335
1336     protected:
1337         int pointCount;
1338
1339         std::vector<Mat> images;
1340         std::vector<std::vector<KeyPoint> > keypoints;
1341         // global indices of the first points in each image, startIndices.size() = keypoints.size()
1342         std::vector<int> startIndices;
1343
1344     private:
1345         static Mat clone_op( Mat m ) { return m.clone(); }
1346     };
1347
1348     KeyPointCollection trainPointCollection;
1349 };
1350
1351
1352 /****************************************************************************************\
1353 *                                VectorDescriptorMatcher                                 *
1354 \****************************************************************************************/
1355
1356 /*
1357  *  A class used for matching descriptors that can be described as vectors in a finite-dimensional space
1358  */
1359 class VectorDescriptorMatcher;
1360 typedef VectorDescriptorMatcher VectorDescriptorMatch;
1361
1362 class CV_EXPORTS VectorDescriptorMatcher : public GenericDescriptorMatcher
1363 {
1364 public:
1365     VectorDescriptorMatcher( const Ptr<DescriptorExtractor>& extractor, const Ptr<DescriptorMatcher>& matcher );
1366     virtual ~VectorDescriptorMatcher();
1367
1368     virtual void add( InputArrayOfArrays imgCollection,
1369                       std::vector<std::vector<KeyPoint> >& pointCollection );
1370
1371     virtual void clear();
1372
1373     virtual void train();
1374
1375     virtual bool isMaskSupported();
1376
1377     virtual void read( const FileNode& fn );
1378     virtual void write( FileStorage& fs ) const;
1379     virtual bool empty() const;
1380
1381     virtual Ptr<GenericDescriptorMatcher> clone( bool emptyTrainData=false ) const;
1382
1383 protected:
1384     virtual void knnMatchImpl( InputArray queryImage, std::vector<KeyPoint>& queryKeypoints,
1385                                std::vector<std::vector<DMatch> >& matches, int k,
1386                                InputArrayOfArrays masks, bool compactResult );
1387     virtual void radiusMatchImpl( InputArray queryImage, std::vector<KeyPoint>& queryKeypoints,
1388                                   std::vector<std::vector<DMatch> >& matches, float maxDistance,
1389                                   InputArrayOfArrays masks, bool compactResult );
1390
1391     Ptr<DescriptorExtractor> extractor;
1392     Ptr<DescriptorMatcher> matcher;
1393 };
1394
1395 /****************************************************************************************\
1396 *                                   Drawing functions                                    *
1397 \****************************************************************************************/
1398 struct CV_EXPORTS DrawMatchesFlags
1399 {
1400     enum{ DEFAULT = 0, // Output image matrix will be created (Mat::create),
1401                        // i.e. existing memory of output image may be reused.
1402                        // Two source image, matches and single keypoints will be drawn.
1403                        // For each keypoint only the center point will be drawn (without
1404                        // the circle around keypoint with keypoint size and orientation).
1405           DRAW_OVER_OUTIMG = 1, // Output image matrix will not be created (Mat::create).
1406                                 // Matches will be drawn on existing content of output image.
1407           NOT_DRAW_SINGLE_POINTS = 2, // Single keypoints will not be drawn.
1408           DRAW_RICH_KEYPOINTS = 4 // For each keypoint the circle around keypoint with keypoint size and
1409                                   // orientation will be drawn.
1410         };
1411 };
1412
1413 // Draw keypoints.
1414 CV_EXPORTS_W void drawKeypoints( InputArray image, const std::vector<KeyPoint>& keypoints, InputOutputArray outImage,
1415                                const Scalar& color=Scalar::all(-1), int flags=DrawMatchesFlags::DEFAULT );
1416
1417 // Draws matches of keypints from two images on output image.
1418 CV_EXPORTS_W void drawMatches( InputArray img1, const std::vector<KeyPoint>& keypoints1,
1419                              InputArray img2, const std::vector<KeyPoint>& keypoints2,
1420                              const std::vector<DMatch>& matches1to2, InputOutputArray outImg,
1421                              const Scalar& matchColor=Scalar::all(-1), const Scalar& singlePointColor=Scalar::all(-1),
1422                              const std::vector<char>& matchesMask=std::vector<char>(), int flags=DrawMatchesFlags::DEFAULT );
1423
1424 CV_EXPORTS_AS(drawMatchesKnn) void drawMatches( InputArray img1, const std::vector<KeyPoint>& keypoints1,
1425                              InputArray img2, const std::vector<KeyPoint>& keypoints2,
1426                              const std::vector<std::vector<DMatch> >& matches1to2, InputOutputArray outImg,
1427                              const Scalar& matchColor=Scalar::all(-1), const Scalar& singlePointColor=Scalar::all(-1),
1428                              const std::vector<std::vector<char> >& matchesMask=std::vector<std::vector<char> >(), int flags=DrawMatchesFlags::DEFAULT );
1429
1430 /****************************************************************************************\
1431 *   Functions to evaluate the feature detectors and [generic] descriptor extractors      *
1432 \****************************************************************************************/
1433
1434 CV_EXPORTS void evaluateFeatureDetector( const Mat& img1, const Mat& img2, const Mat& H1to2,
1435                                          std::vector<KeyPoint>* keypoints1, std::vector<KeyPoint>* keypoints2,
1436                                          float& repeatability, int& correspCount,
1437                                          const Ptr<FeatureDetector>& fdetector=Ptr<FeatureDetector>() );
1438
1439 CV_EXPORTS void computeRecallPrecisionCurve( const std::vector<std::vector<DMatch> >& matches1to2,
1440                                              const std::vector<std::vector<uchar> >& correctMatches1to2Mask,
1441                                              std::vector<Point2f>& recallPrecisionCurve );
1442
1443 CV_EXPORTS float getRecall( const std::vector<Point2f>& recallPrecisionCurve, float l_precision );
1444 CV_EXPORTS int getNearestPoint( const std::vector<Point2f>& recallPrecisionCurve, float l_precision );
1445
1446 CV_EXPORTS void evaluateGenericDescriptorMatcher( const Mat& img1, const Mat& img2, const Mat& H1to2,
1447                                                   std::vector<KeyPoint>& keypoints1, std::vector<KeyPoint>& keypoints2,
1448                                                   std::vector<std::vector<DMatch> >* matches1to2, std::vector<std::vector<uchar> >* correctMatches1to2Mask,
1449                                                   std::vector<Point2f>& recallPrecisionCurve,
1450                                                   const Ptr<GenericDescriptorMatcher>& dmatch=Ptr<GenericDescriptorMatcher>() );
1451
1452
1453 /****************************************************************************************\
1454 *                                     Bag of visual words                                *
1455 \****************************************************************************************/
1456 /*
1457  * Abstract base class for training of a 'bag of visual words' vocabulary from a set of descriptors
1458  */
1459 class CV_EXPORTS BOWTrainer
1460 {
1461 public:
1462     BOWTrainer();
1463     virtual ~BOWTrainer();
1464
1465     void add( const Mat& descriptors );
1466     const std::vector<Mat>& getDescriptors() const;
1467     int descriptorsCount() const;
1468
1469     virtual void clear();
1470
1471     /*
1472      * Train visual words vocabulary, that is cluster training descriptors and
1473      * compute cluster centers.
1474      * Returns cluster centers.
1475      *
1476      * descriptors      Training descriptors computed on images keypoints.
1477      */
1478     virtual Mat cluster() const = 0;
1479     virtual Mat cluster( const Mat& descriptors ) const = 0;
1480
1481 protected:
1482     std::vector<Mat> descriptors;
1483     int size;
1484 };
1485
1486 /*
1487  * This is BOWTrainer using cv::kmeans to get vocabulary.
1488  */
1489 class CV_EXPORTS BOWKMeansTrainer : public BOWTrainer
1490 {
1491 public:
1492     BOWKMeansTrainer( int clusterCount, const TermCriteria& termcrit=TermCriteria(),
1493                       int attempts=3, int flags=KMEANS_PP_CENTERS );
1494     virtual ~BOWKMeansTrainer();
1495
1496     // Returns trained vocabulary (i.e. cluster centers).
1497     virtual Mat cluster() const;
1498     virtual Mat cluster( const Mat& descriptors ) const;
1499
1500 protected:
1501
1502     int clusterCount;
1503     TermCriteria termcrit;
1504     int attempts;
1505     int flags;
1506 };
1507
1508 /*
1509  * Class to compute image descriptor using bag of visual words.
1510  */
1511 class CV_EXPORTS BOWImgDescriptorExtractor
1512 {
1513 public:
1514     BOWImgDescriptorExtractor( const Ptr<DescriptorExtractor>& dextractor,
1515                                const Ptr<DescriptorMatcher>& dmatcher );
1516     BOWImgDescriptorExtractor( const Ptr<DescriptorMatcher>& dmatcher );
1517     virtual ~BOWImgDescriptorExtractor();
1518
1519     void setVocabulary( const Mat& vocabulary );
1520     const Mat& getVocabulary() const;
1521     void compute( InputArray image, std::vector<KeyPoint>& keypoints, OutputArray imgDescriptor,
1522                   std::vector<std::vector<int> >* pointIdxsOfClusters=0, Mat* descriptors=0 );
1523     void compute( InputArray keypointDescriptors, OutputArray imgDescriptor,
1524                   std::vector<std::vector<int> >* pointIdxsOfClusters=0 );
1525     // compute() is not constant because DescriptorMatcher::match is not constant
1526
1527     int descriptorSize() const;
1528     int descriptorType() const;
1529
1530 protected:
1531     Mat vocabulary;
1532     Ptr<DescriptorExtractor> dextractor;
1533     Ptr<DescriptorMatcher> dmatcher;
1534 };
1535
1536 } /* namespace cv */
1537
1538 #endif