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