1 /*M///////////////////////////////////////////////////////////////////////////////////////
3 // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
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.
11 // For Open Source Computer Vision Library
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.
17 // Redistribution and use in source and binary forms, with or without modification,
18 // are permitted provided that the following conditions are met:
20 // * Redistribution's of source code must retain the above copyright notice,
21 // this list of conditions and the following disclaimer.
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.
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.
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.
43 #ifndef __OPENCV_FEATURES_2D_HPP__
44 #define __OPENCV_FEATURES_2D_HPP__
46 #include "opencv2/core/core.hpp"
47 #include "opencv2/flann/miniflann.hpp"
55 CV_EXPORTS bool initModule_features2d();
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.
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.
69 class CV_EXPORTS_W_SIMPLE KeyPoint
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) {}
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);
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);
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)
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);
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.
121 class CV_EXPORTS KeyPointsFilter
127 * Remove keypoints within borderPixels of an image edge.
129 static void runByImageBorder( vector<KeyPoint>& keypoints, Size imageSize, int borderSize );
131 * Remove keypoints of sizes out of range.
133 static void runByKeypointSize( vector<KeyPoint>& keypoints, float minSize,
134 float maxSize=FLT_MAX );
136 * Remove keypoints from some image by mask for pixels of this image.
138 static void runByPixelsMask( vector<KeyPoint>& keypoints, const Mat& mask );
140 * Remove duplicated keypoints.
142 static void removeDuplicated( vector<KeyPoint>& keypoints );
145 * Retain the specified number of the best keypoints (according to the response)
147 static void retainBest( vector<KeyPoint>& keypoints, int npoints );
151 /************************************ Base Classes ************************************/
154 * Abstract base class for 2D image feature detectors.
156 class CV_EXPORTS_W FeatureDetector : public virtual Algorithm
159 virtual ~FeatureDetector();
162 * Detect keypoints in an 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.
168 CV_WRAP void detect( const Mat& image, CV_OUT vector<KeyPoint>& keypoints, const Mat& mask=Mat() ) const;
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].
176 void detect( const vector<Mat>& images, vector<vector<KeyPoint> >& keypoints, const vector<Mat>& masks=vector<Mat>() ) const;
178 // Return true if detector object is empty
179 CV_WRAP virtual bool empty() const;
181 // Create feature detector by detector name.
182 CV_WRAP static Ptr<FeatureDetector> create( const string& detectorType );
185 virtual void detectImpl( const Mat& image, vector<KeyPoint>& keypoints, const Mat& mask=Mat() ) const = 0;
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.
192 static void removeInvalidPoints( const Mat& mask, vector<KeyPoint>& keypoints );
197 * Abstract base class for computing descriptors for image keypoints.
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.
205 class CV_EXPORTS_W DescriptorExtractor : public virtual Algorithm
208 virtual ~DescriptorExtractor();
211 * Compute the descriptors for a set of keypoints in an 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.
216 CV_WRAP void compute( const Mat& image, CV_OUT CV_IN_OUT vector<KeyPoint>& keypoints, CV_OUT Mat& descriptors ) const;
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].
225 void compute( const vector<Mat>& images, vector<vector<KeyPoint> >& keypoints, vector<Mat>& descriptors ) const;
227 CV_WRAP virtual int descriptorSize() const = 0;
228 CV_WRAP virtual int descriptorType() const = 0;
230 CV_WRAP virtual bool empty() const;
232 CV_WRAP static Ptr<DescriptorExtractor> create( const string& descriptorExtractorType );
235 virtual void computeImpl( const Mat& image, vector<KeyPoint>& keypoints, Mat& descriptors ) const = 0;
238 * Remove keypoints within borderPixels of an image edge.
240 static void removeBorderKeypoints( vector<KeyPoint>& keypoints,
241 Size imageSize, int borderSize );
247 * Abstract base class for simultaneous 2D feature detection descriptor extraction.
249 class CV_EXPORTS_W Feature2D : public FeatureDetector, public DescriptorExtractor
253 * Detect keypoints in an 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
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;
266 // Create feature detector and descriptor extractor by name.
267 CV_WRAP static Ptr<Feature2D> create( const string& name );
273 class CV_EXPORTS_W BRISK : public Feature2D
276 CV_WRAP explicit BRISK(int thresh=30, int octaves=3, float patternScale=1.0f);
280 // returns the descriptor size in bytes
281 int descriptorSize() const;
282 // returns the descriptor type
283 int descriptorType() const;
285 // Compute the BRISK features on an image
286 void operator()(InputArray image, InputArray mask, vector<KeyPoint>& keypoints) const;
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;
292 AlgorithmInfo* info() const;
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>());
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>());
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;
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;
315 // Feature parameters
316 CV_PROP_RW int threshold;
317 CV_PROP_RW int octaves;
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
325 struct BriskShortPair{
326 unsigned int i; // index of the first pattern point
327 unsigned int j; // index of other pattern point
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
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
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
358 static const float basicSize_;
365 class CV_EXPORTS_W ORB : public Feature2D
368 // the size of the signature in bytes
369 enum { kBytes = 32, HARRIS_SCORE=0, FAST_SCORE=1 };
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 );
374 // returns the descriptor size in bytes
375 int descriptorSize() const;
376 // returns the descriptor type
377 int descriptorType() const;
379 // Compute the ORB features and descriptors on an image
380 void operator()(InputArray image, InputArray mask, vector<KeyPoint>& keypoints) const;
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;
386 AlgorithmInfo* info() const;
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;
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;
403 typedef ORB OrbFeatureDetector;
404 typedef ORB OrbDescriptorExtractor;
409 class CV_EXPORTS FREAK : public DescriptorExtractor
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
419 explicit FREAK( bool orientationNormalized = true,
420 bool scaleNormalized = true,
421 float patternScale = 22.0f,
423 const vector<int>& selectedPairs = vector<int>());
424 FREAK( const FREAK& rhs );
425 FREAK& operator=( const FREAK& );
429 /** returns the descriptor length in bytes */
430 virtual int descriptorSize() const;
432 /** returns the descriptor type */
433 virtual int descriptorType() const;
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
442 vector<int> selectPairs( const vector<Mat>& images, vector<vector<KeyPoint> >& keypoints,
443 const double corrThresh = 0.7, bool verbose = true );
445 AlgorithmInfo* info() const;
449 NB_SCALES = 64, NB_PAIRS = 512, NB_ORIENPAIRS = 45
453 virtual void computeImpl( const Mat& image, vector<KeyPoint>& keypoints, Mat& descriptors ) const;
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;
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
464 double patternScale0;
466 vector<int> selectedPairs0;
470 float x; // x coordinate relative to center
471 float y; // x coordinate relative to center
472 float sigma; // Gaussian smoothing sigma
475 struct DescriptionPair
477 uchar i; // index of the first point
478 uchar j; // index of the second point
481 struct OrientationPair
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
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];
497 Maximal Stable Extremal Regions class.
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.
503 It returns the regions, each of those is encoded as a contour.
505 class CV_EXPORTS_W MSER : public FeatureDetector
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 );
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;
520 void detectImpl( const Mat& image, vector<KeyPoint>& keypoints, const Mat& mask=Mat() ) const;
528 double areaThreshold;
533 typedef MSER MserFeatureDetector;
538 The class implements the keypoint detector introduced by K. Konolige.
540 class CV_EXPORTS_W StarDetector : public FeatureDetector
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);
549 //! finds the keypoints in the image
550 CV_WRAP_AS(detect) void operator()(const Mat& image,
551 CV_OUT vector<KeyPoint>& keypoints) const;
553 AlgorithmInfo* info() const;
556 void detectImpl( const Mat& image, vector<KeyPoint>& keypoints, const Mat& mask=Mat() ) const;
559 int responseThreshold;
560 int lineThresholdProjected;
561 int lineThresholdBinarized;
562 int suppressNonmaxSize;
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 );
569 CV_EXPORTS void FASTX( InputArray image, CV_OUT vector<KeyPoint>& keypoints,
570 int threshold, bool nonmaxSupression, int type );
572 class CV_EXPORTS_W FastFeatureDetector : public FeatureDetector
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
581 CV_WRAP FastFeatureDetector( int threshold=10, bool nonmaxSuppression=true );
582 AlgorithmInfo* info() const;
585 virtual void detectImpl( const Mat& image, vector<KeyPoint>& keypoints, const Mat& mask=Mat() ) const;
588 bool nonmaxSuppression;
592 class CV_EXPORTS GFTTDetector : public FeatureDetector
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;
600 virtual void detectImpl( const Mat& image, vector<KeyPoint>& keypoints, const Mat& mask=Mat() ) const;
606 bool useHarrisDetector;
610 typedef GFTTDetector GoodFeaturesToTrackDetector;
611 typedef StarDetector StarFeatureDetector;
613 class CV_EXPORTS_W SimpleBlobDetector : public FeatureDetector
616 struct CV_EXPORTS_W_SIMPLE 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;
625 CV_PROP_RW bool filterByColor;
626 CV_PROP_RW uchar blobColor;
628 CV_PROP_RW bool filterByArea;
629 CV_PROP_RW float minArea, maxArea;
631 CV_PROP_RW bool filterByCircularity;
632 CV_PROP_RW float minCircularity, maxCircularity;
634 CV_PROP_RW bool filterByInertia;
635 CV_PROP_RW float minInertiaRatio, maxInertiaRatio;
637 CV_PROP_RW bool filterByConvexity;
638 CV_PROP_RW float minConvexity, maxConvexity;
640 void read( const FileNode& fn );
641 void write( FileStorage& fs ) const;
644 CV_WRAP SimpleBlobDetector(const SimpleBlobDetector::Params ¶meters = SimpleBlobDetector::Params());
646 virtual void read( const FileNode& fn );
647 virtual void write( FileStorage& fs ) const;
650 struct CV_EXPORTS Center
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> ¢ers) const;
661 AlgorithmInfo* info() const;
665 class CV_EXPORTS DenseFeatureDetector : public FeatureDetector
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;
676 virtual void detectImpl( const Mat& image, vector<KeyPoint>& keypoints, const Mat& mask=Mat() ) const;
678 double initFeatureScale;
679 int featureScaleLevels;
680 double featureScaleMul;
685 bool varyXyStepWithScale;
686 bool varyImgBoundWithScale;
690 * Adapts a detector to partition the source image into a grid and detect
691 * points in each cell.
693 class CV_EXPORTS_W GridAdaptedFeatureDetector : public FeatureDetector
697 * detector Detector that will be adapted.
698 * maxTotalKeypoints Maximum count of keypoints detected on the image. Only the strongest keypoints
700 * gridRows Grid rows count.
701 * gridCols Grid column count.
703 CV_WRAP GridAdaptedFeatureDetector( const Ptr<FeatureDetector>& detector=0,
704 int maxTotalKeypoints=1000,
705 int gridRows=4, int gridCols=4 );
707 // TODO implement read/write
708 virtual bool empty() const;
710 AlgorithmInfo* info() const;
713 virtual void detectImpl( const Mat& image, vector<KeyPoint>& keypoints, const Mat& mask=Mat() ) const;
715 Ptr<FeatureDetector> detector;
716 int maxTotalKeypoints;
722 * Adapts a detector to detect points over multiple levels of a Gaussian
723 * pyramid. Useful for detectors that are not inherently scaled.
725 class CV_EXPORTS_W PyramidAdaptedFeatureDetector : public FeatureDetector
728 // maxLevel - The 0-based index of the last pyramid layer
729 CV_WRAP PyramidAdaptedFeatureDetector( const Ptr<FeatureDetector>& detector, int maxLevel=2 );
731 // TODO implement read/write
732 virtual bool empty() const;
735 virtual void detectImpl( const Mat& image, vector<KeyPoint>& keypoints, const Mat& mask=Mat() ) const;
737 Ptr<FeatureDetector> detector;
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
744 class CV_EXPORTS AdjusterAdapter: public FeatureDetector
747 /** pure virtual interface
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
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
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
763 virtual bool good() const = 0;
765 virtual Ptr<AdjusterAdapter> clone() const = 0;
767 static Ptr<AdjusterAdapter> create( const string& detectorType );
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
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));
781 class CV_EXPORTS DynamicAdaptedFeatureDetector: public FeatureDetector
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
791 DynamicAdaptedFeatureDetector( const Ptr<AdjusterAdapter>& adjuster, int min_features=400, int max_features=500, int max_iters=5 );
793 virtual bool empty() const;
796 virtual void detectImpl( const Mat& image, vector<KeyPoint>& keypoints, const Mat& mask=Mat() ) const;
799 DynamicAdaptedFeatureDetector& operator=(const DynamicAdaptedFeatureDetector&);
800 DynamicAdaptedFeatureDetector(const DynamicAdaptedFeatureDetector&);
803 int min_features_, max_features_;
804 const Ptr<AdjusterAdapter> adjuster_;
807 /**\brief an adjust for the FAST detector. This will basically decrement or increment the
810 class CV_EXPORTS FastAdjuster: public AdjusterAdapter
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
816 FastAdjuster(int init_thresh=20, bool nonmax=true, int min_thresh=1, int max_thresh=200);
818 virtual void tooFew(int minv, int n_detected);
819 virtual void tooMany(int maxv, int n_detected);
820 virtual bool good() const;
822 virtual Ptr<AdjusterAdapter> clone() const;
825 virtual void detectImpl( const Mat& image, vector<KeyPoint>& keypoints, const Mat& mask=Mat() ) const;
829 int init_thresh_, min_thresh_, max_thresh_;
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
836 class CV_EXPORTS StarAdjuster: public AdjusterAdapter
839 StarAdjuster(double initial_thresh=30.0, double min_thresh=2., double max_thresh=200.);
841 virtual void tooFew(int minv, int n_detected);
842 virtual void tooMany(int maxv, int n_detected);
843 virtual bool good() const;
845 virtual Ptr<AdjusterAdapter> clone() const;
848 virtual void detectImpl( const Mat& image, vector<KeyPoint>& keypoints, const Mat& mask=Mat() ) const;
850 double thresh_, init_thresh_, min_thresh_, max_thresh_;
853 class CV_EXPORTS SurfAdjuster: public AdjusterAdapter
856 SurfAdjuster( double initial_thresh=400.f, double min_thresh=2, double max_thresh=1000 );
858 virtual void tooFew(int minv, int n_detected);
859 virtual void tooMany(int maxv, int n_detected);
860 virtual bool good() const;
862 virtual Ptr<AdjusterAdapter> clone() const;
865 virtual void detectImpl( const Mat& image, vector<KeyPoint>& keypoints, const Mat& mask=Mat() ) const;
867 double thresh_, init_thresh_, min_thresh_, max_thresh_;
870 CV_EXPORTS Mat windowedMatchingMask( const vector<KeyPoint>& keypoints1, const vector<KeyPoint>& keypoints2,
871 float maxDeltaX, float maxDeltaY );
876 * OpponentColorDescriptorExtractor
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.
884 class CV_EXPORTS OpponentColorDescriptorExtractor : public DescriptorExtractor
887 OpponentColorDescriptorExtractor( const Ptr<DescriptorExtractor>& descriptorExtractor );
889 virtual void read( const FileNode& );
890 virtual void write( FileStorage& ) const;
892 virtual int descriptorSize() const;
893 virtual int descriptorType() const;
895 virtual bool empty() const;
898 virtual void computeImpl( const Mat& image, vector<KeyPoint>& keypoints, Mat& descriptors ) const;
900 Ptr<DescriptorExtractor> descriptorExtractor;
906 class CV_EXPORTS BriefDescriptorExtractor : public DescriptorExtractor
909 static const int PATCH_SIZE = 48;
910 static const int KERNEL_SIZE = 9;
912 // bytes is a length of descriptor in bytes. It can be equal 16, 32 or 64 bytes.
913 BriefDescriptorExtractor( int bytes = 32 );
915 virtual void read( const FileNode& );
916 virtual void write( FileStorage& ) const;
918 virtual int descriptorSize() const;
919 virtual int descriptorType() const;
921 /// @todo read and write for brief
923 AlgorithmInfo* info() const;
926 virtual void computeImpl(const Mat& image, vector<KeyPoint>& keypoints, Mat& descriptors) const;
928 typedef void(*PixelTestFn)(const Mat&, const vector<KeyPoint>&, Mat&);
931 PixelTestFn test_fn_;
935 /****************************************************************************************\
937 \****************************************************************************************/
940 struct CV_EXPORTS Accumulator
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; };
951 * Squared Euclidean distance functor
954 struct CV_EXPORTS SL2
956 enum { normType = NORM_L2SQR };
958 typedef typename Accumulator<T>::Type ResultType;
960 ResultType operator()( const T* a, const T* b, int size ) const
962 return normL2Sqr<ValueType, ResultType>(a, b, size);
967 * Euclidean distance functor
972 enum { normType = NORM_L2 };
974 typedef typename Accumulator<T>::Type ResultType;
976 ResultType operator()( const T* a, const T* b, int size ) const
978 return (ResultType)sqrt((double)normL2Sqr<ValueType, ResultType>(a, b, size));
983 * Manhattan distance (city block distance) functor
988 enum { normType = NORM_L1 };
990 typedef typename Accumulator<T>::Type ResultType;
992 ResultType operator()( const T* a, const T* b, int size ) const
994 return normL1<ValueType, ResultType>(a, b, size);
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
1002 struct CV_EXPORTS Hamming
1004 enum { normType = NORM_HAMMING };
1005 typedef unsigned char ValueType;
1006 typedef int ResultType;
1008 /** this will count the bits in a ^ b
1010 ResultType operator()( const unsigned char* a, const unsigned char* b, int size ) const
1012 return normHamming(a, b, size);
1016 typedef Hamming HammingLUT;
1018 template<int cellsize> struct CV_EXPORTS HammingMultilevel
1020 enum { normType = NORM_HAMMING + (cellsize>1) };
1021 typedef unsigned char ValueType;
1022 typedef int ResultType;
1024 ResultType operator()( const unsigned char* a, const unsigned char* b, int size ) const
1026 return normHamming(a, b, size, cellsize);
1030 /****************************************************************************************\
1032 \****************************************************************************************/
1034 * Struct for matching: query descriptor index, train descriptor index, train image index and distance between descriptors.
1036 struct CV_EXPORTS_W_SIMPLE DMatch
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) {}
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
1048 CV_PROP_RW float distance;
1051 bool operator<( const DMatch &m ) const
1053 return distance < m.distance;
1057 /****************************************************************************************\
1058 * DescriptorMatcher *
1059 \****************************************************************************************/
1061 * Abstract base class for matching two sets of descriptors.
1063 class CV_EXPORTS_W DescriptorMatcher : public Algorithm
1066 virtual ~DescriptorMatcher();
1069 * Add descriptors to train descriptor collection.
1070 * descriptors Descriptors to add. Each descriptors[i] is a descriptors set from one image.
1072 CV_WRAP virtual void add( const vector<Mat>& descriptors );
1074 * Get train descriptors collection.
1076 CV_WRAP const vector<Mat>& getTrainDescriptors() const;
1078 * Clear train descriptors collection.
1080 CV_WRAP virtual void clear();
1083 * Return true if there are not train descriptors in collection.
1085 CV_WRAP virtual bool empty() const;
1087 * Return true if the matcher supports mask in match methods.
1089 CV_WRAP virtual bool isMaskSupported() const = 0;
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
1102 CV_WRAP virtual void train();
1104 * Group of methods to match descriptors from image pair.
1105 * Method train() is run in this methods.
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;
1123 * Group of methods to match descriptors from one image to image set.
1124 * See description of similar methods for matching image pair above.
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 );
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;
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;
1143 CV_WRAP static Ptr<DescriptorMatcher> create( const string& descriptorMatcherType );
1146 * Class to work with descriptors from several images as with one merged matrix.
1147 * It is used e.g. in FlannBasedMatcher.
1149 class CV_EXPORTS DescriptorCollection
1152 DescriptorCollection();
1153 DescriptorCollection( const DescriptorCollection& collection );
1154 virtual ~DescriptorCollection();
1156 // Vector of matrices "descriptors" will be merged to one matrix "mergedDescriptors" here.
1157 void set( const vector<Mat>& descriptors );
1158 virtual void clear();
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;
1168 Mat mergedDescriptors;
1169 vector<int> startIdxs;
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;
1180 static bool isPossibleMatch( const Mat& mask, int queryIdx, int trainIdx );
1181 static bool isMaskedOut( const vector<Mat>& masks, int queryIdx );
1183 static Mat clone_op( Mat m ) { return m.clone(); }
1184 void checkMasks( const vector<Mat>& masks, int queryDescriptorsCount ) const;
1186 // Collection of descriptors from train images.
1187 vector<Mat> trainDescCollection;
1191 * Brute-force descriptor matcher.
1193 * For each descriptor in the first set, this matcher finds the closest
1194 * descriptor in the second set by trying each one.
1196 * For efficiency, BruteForceMatcher is templated on the distance metric.
1197 * For float descriptors, a common choice would be cv::L2<float>.
1199 class CV_EXPORTS_W BFMatcher : public DescriptorMatcher
1202 CV_WRAP BFMatcher( int normType=NORM_L2, bool crossCheck=false );
1203 virtual ~BFMatcher() {}
1205 virtual bool isMaskSupported() const { return true; }
1207 virtual Ptr<DescriptorMatcher> clone( bool emptyTrainData=false ) const;
1209 AlgorithmInfo* info() const;
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 );
1222 * Flann based matcher
1224 class CV_EXPORTS_W FlannBasedMatcher : public DescriptorMatcher
1227 CV_WRAP FlannBasedMatcher( const Ptr<flann::IndexParams>& indexParams=new flann::KDTreeIndexParams(),
1228 const Ptr<flann::SearchParams>& searchParams=new flann::SearchParams() );
1230 virtual void add( const vector<Mat>& descriptors );
1231 virtual void clear();
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;
1238 virtual void train();
1239 virtual bool isMaskSupported() const;
1241 virtual Ptr<DescriptorMatcher> clone( bool emptyTrainData=false ) const;
1243 AlgorithmInfo* info() const;
1245 static void convertToDMatches( const DescriptorCollection& descriptors,
1246 const Mat& indices, const Mat& distances,
1247 vector<vector<DMatch> >& matches );
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 );
1254 Ptr<flann::IndexParams> indexParams;
1255 Ptr<flann::SearchParams> searchParams;
1256 Ptr<flann::Index> flannIndex;
1258 DescriptorCollection mergedDescriptors;
1262 /****************************************************************************************\
1263 * GenericDescriptorMatcher *
1264 \****************************************************************************************/
1266 * Abstract interface for a keypoint descriptor and matcher
1268 class GenericDescriptorMatcher;
1269 typedef GenericDescriptorMatcher GenericDescriptorMatch;
1271 class CV_EXPORTS GenericDescriptorMatcher
1274 GenericDescriptorMatcher();
1275 virtual ~GenericDescriptorMatcher();
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.
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.
1287 virtual void add( const vector<Mat>& images,
1288 vector<vector<KeyPoint> >& keypoints );
1290 const vector<Mat>& getTrainImages() const;
1291 const vector<vector<KeyPoint> >& getTrainKeypoints() const;
1294 * Clear images and keypoints storing in train collection.
1296 virtual void clear();
1298 * Returns true if matcher supports mask to match descriptors.
1300 virtual bool isMaskSupported() = 0;
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.
1306 virtual void train();
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
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 );
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.
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;
1344 * Group of methods to match keypoints from one image to image set.
1345 * See description of similar methods for matching image pair above.
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 );
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;
1361 // Return true if matching object is empty (e.g. feature detector or descriptor matcher are empty)
1362 virtual bool empty() const;
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;
1369 static Ptr<GenericDescriptorMatcher> create( const string& genericDescritptorMatcherType,
1370 const string ¶msFilename=string() );
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;
1383 * A storage for sets of keypoints together with corresponding images and class IDs
1385 class CV_EXPORTS KeyPointCollection
1388 KeyPointCollection();
1389 KeyPointCollection( const KeyPointCollection& collection );
1390 void add( const vector<Mat>& images, const vector<vector<KeyPoint> >& keypoints );
1393 // Returns the total number of keypoints in the collection
1394 size_t keypointCount() const;
1395 size_t imageCount() const;
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;
1403 const vector<Mat>& getImages() const;
1404 const Mat& getImage( int imgIdx ) const;
1410 vector<vector<KeyPoint> > keypoints;
1411 // global indices of the first points in each image, startIndices.size() = keypoints.size()
1412 vector<int> startIndices;
1415 static Mat clone_op( Mat m ) { return m.clone(); }
1418 KeyPointCollection trainPointCollection;
1422 /****************************************************************************************\
1423 * VectorDescriptorMatcher *
1424 \****************************************************************************************/
1427 * A class used for matching descriptors that can be described as vectors in a finite-dimensional space
1429 class VectorDescriptorMatcher;
1430 typedef VectorDescriptorMatcher VectorDescriptorMatch;
1432 class CV_EXPORTS VectorDescriptorMatcher : public GenericDescriptorMatcher
1435 VectorDescriptorMatcher( const Ptr<DescriptorExtractor>& extractor, const Ptr<DescriptorMatcher>& matcher );
1436 virtual ~VectorDescriptorMatcher();
1438 virtual void add( const vector<Mat>& imgCollection,
1439 vector<vector<KeyPoint> >& pointCollection );
1441 virtual void clear();
1443 virtual void train();
1445 virtual bool isMaskSupported();
1447 virtual void read( const FileNode& fn );
1448 virtual void write( FileStorage& fs ) const;
1449 virtual bool empty() const;
1451 virtual Ptr<GenericDescriptorMatcher> clone( bool emptyTrainData=false ) const;
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 );
1461 Ptr<DescriptorExtractor> extractor;
1462 Ptr<DescriptorMatcher> matcher;
1465 /****************************************************************************************\
1466 * Drawing functions *
1467 \****************************************************************************************/
1468 struct CV_EXPORTS DrawMatchesFlags
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.
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 );
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 );
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 );
1500 /****************************************************************************************\
1501 * Functions to evaluate the feature detectors and [generic] descriptor extractors *
1502 \****************************************************************************************/
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>() );
1509 CV_EXPORTS void computeRecallPrecisionCurve( const vector<vector<DMatch> >& matches1to2,
1510 const vector<vector<uchar> >& correctMatches1to2Mask,
1511 vector<Point2f>& recallPrecisionCurve );
1513 CV_EXPORTS float getRecall( const vector<Point2f>& recallPrecisionCurve, float l_precision );
1514 CV_EXPORTS int getNearestPoint( const vector<Point2f>& recallPrecisionCurve, float l_precision );
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>() );
1523 /****************************************************************************************\
1524 * Bag of visual words *
1525 \****************************************************************************************/
1527 * Abstract base class for training of a 'bag of visual words' vocabulary from a set of descriptors
1529 class CV_EXPORTS BOWTrainer
1533 virtual ~BOWTrainer();
1535 void add( const Mat& descriptors );
1536 const vector<Mat>& getDescriptors() const;
1537 int descripotorsCount() const;
1539 virtual void clear();
1542 * Train visual words vocabulary, that is cluster training descriptors and
1543 * compute cluster centers.
1544 * Returns cluster centers.
1546 * descriptors Training descriptors computed on images keypoints.
1548 virtual Mat cluster() const = 0;
1549 virtual Mat cluster( const Mat& descriptors ) const = 0;
1552 vector<Mat> descriptors;
1557 * This is BOWTrainer using cv::kmeans to get vocabulary.
1559 class CV_EXPORTS BOWKMeansTrainer : public BOWTrainer
1562 BOWKMeansTrainer( int clusterCount, const TermCriteria& termcrit=TermCriteria(),
1563 int attempts=3, int flags=KMEANS_PP_CENTERS );
1564 virtual ~BOWKMeansTrainer();
1566 // Returns trained vocabulary (i.e. cluster centers).
1567 virtual Mat cluster() const;
1568 virtual Mat cluster( const Mat& descriptors ) const;
1573 TermCriteria termcrit;
1579 * Class to compute image descriptor using bag of visual words.
1581 class CV_EXPORTS BOWImgDescriptorExtractor
1584 BOWImgDescriptorExtractor( const Ptr<DescriptorExtractor>& dextractor,
1585 const Ptr<DescriptorMatcher>& dmatcher );
1586 virtual ~BOWImgDescriptorExtractor();
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
1594 int descriptorSize() const;
1595 int descriptorType() const;
1599 Ptr<DescriptorExtractor> dextractor;
1600 Ptr<DescriptorMatcher> dmatcher;
1603 } /* namespace cv */
1605 #endif /* __cplusplus */