fixed defects found by coverity scan
[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
409     template <typename imgType, typename iiType>
410     imgType meanIntensity( InputArray image, InputArray integral, const float kp_x, const float kp_y,
411                            const unsigned int scale, const unsigned int rot, const unsigned int point ) const;
412
413     template <typename srcMatType, typename iiMatType>
414     void computeDescriptors( InputArray image, std::vector<KeyPoint>& keypoints, OutputArray descriptors ) const;
415
416     template <typename srcMatType>
417     void extractDescriptor(srcMatType *pointsValue, void ** ptr) const;
418
419     bool orientationNormalized; //true if the orientation is normalized, false otherwise
420     bool scaleNormalized; //true if the scale is normalized, false otherwise
421     double patternScale; //scaling of the pattern
422     int nOctaves; //number of octaves
423     bool extAll; // true if all pairs need to be extracted for pairs selection
424
425     double patternScale0;
426     int nOctaves0;
427     std::vector<int> selectedPairs0;
428
429     struct PatternPoint
430     {
431         float x; // x coordinate relative to center
432         float y; // x coordinate relative to center
433         float sigma; // Gaussian smoothing sigma
434     };
435
436     struct DescriptionPair
437     {
438         uchar i; // index of the first point
439         uchar j; // index of the second point
440     };
441
442     struct OrientationPair
443     {
444         uchar i; // index of the first point
445         uchar j; // index of the second point
446         int weight_dx; // dx/(norm_sq))*4096
447         int weight_dy; // dy/(norm_sq))*4096
448     };
449
450     std::vector<PatternPoint> patternLookup; // look-up table for the pattern points (position+sigma of all points at all scales and orientation)
451     int patternSizes[NB_SCALES]; // size of the pattern at a specific scale (used to check if a point is within image boundaries)
452     DescriptionPair descriptionPairs[NB_PAIRS];
453     OrientationPair orientationPairs[NB_ORIENPAIRS];
454 };
455
456
457 /*!
458  Maximal Stable Extremal Regions class.
459
460  The class implements MSER algorithm introduced by J. Matas.
461  Unlike SIFT, SURF and many other detectors in OpenCV, this is salient region detector,
462  not the salient point detector.
463
464  It returns the regions, each of those is encoded as a contour.
465 */
466 class CV_EXPORTS_W MSER : public FeatureDetector
467 {
468 public:
469     //! the full constructor
470     CV_WRAP explicit MSER( int _delta=5, int _min_area=60, int _max_area=14400,
471           double _max_variation=0.25, double _min_diversity=.2,
472           int _max_evolution=200, double _area_threshold=1.01,
473           double _min_margin=0.003, int _edge_blur_size=5 );
474
475     //! the operator that extracts the MSERs from the image or the specific part of it
476     CV_WRAP_AS(detect) void operator()( InputArray image, CV_OUT std::vector<std::vector<Point> >& msers,
477                                         InputArray mask=noArray() ) const;
478     AlgorithmInfo* info() const;
479
480 protected:
481     void detectImpl( InputArray image, std::vector<KeyPoint>& keypoints, InputArray mask=noArray() ) const;
482
483     int delta;
484     int minArea;
485     int maxArea;
486     double maxVariation;
487     double minDiversity;
488     int maxEvolution;
489     double areaThreshold;
490     double minMargin;
491     int edgeBlurSize;
492 };
493
494 typedef MSER MserFeatureDetector;
495
496 /*!
497  The "Star" Detector.
498
499  The class implements the keypoint detector introduced by K. Konolige.
500 */
501 class CV_EXPORTS_W StarDetector : public FeatureDetector
502 {
503 public:
504     //! the full constructor
505     CV_WRAP StarDetector(int _maxSize=45, int _responseThreshold=30,
506                  int _lineThresholdProjected=10,
507                  int _lineThresholdBinarized=8,
508                  int _suppressNonmaxSize=5);
509
510     //! finds the keypoints in the image
511     CV_WRAP_AS(detect) void operator()(const Mat& image,
512                 CV_OUT std::vector<KeyPoint>& keypoints) const;
513
514     AlgorithmInfo* info() const;
515
516 protected:
517     void detectImpl( InputArray image, std::vector<KeyPoint>& keypoints, InputArray mask=noArray() ) const;
518
519     int maxSize;
520     int responseThreshold;
521     int lineThresholdProjected;
522     int lineThresholdBinarized;
523     int suppressNonmaxSize;
524 };
525
526 //! detects corners using FAST algorithm by E. Rosten
527 CV_EXPORTS void FAST( InputArray image, CV_OUT std::vector<KeyPoint>& keypoints,
528                       int threshold, bool nonmaxSuppression=true );
529
530 CV_EXPORTS void FAST( InputArray image, CV_OUT std::vector<KeyPoint>& keypoints,
531                       int threshold, bool nonmaxSuppression, int type );
532
533 class CV_EXPORTS_W FastFeatureDetector : public FeatureDetector
534 {
535 public:
536     enum Type
537     {
538       TYPE_5_8 = 0, TYPE_7_12 = 1, TYPE_9_16 = 2
539     };
540
541     CV_WRAP FastFeatureDetector( int threshold=10, bool nonmaxSuppression=true);
542     CV_WRAP FastFeatureDetector( int threshold, bool nonmaxSuppression, int type);
543     AlgorithmInfo* info() const;
544
545 protected:
546     virtual void detectImpl( InputArray image, std::vector<KeyPoint>& keypoints, InputArray mask=noArray() ) const;
547
548     int threshold;
549     bool nonmaxSuppression;
550     int type;
551 };
552
553
554 class CV_EXPORTS_W GFTTDetector : public FeatureDetector
555 {
556 public:
557     CV_WRAP GFTTDetector( int maxCorners=1000, double qualityLevel=0.01, double minDistance=1,
558                           int blockSize=3, bool useHarrisDetector=false, double k=0.04 );
559     AlgorithmInfo* info() const;
560
561 protected:
562     virtual void detectImpl( InputArray image, std::vector<KeyPoint>& keypoints, InputArray mask=noArray() ) const;
563
564     int nfeatures;
565     double qualityLevel;
566     double minDistance;
567     int blockSize;
568     bool useHarrisDetector;
569     double k;
570 };
571
572 typedef GFTTDetector GoodFeaturesToTrackDetector;
573 typedef StarDetector StarFeatureDetector;
574
575 class CV_EXPORTS_W SimpleBlobDetector : public FeatureDetector
576 {
577 public:
578   struct CV_EXPORTS_W_SIMPLE Params
579   {
580       CV_WRAP Params();
581       CV_PROP_RW float thresholdStep;
582       CV_PROP_RW float minThreshold;
583       CV_PROP_RW float maxThreshold;
584       CV_PROP_RW size_t minRepeatability;
585       CV_PROP_RW float minDistBetweenBlobs;
586
587       CV_PROP_RW bool filterByColor;
588       CV_PROP_RW uchar blobColor;
589
590       CV_PROP_RW bool filterByArea;
591       CV_PROP_RW float minArea, maxArea;
592
593       CV_PROP_RW bool filterByCircularity;
594       CV_PROP_RW float minCircularity, maxCircularity;
595
596       CV_PROP_RW bool filterByInertia;
597       CV_PROP_RW float minInertiaRatio, maxInertiaRatio;
598
599       CV_PROP_RW bool filterByConvexity;
600       CV_PROP_RW float minConvexity, maxConvexity;
601
602       void read( const FileNode& fn );
603       void write( FileStorage& fs ) const;
604   };
605
606   CV_WRAP SimpleBlobDetector(const SimpleBlobDetector::Params &parameters = SimpleBlobDetector::Params());
607
608   virtual void read( const FileNode& fn );
609   virtual void write( FileStorage& fs ) const;
610
611 protected:
612   struct CV_EXPORTS Center
613   {
614       Point2d location;
615       double radius;
616       double confidence;
617   };
618
619   virtual void detectImpl( InputArray image, std::vector<KeyPoint>& keypoints, InputArray mask=noArray() ) const;
620   virtual void findBlobs(InputArray image, InputArray binaryImage, std::vector<Center> &centers) const;
621
622   Params params;
623   AlgorithmInfo* info() const;
624 };
625
626
627 class CV_EXPORTS_W DenseFeatureDetector : public FeatureDetector
628 {
629 public:
630     CV_WRAP explicit DenseFeatureDetector( float initFeatureScale=1.f, int featureScaleLevels=1,
631                                            float featureScaleMul=0.1f,
632                                            int initXyStep=6, int initImgBound=0,
633                                            bool varyXyStepWithScale=true,
634                                            bool varyImgBoundWithScale=false );
635     AlgorithmInfo* info() const;
636
637 protected:
638     virtual void detectImpl( InputArray image, std::vector<KeyPoint>& keypoints, InputArray mask=noArray() ) const;
639
640     double initFeatureScale;
641     int featureScaleLevels;
642     double featureScaleMul;
643
644     int initXyStep;
645     int initImgBound;
646
647     bool varyXyStepWithScale;
648     bool varyImgBoundWithScale;
649 };
650
651 /*
652  * Adapts a detector to partition the source image into a grid and detect
653  * points in each cell.
654  */
655 class CV_EXPORTS_W GridAdaptedFeatureDetector : public FeatureDetector
656 {
657 public:
658     /*
659      * detector            Detector that will be adapted.
660      * maxTotalKeypoints   Maximum count of keypoints detected on the image. Only the strongest keypoints
661      *                      will be keeped.
662      * gridRows            Grid rows count.
663      * gridCols            Grid column count.
664      */
665     CV_WRAP GridAdaptedFeatureDetector( const Ptr<FeatureDetector>& detector=Ptr<FeatureDetector>(),
666                                         int maxTotalKeypoints=1000,
667                                         int gridRows=4, int gridCols=4 );
668
669     // TODO implement read/write
670     virtual bool empty() const;
671
672     AlgorithmInfo* info() const;
673
674 protected:
675     virtual void detectImpl( InputArray image, std::vector<KeyPoint>& keypoints, InputArray mask=noArray() ) const;
676
677     Ptr<FeatureDetector> detector;
678     int maxTotalKeypoints;
679     int gridRows;
680     int gridCols;
681 };
682
683 /*
684  * Adapts a detector to detect points over multiple levels of a Gaussian
685  * pyramid. Useful for detectors that are not inherently scaled.
686  */
687 class CV_EXPORTS_W PyramidAdaptedFeatureDetector : public FeatureDetector
688 {
689 public:
690     // maxLevel - The 0-based index of the last pyramid layer
691     CV_WRAP PyramidAdaptedFeatureDetector( const Ptr<FeatureDetector>& detector, int maxLevel=2 );
692
693     // TODO implement read/write
694     virtual bool empty() const;
695
696 protected:
697     virtual void detectImpl( InputArray image, std::vector<KeyPoint>& keypoints, InputArray mask=noArray() ) const;
698
699     Ptr<FeatureDetector> detector;
700     int maxLevel;
701 };
702
703 /** \brief A feature detector parameter adjuster, this is used by the DynamicAdaptedFeatureDetector
704  *  and is a wrapper for FeatureDetector that allow them to be adjusted after a detection
705  */
706 class CV_EXPORTS AdjusterAdapter: public FeatureDetector
707 {
708 public:
709     /** pure virtual interface
710      */
711     virtual ~AdjusterAdapter() {}
712     /** too few features were detected so, adjust the detector params accordingly
713      * \param min the minimum number of desired features
714      * \param n_detected the number previously detected
715      */
716     virtual void tooFew(int min, int n_detected) = 0;
717     /** too many features were detected so, adjust the detector params accordingly
718      * \param max the maximum number of desired features
719      * \param n_detected the number previously detected
720      */
721     virtual void tooMany(int max, int n_detected) = 0;
722     /** are params maxed out or still valid?
723      * \return false if the parameters can't be adjusted any more
724      */
725     virtual bool good() const = 0;
726
727     virtual Ptr<AdjusterAdapter> clone() const = 0;
728
729     static Ptr<AdjusterAdapter> create( const String& detectorType );
730 };
731 /** \brief an adaptively adjusting detector that iteratively detects until the desired number
732  * of features are detected.
733  *  Beware that this is not thread safe - as the adjustment of parameters breaks the const
734  *  of the detection routine...
735  *  /TODO Make this const correct and thread safe
736  *
737  *  sample usage:
738  //will create a detector that attempts to find 100 - 110 FAST Keypoints, and will at most run
739  //FAST feature detection 10 times until that number of keypoints are found
740  Ptr<FeatureDetector> detector(new DynamicAdaptedFeatureDetector(new FastAdjuster(20,true),100, 110, 10));
741
742  */
743 class CV_EXPORTS DynamicAdaptedFeatureDetector: public FeatureDetector
744 {
745 public:
746
747     /** \param adjuster an AdjusterAdapter that will do the detection and parameter adjustment
748      *  \param max_features the maximum desired number of features
749      *  \param max_iters the maximum number of times to try to adjust the feature detector params
750      *          for the FastAdjuster this can be high, but with Star or Surf this can get time consuming
751      *  \param min_features the minimum desired features
752      */
753     DynamicAdaptedFeatureDetector( const Ptr<AdjusterAdapter>& adjuster, int min_features=400, int max_features=500, int max_iters=5 );
754
755     virtual bool empty() const;
756
757 protected:
758     virtual void detectImpl( InputArray image, std::vector<KeyPoint>& keypoints, InputArray mask=noArray() ) const;
759
760 private:
761     DynamicAdaptedFeatureDetector& operator=(const DynamicAdaptedFeatureDetector&);
762     DynamicAdaptedFeatureDetector(const DynamicAdaptedFeatureDetector&);
763
764     int escape_iters_;
765     int min_features_, max_features_;
766     const Ptr<AdjusterAdapter> adjuster_;
767 };
768
769 /**\brief an adjust for the FAST detector. This will basically decrement or increment the
770  * threshold by 1
771  */
772 class CV_EXPORTS FastAdjuster: public AdjusterAdapter
773 {
774 public:
775     /**\param init_thresh the initial threshold to start with, default = 20
776      * \param nonmax whether to use non max or not for fast feature detection
777      */
778     FastAdjuster(int init_thresh=20, bool nonmax=true, int min_thresh=1, int max_thresh=200);
779
780     virtual void tooFew(int minv, int n_detected);
781     virtual void tooMany(int maxv, int n_detected);
782     virtual bool good() const;
783
784     virtual Ptr<AdjusterAdapter> clone() const;
785
786 protected:
787     virtual void detectImpl( InputArray image, std::vector<KeyPoint>& keypoints, InputArray mask=noArray() ) const;
788
789     int thresh_;
790     bool nonmax_;
791     int init_thresh_, min_thresh_, max_thresh_;
792 };
793
794
795 /** An adjuster for StarFeatureDetector, this one adjusts the responseThreshold for now
796  * TODO find a faster way to converge the parameters for Star - use CvStarDetectorParams
797  */
798 class CV_EXPORTS StarAdjuster: public AdjusterAdapter
799 {
800 public:
801     StarAdjuster(double initial_thresh=30.0, double min_thresh=2., double max_thresh=200.);
802
803     virtual void tooFew(int minv, int n_detected);
804     virtual void tooMany(int maxv, int n_detected);
805     virtual bool good() const;
806
807     virtual Ptr<AdjusterAdapter> clone() const;
808
809 protected:
810     virtual void detectImpl(InputArray image, std::vector<KeyPoint>& keypoints, InputArray mask=noArray() ) const;
811
812     double thresh_, init_thresh_, min_thresh_, max_thresh_;
813 };
814
815 class CV_EXPORTS SurfAdjuster: public AdjusterAdapter
816 {
817 public:
818     SurfAdjuster( double initial_thresh=400.f, double min_thresh=2, double max_thresh=1000 );
819
820     virtual void tooFew(int minv, int n_detected);
821     virtual void tooMany(int maxv, int n_detected);
822     virtual bool good() const;
823
824     virtual Ptr<AdjusterAdapter> clone() const;
825
826 protected:
827     virtual void detectImpl( InputArray image, std::vector<KeyPoint>& keypoints, InputArray mask=noArray() ) const;
828
829     double thresh_, init_thresh_, min_thresh_, max_thresh_;
830 };
831
832 CV_EXPORTS Mat windowedMatchingMask( const std::vector<KeyPoint>& keypoints1, const std::vector<KeyPoint>& keypoints2,
833                                      float maxDeltaX, float maxDeltaY );
834
835
836
837 /*
838  * OpponentColorDescriptorExtractor
839  *
840  * Adapts a descriptor extractor to compute descriptors in Opponent Color Space
841  * (refer to van de Sande et al., CGIV 2008 "Color Descriptors for Object Category Recognition").
842  * Input RGB image is transformed in Opponent Color Space. Then unadapted descriptor extractor
843  * (set in constructor) computes descriptors on each of the three channel and concatenate
844  * them into a single color descriptor.
845  */
846 class CV_EXPORTS OpponentColorDescriptorExtractor : public DescriptorExtractor
847 {
848 public:
849     OpponentColorDescriptorExtractor( const Ptr<DescriptorExtractor>& descriptorExtractor );
850
851     virtual void read( const FileNode& );
852     virtual void write( FileStorage& ) const;
853
854     virtual int descriptorSize() const;
855     virtual int descriptorType() const;
856     virtual int defaultNorm() const;
857
858     virtual bool empty() const;
859
860 protected:
861     virtual void computeImpl( InputArray image, std::vector<KeyPoint>& keypoints, OutputArray descriptors ) const;
862
863     Ptr<DescriptorExtractor> descriptorExtractor;
864 };
865
866 /*
867  * BRIEF Descriptor
868  */
869 class CV_EXPORTS BriefDescriptorExtractor : public DescriptorExtractor
870 {
871 public:
872     static const int PATCH_SIZE = 48;
873     static const int KERNEL_SIZE = 9;
874
875     // bytes is a length of descriptor in bytes. It can be equal 16, 32 or 64 bytes.
876     BriefDescriptorExtractor( int bytes = 32 );
877
878     virtual void read( const FileNode& );
879     virtual void write( FileStorage& ) const;
880
881     virtual int descriptorSize() const;
882     virtual int descriptorType() const;
883     virtual int defaultNorm() const;
884
885     /// @todo read and write for brief
886
887     AlgorithmInfo* info() const;
888
889 protected:
890     virtual void computeImpl(InputArray image, std::vector<KeyPoint>& keypoints, OutputArray descriptors) const;
891
892     typedef void(*PixelTestFn)(InputArray, const std::vector<KeyPoint>&, OutputArray);
893
894     int bytes_;
895     PixelTestFn test_fn_;
896 };
897
898 /*!
899 KAZE implementation
900 */
901 class CV_EXPORTS_W KAZE : public Feature2D
902 {
903 public:
904     CV_WRAP KAZE();
905     CV_WRAP explicit KAZE(bool extended, bool upright);
906
907     virtual ~KAZE();
908
909     // returns the descriptor size in bytes
910     int descriptorSize() const;
911     // returns the descriptor type
912     int descriptorType() const;
913     // returns the default norm type
914     int defaultNorm() const;
915
916     AlgorithmInfo* info() const;
917
918     // Compute the KAZE features on an image
919     void operator()(InputArray image, InputArray mask, std::vector<KeyPoint>& keypoints) const;
920
921     // Compute the KAZE features and descriptors on an image
922     void operator()(InputArray image, InputArray mask, std::vector<KeyPoint>& keypoints,
923         OutputArray descriptors, bool useProvidedKeypoints = false) const;
924
925 protected:
926     void detectImpl(InputArray image, std::vector<KeyPoint>& keypoints, InputArray mask) const;
927     void computeImpl(InputArray image, std::vector<KeyPoint>& keypoints, OutputArray descriptors) const;
928
929     CV_PROP bool extended;
930     CV_PROP bool upright;
931 };
932
933 /*!
934 AKAZE implementation
935 */
936 class CV_EXPORTS_W AKAZE : public Feature2D
937 {
938 public:
939     /// AKAZE Descriptor Type
940     enum DESCRIPTOR_TYPE {
941         DESCRIPTOR_KAZE_UPRIGHT = 2, ///< Upright descriptors, not invariant to rotation
942         DESCRIPTOR_KAZE = 3,
943         DESCRIPTOR_MLDB_UPRIGHT = 4, ///< Upright descriptors, not invariant to rotation
944         DESCRIPTOR_MLDB = 5
945     };
946
947     CV_WRAP AKAZE();
948     explicit AKAZE(DESCRIPTOR_TYPE descriptor_type, int descriptor_size = 0, int descriptor_channels = 3);
949
950     virtual ~AKAZE();
951
952     // returns the descriptor size in bytes
953     int descriptorSize() const;
954     // returns the descriptor type
955     int descriptorType() const;
956     // returns the default norm type
957     int defaultNorm() const;
958
959     // Compute the AKAZE features on an image
960     void operator()(InputArray image, InputArray mask, std::vector<KeyPoint>& keypoints) const;
961
962     // Compute the AKAZE features and descriptors on an image
963     void operator()(InputArray image, InputArray mask, std::vector<KeyPoint>& keypoints,
964         OutputArray descriptors, bool useProvidedKeypoints = false) const;
965
966     AlgorithmInfo* info() const;
967
968 protected:
969
970     void computeImpl(InputArray image, std::vector<KeyPoint>& keypoints, OutputArray descriptors) const;
971     void detectImpl(InputArray image, std::vector<KeyPoint>& keypoints, InputArray mask = noArray()) const;
972
973     CV_PROP int descriptor;
974     CV_PROP int descriptor_channels;
975     CV_PROP int descriptor_size;
976
977 };
978 /****************************************************************************************\
979 *                                      Distance                                          *
980 \****************************************************************************************/
981
982 template<typename T>
983 struct CV_EXPORTS Accumulator
984 {
985     typedef T Type;
986 };
987
988 template<> struct Accumulator<unsigned char>  { typedef float Type; };
989 template<> struct Accumulator<unsigned short> { typedef float Type; };
990 template<> struct Accumulator<char>   { typedef float Type; };
991 template<> struct Accumulator<short>  { typedef float Type; };
992
993 /*
994  * Squared Euclidean distance functor
995  */
996 template<class T>
997 struct CV_EXPORTS SL2
998 {
999     enum { normType = NORM_L2SQR };
1000     typedef T ValueType;
1001     typedef typename Accumulator<T>::Type ResultType;
1002
1003     ResultType operator()( const T* a, const T* b, int size ) const
1004     {
1005         return normL2Sqr<ValueType, ResultType>(a, b, size);
1006     }
1007 };
1008
1009 /*
1010  * Euclidean distance functor
1011  */
1012 template<class T>
1013 struct CV_EXPORTS L2
1014 {
1015     enum { normType = NORM_L2 };
1016     typedef T ValueType;
1017     typedef typename Accumulator<T>::Type ResultType;
1018
1019     ResultType operator()( const T* a, const T* b, int size ) const
1020     {
1021         return (ResultType)std::sqrt((double)normL2Sqr<ValueType, ResultType>(a, b, size));
1022     }
1023 };
1024
1025 /*
1026  * Manhattan distance (city block distance) functor
1027  */
1028 template<class T>
1029 struct CV_EXPORTS L1
1030 {
1031     enum { normType = NORM_L1 };
1032     typedef T ValueType;
1033     typedef typename Accumulator<T>::Type ResultType;
1034
1035     ResultType operator()( const T* a, const T* b, int size ) const
1036     {
1037         return normL1<ValueType, ResultType>(a, b, size);
1038     }
1039 };
1040
1041 /*
1042  * Hamming distance functor - counts the bit differences between two strings - useful for the Brief descriptor
1043  * bit count of A exclusive XOR'ed with B
1044  */
1045 struct CV_EXPORTS Hamming
1046 {
1047     enum { normType = NORM_HAMMING };
1048     typedef unsigned char ValueType;
1049     typedef int ResultType;
1050
1051     /** this will count the bits in a ^ b
1052      */
1053     ResultType operator()( const unsigned char* a, const unsigned char* b, int size ) const
1054     {
1055         return normHamming(a, b, size);
1056     }
1057 };
1058
1059 typedef Hamming HammingLUT;
1060
1061 template<int cellsize> struct HammingMultilevel
1062 {
1063     enum { normType = NORM_HAMMING + (cellsize>1) };
1064     typedef unsigned char ValueType;
1065     typedef int ResultType;
1066
1067     ResultType operator()( const unsigned char* a, const unsigned char* b, int size ) const
1068     {
1069         return normHamming(a, b, size, cellsize);
1070     }
1071 };
1072
1073 /****************************************************************************************\
1074 *                                  DescriptorMatcher                                     *
1075 \****************************************************************************************/
1076 /*
1077  * Abstract base class for matching two sets of descriptors.
1078  */
1079 class CV_EXPORTS_W DescriptorMatcher : public Algorithm
1080 {
1081 public:
1082     virtual ~DescriptorMatcher();
1083
1084     /*
1085      * Add descriptors to train descriptor collection.
1086      * descriptors      Descriptors to add. Each descriptors[i] is a descriptors set from one image.
1087      */
1088     CV_WRAP virtual void add( InputArrayOfArrays descriptors );
1089     /*
1090      * Get train descriptors collection.
1091      */
1092     CV_WRAP const std::vector<Mat>& getTrainDescriptors() const;
1093     /*
1094      * Clear train descriptors collection.
1095      */
1096     CV_WRAP virtual void clear();
1097
1098     /*
1099      * Return true if there are not train descriptors in collection.
1100      */
1101     CV_WRAP virtual bool empty() const;
1102     /*
1103      * Return true if the matcher supports mask in match methods.
1104      */
1105     CV_WRAP virtual bool isMaskSupported() const = 0;
1106
1107     /*
1108      * Train matcher (e.g. train flann index).
1109      * In all methods to match the method train() is run every time before matching.
1110      * Some descriptor matchers (e.g. BruteForceMatcher) have empty implementation
1111      * of this method, other matchers really train their inner structures
1112      * (e.g. FlannBasedMatcher trains flann::Index). So nonempty implementation
1113      * of train() should check the class object state and do traing/retraining
1114      * only if the state requires that (e.g. FlannBasedMatcher trains flann::Index
1115      * if it has not trained yet or if new descriptors have been added to the train
1116      * collection).
1117      */
1118     CV_WRAP virtual void train();
1119     /*
1120      * Group of methods to match descriptors from image pair.
1121      * Method train() is run in this methods.
1122      */
1123     // Find one best match for each query descriptor (if mask is empty).
1124     CV_WRAP void match( InputArray queryDescriptors, InputArray trainDescriptors,
1125                 CV_OUT std::vector<DMatch>& matches, InputArray mask=noArray() ) const;
1126     // Find k best matches for each query descriptor (in increasing order of distances).
1127     // compactResult is used when mask is not empty. If compactResult is false matches
1128     // vector will have the same size as queryDescriptors rows. If compactResult is true
1129     // matches vector will not contain matches for fully masked out query descriptors.
1130     CV_WRAP void knnMatch( InputArray queryDescriptors, InputArray trainDescriptors,
1131                    CV_OUT std::vector<std::vector<DMatch> >& matches, int k,
1132                    InputArray mask=noArray(), bool compactResult=false ) const;
1133     // Find best matches for each query descriptor which have distance less than
1134     // maxDistance (in increasing order of distances).
1135     void radiusMatch( InputArray queryDescriptors, InputArray trainDescriptors,
1136                       std::vector<std::vector<DMatch> >& matches, float maxDistance,
1137                       InputArray mask=noArray(), bool compactResult=false ) const;
1138     /*
1139      * Group of methods to match descriptors from one image to image set.
1140      * See description of similar methods for matching image pair above.
1141      */
1142     CV_WRAP void match( InputArray queryDescriptors, CV_OUT std::vector<DMatch>& matches,
1143                         InputArrayOfArrays masks=noArray() );
1144     CV_WRAP void knnMatch( InputArray queryDescriptors, CV_OUT std::vector<std::vector<DMatch> >& matches, int k,
1145                            InputArrayOfArrays masks=noArray(), bool compactResult=false );
1146     void radiusMatch( InputArray queryDescriptors, std::vector<std::vector<DMatch> >& matches, float maxDistance,
1147                       InputArrayOfArrays masks=noArray(), bool compactResult=false );
1148
1149     // Reads matcher object from a file node
1150     virtual void read( const FileNode& );
1151     // Writes matcher object to a file storage
1152     virtual void write( FileStorage& ) const;
1153
1154     // Clone the matcher. If emptyTrainData is false the method create deep copy of the object, i.e. copies
1155     // both parameters and train data. If emptyTrainData is true the method create object copy with current parameters
1156     // but with empty train data.
1157     virtual Ptr<DescriptorMatcher> clone( bool emptyTrainData=false ) const = 0;
1158
1159     CV_WRAP static Ptr<DescriptorMatcher> create( const String& descriptorMatcherType );
1160 protected:
1161     /*
1162      * Class to work with descriptors from several images as with one merged matrix.
1163      * It is used e.g. in FlannBasedMatcher.
1164      */
1165     class CV_EXPORTS DescriptorCollection
1166     {
1167     public:
1168         DescriptorCollection();
1169         DescriptorCollection( const DescriptorCollection& collection );
1170         virtual ~DescriptorCollection();
1171
1172         // Vector of matrices "descriptors" will be merged to one matrix "mergedDescriptors" here.
1173         void set( const std::vector<Mat>& descriptors );
1174         virtual void clear();
1175
1176         const Mat& getDescriptors() const;
1177         const Mat getDescriptor( int imgIdx, int localDescIdx ) const;
1178         const Mat getDescriptor( int globalDescIdx ) const;
1179         void getLocalIdx( int globalDescIdx, int& imgIdx, int& localDescIdx ) const;
1180
1181         int size() const;
1182
1183     protected:
1184         Mat mergedDescriptors;
1185         std::vector<int> startIdxs;
1186     };
1187
1188     // In fact the matching is implemented only by the following two methods. These methods suppose
1189     // that the class object has been trained already. Public match methods call these methods
1190     // after calling train().
1191     virtual void knnMatchImpl( InputArray queryDescriptors, std::vector<std::vector<DMatch> >& matches, int k,
1192         InputArrayOfArrays masks=noArray(), bool compactResult=false ) = 0;
1193     virtual void radiusMatchImpl( InputArray queryDescriptors, std::vector<std::vector<DMatch> >& matches, float maxDistance,
1194         InputArrayOfArrays masks=noArray(), bool compactResult=false ) = 0;
1195
1196     static bool isPossibleMatch( InputArray mask, int queryIdx, int trainIdx );
1197     static bool isMaskedOut( InputArrayOfArrays masks, int queryIdx );
1198
1199     static Mat clone_op( Mat m ) { return m.clone(); }
1200     void checkMasks( InputArrayOfArrays masks, int queryDescriptorsCount ) const;
1201
1202     // Collection of descriptors from train images.
1203     std::vector<Mat> trainDescCollection;
1204     std::vector<UMat> utrainDescCollection;
1205 };
1206
1207 /*
1208  * Brute-force descriptor matcher.
1209  *
1210  * For each descriptor in the first set, this matcher finds the closest
1211  * descriptor in the second set by trying each one.
1212  *
1213  * For efficiency, BruteForceMatcher is templated on the distance metric.
1214  * For float descriptors, a common choice would be cv::L2<float>.
1215  */
1216 class CV_EXPORTS_W BFMatcher : public DescriptorMatcher
1217 {
1218 public:
1219     CV_WRAP BFMatcher( int normType=NORM_L2, bool crossCheck=false );
1220     virtual ~BFMatcher() {}
1221
1222     virtual bool isMaskSupported() const { return true; }
1223
1224     virtual Ptr<DescriptorMatcher> clone( bool emptyTrainData=false ) const;
1225
1226     AlgorithmInfo* info() const;
1227 protected:
1228     virtual void knnMatchImpl( InputArray queryDescriptors, std::vector<std::vector<DMatch> >& matches, int k,
1229         InputArrayOfArrays masks=noArray(), bool compactResult=false );
1230     virtual void radiusMatchImpl( InputArray queryDescriptors, std::vector<std::vector<DMatch> >& matches, float maxDistance,
1231         InputArrayOfArrays masks=noArray(), bool compactResult=false );
1232
1233     int normType;
1234     bool crossCheck;
1235 };
1236
1237
1238 /*
1239  * Flann based matcher
1240  */
1241 class CV_EXPORTS_W FlannBasedMatcher : public DescriptorMatcher
1242 {
1243 public:
1244     CV_WRAP FlannBasedMatcher( const Ptr<flann::IndexParams>& indexParams=makePtr<flann::KDTreeIndexParams>(),
1245                        const Ptr<flann::SearchParams>& searchParams=makePtr<flann::SearchParams>() );
1246
1247     virtual void add( InputArrayOfArrays descriptors );
1248     virtual void clear();
1249
1250     // Reads matcher object from a file node
1251     virtual void read( const FileNode& );
1252     // Writes matcher object to a file storage
1253     virtual void write( FileStorage& ) const;
1254
1255     virtual void train();
1256     virtual bool isMaskSupported() const;
1257
1258     virtual Ptr<DescriptorMatcher> clone( bool emptyTrainData=false ) const;
1259
1260     AlgorithmInfo* info() const;
1261 protected:
1262     static void convertToDMatches( const DescriptorCollection& descriptors,
1263                                    const Mat& indices, const Mat& distances,
1264                                    std::vector<std::vector<DMatch> >& matches );
1265
1266     virtual void knnMatchImpl( InputArray queryDescriptors, std::vector<std::vector<DMatch> >& matches, int k,
1267         InputArrayOfArrays masks=noArray(), bool compactResult=false );
1268     virtual void radiusMatchImpl( InputArray queryDescriptors, std::vector<std::vector<DMatch> >& matches, float maxDistance,
1269         InputArrayOfArrays masks=noArray(), bool compactResult=false );
1270
1271     Ptr<flann::IndexParams> indexParams;
1272     Ptr<flann::SearchParams> searchParams;
1273     Ptr<flann::Index> flannIndex;
1274
1275     DescriptorCollection mergedDescriptors;
1276     int addedDescCount;
1277 };
1278
1279 /****************************************************************************************\
1280 *                                GenericDescriptorMatcher                                *
1281 \****************************************************************************************/
1282 /*
1283  *   Abstract interface for a keypoint descriptor and matcher
1284  */
1285 class GenericDescriptorMatcher;
1286 typedef GenericDescriptorMatcher GenericDescriptorMatch;
1287
1288 class CV_EXPORTS GenericDescriptorMatcher
1289 {
1290 public:
1291     GenericDescriptorMatcher();
1292     virtual ~GenericDescriptorMatcher();
1293
1294     /*
1295      * Add train collection: images and keypoints from them.
1296      * images       A set of train images.
1297      * ketpoints    Keypoint collection that have been detected on train images.
1298      *
1299      * Keypoints for which a descriptor cannot be computed are removed. Such keypoints
1300      * must be filtered in this method befor adding keypoints to train collection "trainPointCollection".
1301      * If inheritor class need perform such prefiltering the method add() must be overloaded.
1302      * In the other class methods programmer has access to the train keypoints by a constant link.
1303      */
1304     virtual void add( InputArrayOfArrays images,
1305                       std::vector<std::vector<KeyPoint> >& keypoints );
1306
1307     const std::vector<Mat>& getTrainImages() const;
1308     const std::vector<std::vector<KeyPoint> >& getTrainKeypoints() const;
1309
1310     /*
1311      * Clear images and keypoints storing in train collection.
1312      */
1313     virtual void clear();
1314     /*
1315      * Returns true if matcher supports mask to match descriptors.
1316      */
1317     virtual bool isMaskSupported() = 0;
1318     /*
1319      * Train some inner structures (e.g. flann index or decision trees).
1320      * train() methods is run every time in matching methods. So the method implementation
1321      * should has a check whether these inner structures need be trained/retrained or not.
1322      */
1323     virtual void train();
1324
1325     /*
1326      * Classifies query keypoints.
1327      * queryImage    The query image
1328      * queryKeypoints   Keypoints from the query image
1329      * trainImage    The train image
1330      * trainKeypoints   Keypoints from the train image
1331      */
1332     // Classify keypoints from query image under one train image.
1333     void classify( InputArray queryImage, std::vector<KeyPoint>& queryKeypoints,
1334                            InputArray trainImage, std::vector<KeyPoint>& trainKeypoints ) const;
1335     // Classify keypoints from query image under train image collection.
1336     void classify( InputArray queryImage, std::vector<KeyPoint>& queryKeypoints );
1337
1338     /*
1339      * Group of methods to match keypoints from image pair.
1340      * Keypoints for which a descriptor cannot be computed are removed.
1341      * train() method is called here.
1342      */
1343     // Find one best match for each query descriptor (if mask is empty).
1344     void match( InputArray queryImage, std::vector<KeyPoint>& queryKeypoints,
1345                 InputArray trainImage, std::vector<KeyPoint>& trainKeypoints,
1346                 std::vector<DMatch>& matches, InputArray mask=noArray() ) const;
1347     // Find k best matches for each query keypoint (in increasing order of distances).
1348     // compactResult is used when mask is not empty. If compactResult is false matches
1349     // vector will have the same size as queryDescriptors rows.
1350     // If compactResult is true matches vector will not contain matches for fully masked out query descriptors.
1351     void knnMatch( InputArray queryImage, std::vector<KeyPoint>& queryKeypoints,
1352                    InputArray trainImage, std::vector<KeyPoint>& trainKeypoints,
1353                    std::vector<std::vector<DMatch> >& matches, int k,
1354                    InputArray mask=noArray(), bool compactResult=false ) const;
1355     // Find best matches for each query descriptor which have distance less than maxDistance (in increasing order of distances).
1356     void radiusMatch( InputArray queryImage, std::vector<KeyPoint>& queryKeypoints,
1357                       InputArray trainImage, std::vector<KeyPoint>& trainKeypoints,
1358                       std::vector<std::vector<DMatch> >& matches, float maxDistance,
1359                       InputArray mask=noArray(), bool compactResult=false ) const;
1360     /*
1361      * Group of methods to match keypoints from one image to image set.
1362      * See description of similar methods for matching image pair above.
1363      */
1364     void match( InputArray queryImage, std::vector<KeyPoint>& queryKeypoints,
1365                 std::vector<DMatch>& matches, InputArrayOfArrays masks=noArray() );
1366     void knnMatch( InputArray queryImage, std::vector<KeyPoint>& queryKeypoints,
1367                    std::vector<std::vector<DMatch> >& matches, int k,
1368                    InputArrayOfArrays masks=noArray(), bool compactResult=false );
1369     void radiusMatch(InputArray queryImage, std::vector<KeyPoint>& queryKeypoints,
1370                       std::vector<std::vector<DMatch> >& matches, float maxDistance,
1371                       InputArrayOfArrays masks=noArray(), bool compactResult=false );
1372
1373     // Reads matcher object from a file node
1374     virtual void read( const FileNode& fn );
1375     // Writes matcher object to a file storage
1376     virtual void write( FileStorage& fs ) const;
1377
1378     // Return true if matching object is empty (e.g. feature detector or descriptor matcher are empty)
1379     virtual bool empty() const;
1380
1381     // Clone the matcher. If emptyTrainData is false the method create deep copy of the object, i.e. copies
1382     // both parameters and train data. If emptyTrainData is true the method create object copy with current parameters
1383     // but with empty train data.
1384     virtual Ptr<GenericDescriptorMatcher> clone( bool emptyTrainData=false ) const = 0;
1385
1386     static Ptr<GenericDescriptorMatcher> create( const String& genericDescritptorMatcherType,
1387                                                  const String &paramsFilename=String() );
1388
1389 protected:
1390     // In fact the matching is implemented only by the following two methods. These methods suppose
1391     // that the class object has been trained already. Public match methods call these methods
1392     // after calling train().
1393     virtual void knnMatchImpl( InputArray queryImage, std::vector<KeyPoint>& queryKeypoints,
1394                                std::vector<std::vector<DMatch> >& matches, int k,
1395                                InputArrayOfArrays masks, bool compactResult ) = 0;
1396     virtual void radiusMatchImpl( InputArray queryImage, std::vector<KeyPoint>& queryKeypoints,
1397                                   std::vector<std::vector<DMatch> >& matches, float maxDistance,
1398                                   InputArrayOfArrays masks, bool compactResult ) = 0;
1399     /*
1400      * A storage for sets of keypoints together with corresponding images and class IDs
1401      */
1402     class CV_EXPORTS KeyPointCollection
1403     {
1404     public:
1405         KeyPointCollection();
1406         KeyPointCollection( const KeyPointCollection& collection );
1407         void add( const std::vector<Mat>& images, const std::vector<std::vector<KeyPoint> >& keypoints );
1408         void clear();
1409
1410         // Returns the total number of keypoints in the collection
1411         size_t keypointCount() const;
1412         size_t imageCount() const;
1413
1414         const std::vector<std::vector<KeyPoint> >& getKeypoints() const;
1415         const std::vector<KeyPoint>& getKeypoints( int imgIdx ) const;
1416         const KeyPoint& getKeyPoint( int imgIdx, int localPointIdx ) const;
1417         const KeyPoint& getKeyPoint( int globalPointIdx ) const;
1418         void getLocalIdx( int globalPointIdx, int& imgIdx, int& localPointIdx ) const;
1419
1420         const std::vector<Mat>& getImages() const;
1421         const Mat& getImage( int imgIdx ) const;
1422
1423     protected:
1424         int pointCount;
1425
1426         std::vector<Mat> images;
1427         std::vector<std::vector<KeyPoint> > keypoints;
1428         // global indices of the first points in each image, startIndices.size() = keypoints.size()
1429         std::vector<int> startIndices;
1430
1431     private:
1432         static Mat clone_op( Mat m ) { return m.clone(); }
1433     };
1434
1435     KeyPointCollection trainPointCollection;
1436 };
1437
1438
1439 /****************************************************************************************\
1440 *                                VectorDescriptorMatcher                                 *
1441 \****************************************************************************************/
1442
1443 /*
1444  *  A class used for matching descriptors that can be described as vectors in a finite-dimensional space
1445  */
1446 class VectorDescriptorMatcher;
1447 typedef VectorDescriptorMatcher VectorDescriptorMatch;
1448
1449 class CV_EXPORTS VectorDescriptorMatcher : public GenericDescriptorMatcher
1450 {
1451 public:
1452     VectorDescriptorMatcher( const Ptr<DescriptorExtractor>& extractor, const Ptr<DescriptorMatcher>& matcher );
1453     virtual ~VectorDescriptorMatcher();
1454
1455     virtual void add( InputArrayOfArrays imgCollection,
1456                       std::vector<std::vector<KeyPoint> >& pointCollection );
1457
1458     virtual void clear();
1459
1460     virtual void train();
1461
1462     virtual bool isMaskSupported();
1463
1464     virtual void read( const FileNode& fn );
1465     virtual void write( FileStorage& fs ) const;
1466     virtual bool empty() const;
1467
1468     virtual Ptr<GenericDescriptorMatcher> clone( bool emptyTrainData=false ) const;
1469
1470 protected:
1471     virtual void knnMatchImpl( InputArray queryImage, std::vector<KeyPoint>& queryKeypoints,
1472                                std::vector<std::vector<DMatch> >& matches, int k,
1473                                InputArrayOfArrays masks, bool compactResult );
1474     virtual void radiusMatchImpl( InputArray queryImage, std::vector<KeyPoint>& queryKeypoints,
1475                                   std::vector<std::vector<DMatch> >& matches, float maxDistance,
1476                                   InputArrayOfArrays masks, bool compactResult );
1477
1478     Ptr<DescriptorExtractor> extractor;
1479     Ptr<DescriptorMatcher> matcher;
1480 };
1481
1482 /****************************************************************************************\
1483 *                                   Drawing functions                                    *
1484 \****************************************************************************************/
1485 struct CV_EXPORTS DrawMatchesFlags
1486 {
1487     enum{ DEFAULT = 0, // Output image matrix will be created (Mat::create),
1488                        // i.e. existing memory of output image may be reused.
1489                        // Two source image, matches and single keypoints will be drawn.
1490                        // For each keypoint only the center point will be drawn (without
1491                        // the circle around keypoint with keypoint size and orientation).
1492           DRAW_OVER_OUTIMG = 1, // Output image matrix will not be created (Mat::create).
1493                                 // Matches will be drawn on existing content of output image.
1494           NOT_DRAW_SINGLE_POINTS = 2, // Single keypoints will not be drawn.
1495           DRAW_RICH_KEYPOINTS = 4 // For each keypoint the circle around keypoint with keypoint size and
1496                                   // orientation will be drawn.
1497         };
1498 };
1499
1500 // Draw keypoints.
1501 CV_EXPORTS_W void drawKeypoints( InputArray image, const std::vector<KeyPoint>& keypoints, InputOutputArray outImage,
1502                                const Scalar& color=Scalar::all(-1), int flags=DrawMatchesFlags::DEFAULT );
1503
1504 // Draws matches of keypints from two images on output image.
1505 CV_EXPORTS_W void drawMatches( InputArray img1, const std::vector<KeyPoint>& keypoints1,
1506                              InputArray img2, const std::vector<KeyPoint>& keypoints2,
1507                              const std::vector<DMatch>& matches1to2, InputOutputArray outImg,
1508                              const Scalar& matchColor=Scalar::all(-1), const Scalar& singlePointColor=Scalar::all(-1),
1509                              const std::vector<char>& matchesMask=std::vector<char>(), int flags=DrawMatchesFlags::DEFAULT );
1510
1511 CV_EXPORTS_AS(drawMatchesKnn) void drawMatches( InputArray img1, const std::vector<KeyPoint>& keypoints1,
1512                              InputArray img2, const std::vector<KeyPoint>& keypoints2,
1513                              const std::vector<std::vector<DMatch> >& matches1to2, InputOutputArray outImg,
1514                              const Scalar& matchColor=Scalar::all(-1), const Scalar& singlePointColor=Scalar::all(-1),
1515                              const std::vector<std::vector<char> >& matchesMask=std::vector<std::vector<char> >(), int flags=DrawMatchesFlags::DEFAULT );
1516
1517 /****************************************************************************************\
1518 *   Functions to evaluate the feature detectors and [generic] descriptor extractors      *
1519 \****************************************************************************************/
1520
1521 CV_EXPORTS void evaluateFeatureDetector( const Mat& img1, const Mat& img2, const Mat& H1to2,
1522                                          std::vector<KeyPoint>* keypoints1, std::vector<KeyPoint>* keypoints2,
1523                                          float& repeatability, int& correspCount,
1524                                          const Ptr<FeatureDetector>& fdetector=Ptr<FeatureDetector>() );
1525
1526 CV_EXPORTS void computeRecallPrecisionCurve( const std::vector<std::vector<DMatch> >& matches1to2,
1527                                              const std::vector<std::vector<uchar> >& correctMatches1to2Mask,
1528                                              std::vector<Point2f>& recallPrecisionCurve );
1529
1530 CV_EXPORTS float getRecall( const std::vector<Point2f>& recallPrecisionCurve, float l_precision );
1531 CV_EXPORTS int getNearestPoint( const std::vector<Point2f>& recallPrecisionCurve, float l_precision );
1532
1533 CV_EXPORTS void evaluateGenericDescriptorMatcher( const Mat& img1, const Mat& img2, const Mat& H1to2,
1534                                                   std::vector<KeyPoint>& keypoints1, std::vector<KeyPoint>& keypoints2,
1535                                                   std::vector<std::vector<DMatch> >* matches1to2, std::vector<std::vector<uchar> >* correctMatches1to2Mask,
1536                                                   std::vector<Point2f>& recallPrecisionCurve,
1537                                                   const Ptr<GenericDescriptorMatcher>& dmatch=Ptr<GenericDescriptorMatcher>() );
1538
1539
1540 /****************************************************************************************\
1541 *                                     Bag of visual words                                *
1542 \****************************************************************************************/
1543 /*
1544  * Abstract base class for training of a 'bag of visual words' vocabulary from a set of descriptors
1545  */
1546 class CV_EXPORTS BOWTrainer
1547 {
1548 public:
1549     BOWTrainer();
1550     virtual ~BOWTrainer();
1551
1552     void add( const Mat& descriptors );
1553     const std::vector<Mat>& getDescriptors() const;
1554     int descriptorsCount() const;
1555
1556     virtual void clear();
1557
1558     /*
1559      * Train visual words vocabulary, that is cluster training descriptors and
1560      * compute cluster centers.
1561      * Returns cluster centers.
1562      *
1563      * descriptors      Training descriptors computed on images keypoints.
1564      */
1565     virtual Mat cluster() const = 0;
1566     virtual Mat cluster( const Mat& descriptors ) const = 0;
1567
1568 protected:
1569     std::vector<Mat> descriptors;
1570     int size;
1571 };
1572
1573 /*
1574  * This is BOWTrainer using cv::kmeans to get vocabulary.
1575  */
1576 class CV_EXPORTS BOWKMeansTrainer : public BOWTrainer
1577 {
1578 public:
1579     BOWKMeansTrainer( int clusterCount, const TermCriteria& termcrit=TermCriteria(),
1580                       int attempts=3, int flags=KMEANS_PP_CENTERS );
1581     virtual ~BOWKMeansTrainer();
1582
1583     // Returns trained vocabulary (i.e. cluster centers).
1584     virtual Mat cluster() const;
1585     virtual Mat cluster( const Mat& descriptors ) const;
1586
1587 protected:
1588
1589     int clusterCount;
1590     TermCriteria termcrit;
1591     int attempts;
1592     int flags;
1593 };
1594
1595 /*
1596  * Class to compute image descriptor using bag of visual words.
1597  */
1598 class CV_EXPORTS BOWImgDescriptorExtractor
1599 {
1600 public:
1601     BOWImgDescriptorExtractor( const Ptr<DescriptorExtractor>& dextractor,
1602                                const Ptr<DescriptorMatcher>& dmatcher );
1603     BOWImgDescriptorExtractor( const Ptr<DescriptorMatcher>& dmatcher );
1604     virtual ~BOWImgDescriptorExtractor();
1605
1606     void setVocabulary( const Mat& vocabulary );
1607     const Mat& getVocabulary() const;
1608     void compute( InputArray image, std::vector<KeyPoint>& keypoints, OutputArray imgDescriptor,
1609                   std::vector<std::vector<int> >* pointIdxsOfClusters=0, Mat* descriptors=0 );
1610     void compute( InputArray keypointDescriptors, OutputArray imgDescriptor,
1611                   std::vector<std::vector<int> >* pointIdxsOfClusters=0 );
1612     // compute() is not constant because DescriptorMatcher::match is not constant
1613
1614     int descriptorSize() const;
1615     int descriptorType() const;
1616
1617 protected:
1618     Mat vocabulary;
1619     Ptr<DescriptorExtractor> dextractor;
1620     Ptr<DescriptorMatcher> dmatcher;
1621 };
1622
1623 } /* namespace cv */
1624
1625 #endif