Merge pull request #1263 from abidrahmank:pyCLAHE_24
[profile/ivi/opencv.git] / modules / features2d / doc / common_interfaces_of_feature_detectors.rst
1 Common Interfaces of Feature Detectors
2 ======================================
3
4 .. highlight:: cpp
5
6 Feature detectors in OpenCV have wrappers with a common interface that enables you to easily switch
7 between different algorithms solving the same problem. All objects that implement keypoint detectors
8 inherit the
9 :ocv:class:`FeatureDetector` interface.
10
11 .. note::
12
13    * An example explaining keypoint detection can be found at opencv_source_code/samples/cpp/descriptor_extractor_matcher.cpp
14
15
16 KeyPoint
17 --------
18 .. ocv:class:: KeyPoint
19
20   Data structure for salient point detectors.
21
22   .. ocv:member:: Point2f pt
23
24      coordinates of the keypoint
25
26   .. ocv:member:: float size
27
28      diameter of the meaningful keypoint neighborhood
29
30   .. ocv:member:: float angle
31
32      computed orientation of the keypoint (-1 if not applicable). Its possible values are in a range [0,360) degrees. It is measured relative to image coordinate system (y-axis is directed downward), ie in clockwise.
33
34   .. ocv:member:: float response
35
36      the response by which the most strong keypoints have been selected. Can be used for further sorting or subsampling
37
38   .. ocv:member:: int octave
39
40      octave (pyramid layer) from which the keypoint has been extracted
41
42   .. ocv:member:: int class_id
43
44      object id that can be used to clustered keypoints by an object they belong to
45
46 KeyPoint::KeyPoint
47 ------------------
48 The keypoint constructors
49
50 .. ocv:function:: KeyPoint::KeyPoint()
51
52 .. ocv:function:: KeyPoint::KeyPoint(Point2f _pt, float _size, float _angle=-1, float _response=0, int _octave=0, int _class_id=-1)
53
54 .. ocv:function:: KeyPoint::KeyPoint(float x, float y, float _size, float _angle=-1, float _response=0, int _octave=0, int _class_id=-1)
55
56 .. ocv:pyfunction:: cv2.KeyPoint([x, y, _size[, _angle[, _response[, _octave[, _class_id]]]]]) -> <KeyPoint object>
57
58     :param x: x-coordinate of the keypoint
59
60     :param y: y-coordinate of the keypoint
61
62     :param _pt: x & y coordinates of the keypoint
63
64     :param _size: keypoint diameter
65
66     :param _angle: keypoint orientation
67
68     :param _response: keypoint detector response on the keypoint (that is, strength of the keypoint)
69
70     :param _octave: pyramid octave in which the keypoint has been detected
71
72     :param _class_id: object id
73
74
75 FeatureDetector
76 ---------------
77 .. ocv:class:: FeatureDetector : public Algorithm
78
79 Abstract base class for 2D image feature detectors. ::
80
81     class CV_EXPORTS FeatureDetector
82     {
83     public:
84         virtual ~FeatureDetector();
85
86         void detect( const Mat& image, vector<KeyPoint>& keypoints,
87                      const Mat& mask=Mat() ) const;
88
89         void detect( const vector<Mat>& images,
90                      vector<vector<KeyPoint> >& keypoints,
91                      const vector<Mat>& masks=vector<Mat>() ) const;
92
93         virtual void read(const FileNode&);
94         virtual void write(FileStorage&) const;
95
96         static Ptr<FeatureDetector> create( const string& detectorType );
97
98     protected:
99     ...
100     };
101
102 FeatureDetector::detect
103 ---------------------------
104 Detects keypoints in an image (first variant) or image set (second variant).
105
106 .. ocv:function:: void FeatureDetector::detect( const Mat& image, vector<KeyPoint>& keypoints, const Mat& mask=Mat() ) const
107
108 .. ocv:function:: void FeatureDetector::detect( const vector<Mat>& images, vector<vector<KeyPoint> >& keypoints, const vector<Mat>& masks=vector<Mat>() ) const
109
110     :param image: Image.
111
112     :param images: Image set.
113
114     :param keypoints: The detected keypoints. In the second variant of the method ``keypoints[i]`` is a set of keypoints detected in ``images[i]`` .
115
116     :param mask: Mask specifying where to look for keypoints (optional). It must be a 8-bit integer matrix with non-zero values in the region of interest.
117
118     :param masks: Masks for each input image specifying where to look for keypoints (optional). ``masks[i]`` is a mask for ``images[i]``.
119
120 FeatureDetector::create
121 -----------------------
122 Creates a feature detector by its name.
123
124 .. ocv:function:: Ptr<FeatureDetector> FeatureDetector::create( const string& detectorType )
125
126     :param detectorType: Feature detector type.
127
128 The following detector types are supported:
129
130 * ``"FAST"`` -- :ocv:class:`FastFeatureDetector`
131 * ``"STAR"`` -- :ocv:class:`StarFeatureDetector`
132 * ``"SIFT"`` -- :ocv:class:`SIFT` (nonfree module)
133 * ``"SURF"`` -- :ocv:class:`SURF` (nonfree module)
134 * ``"ORB"`` -- :ocv:class:`ORB`
135 * ``"BRISK"`` -- :ocv:class:`BRISK`
136 * ``"MSER"`` -- :ocv:class:`MSER`
137 * ``"GFTT"`` -- :ocv:class:`GoodFeaturesToTrackDetector`
138 * ``"HARRIS"`` -- :ocv:class:`GoodFeaturesToTrackDetector` with Harris detector enabled
139 * ``"Dense"`` -- :ocv:class:`DenseFeatureDetector`
140 * ``"SimpleBlob"`` -- :ocv:class:`SimpleBlobDetector`
141
142 Also a combined format is supported: feature detector adapter name ( ``"Grid"`` --
143 :ocv:class:`GridAdaptedFeatureDetector`, ``"Pyramid"`` --
144 :ocv:class:`PyramidAdaptedFeatureDetector` ) + feature detector name (see above),
145 for example: ``"GridFAST"``, ``"PyramidSTAR"`` .
146
147 FastFeatureDetector
148 -------------------
149 .. ocv:class:: FastFeatureDetector : public FeatureDetector
150
151 Wrapping class for feature detection using the
152 :ocv:func:`FAST` method. ::
153
154     class FastFeatureDetector : public FeatureDetector
155     {
156     public:
157         FastFeatureDetector( int threshold=1, bool nonmaxSuppression=true, type=FastFeatureDetector::TYPE_9_16 );
158         virtual void read( const FileNode& fn );
159         virtual void write( FileStorage& fs ) const;
160     protected:
161         ...
162     };
163
164 GoodFeaturesToTrackDetector
165 ---------------------------
166 .. ocv:class:: GoodFeaturesToTrackDetector : public FeatureDetector
167
168 Wrapping class for feature detection using the
169 :ocv:func:`goodFeaturesToTrack` function. ::
170
171     class GoodFeaturesToTrackDetector : public FeatureDetector
172     {
173     public:
174         class Params
175         {
176         public:
177             Params( int maxCorners=1000, double qualityLevel=0.01,
178                     double minDistance=1., int blockSize=3,
179                     bool useHarrisDetector=false, double k=0.04 );
180             void read( const FileNode& fn );
181             void write( FileStorage& fs ) const;
182
183             int maxCorners;
184             double qualityLevel;
185             double minDistance;
186             int blockSize;
187             bool useHarrisDetector;
188             double k;
189         };
190
191         GoodFeaturesToTrackDetector( const GoodFeaturesToTrackDetector::Params& params=
192                                                 GoodFeaturesToTrackDetector::Params() );
193         GoodFeaturesToTrackDetector( int maxCorners, double qualityLevel,
194                                      double minDistance, int blockSize=3,
195                                      bool useHarrisDetector=false, double k=0.04 );
196         virtual void read( const FileNode& fn );
197         virtual void write( FileStorage& fs ) const;
198     protected:
199         ...
200     };
201
202 MserFeatureDetector
203 -------------------
204 .. ocv:class:: MserFeatureDetector : public FeatureDetector
205
206 Wrapping class for feature detection using the
207 :ocv:class:`MSER` class. ::
208
209     class MserFeatureDetector : public FeatureDetector
210     {
211     public:
212         MserFeatureDetector( CvMSERParams params=cvMSERParams() );
213         MserFeatureDetector( int delta, int minArea, int maxArea,
214                              double maxVariation, double minDiversity,
215                              int maxEvolution, double areaThreshold,
216                              double minMargin, int edgeBlurSize );
217         virtual void read( const FileNode& fn );
218         virtual void write( FileStorage& fs ) const;
219     protected:
220         ...
221     };
222
223
224 StarFeatureDetector
225 -------------------
226 .. ocv:class:: StarFeatureDetector : public FeatureDetector
227
228 The class implements the keypoint detector introduced by [Agrawal08]_, synonym of ``StarDetector``.  ::
229
230     class StarFeatureDetector : public FeatureDetector
231     {
232     public:
233         StarFeatureDetector( int maxSize=16, int responseThreshold=30,
234                              int lineThresholdProjected = 10,
235                              int lineThresholdBinarized=8, int suppressNonmaxSize=5 );
236         virtual void read( const FileNode& fn );
237         virtual void write( FileStorage& fs ) const;
238     protected:
239         ...
240     };
241
242 .. [Agrawal08] Agrawal, M., Konolige, K., & Blas, M. R. (2008). Censure: Center surround extremas for realtime feature detection and matching. In Computer Vision–ECCV 2008 (pp. 102-115). Springer Berlin Heidelberg.
243
244
245 DenseFeatureDetector
246 --------------------
247 .. ocv:class:: DenseFeatureDetector : public FeatureDetector
248
249 Class for generation of image features which are distributed densely and regularly over the image. ::
250
251         class DenseFeatureDetector : public FeatureDetector
252         {
253         public:
254                 DenseFeatureDetector( float initFeatureScale=1.f, int featureScaleLevels=1,
255                               float featureScaleMul=0.1f,
256                               int initXyStep=6, int initImgBound=0,
257                               bool varyXyStepWithScale=true,
258                               bool varyImgBoundWithScale=false );
259         protected:
260         ...
261     };
262
263 The detector generates several levels (in the amount of ``featureScaleLevels``) of features. Features of each level are located in the nodes of a regular grid over the image (excluding the image boundary of given size). The level parameters (a feature scale, a node size, a size of boundary) are multiplied by ``featureScaleMul`` with level index growing depending on input flags, viz.:
264
265 * Feature scale is multiplied always.
266
267 * The grid node size is multiplied if ``varyXyStepWithScale`` is ``true``.
268
269 * Size of image boundary is multiplied if ``varyImgBoundWithScale`` is ``true``.
270
271
272 SimpleBlobDetector
273 -------------------
274 .. ocv:class:: SimpleBlobDetector : public FeatureDetector
275
276 Class for extracting blobs from an image. ::
277
278     class SimpleBlobDetector : public FeatureDetector
279     {
280     public:
281     struct Params
282     {
283         Params();
284         float thresholdStep;
285         float minThreshold;
286         float maxThreshold;
287         size_t minRepeatability;
288         float minDistBetweenBlobs;
289
290         bool filterByColor;
291         uchar blobColor;
292
293         bool filterByArea;
294         float minArea, maxArea;
295
296         bool filterByCircularity;
297         float minCircularity, maxCircularity;
298
299         bool filterByInertia;
300         float minInertiaRatio, maxInertiaRatio;
301
302         bool filterByConvexity;
303         float minConvexity, maxConvexity;
304     };
305
306     SimpleBlobDetector(const SimpleBlobDetector::Params &parameters = SimpleBlobDetector::Params());
307
308     protected:
309         ...
310     };
311
312 The class implements a simple algorithm for extracting blobs from an image:
313
314 #. Convert the source image to binary images by applying thresholding with several thresholds from ``minThreshold`` (inclusive) to ``maxThreshold`` (exclusive) with distance ``thresholdStep`` between neighboring thresholds.
315
316 #. Extract connected components from every binary image by  :ocv:func:`findContours`  and calculate their centers.
317
318 #. Group centers from several binary images by their coordinates. Close centers form one group that corresponds to one blob, which is controlled by the ``minDistBetweenBlobs`` parameter.
319
320 #. From the groups, estimate final centers of blobs and their radiuses and return as locations and sizes of keypoints.
321
322 This class performs several filtrations of returned blobs. You should set ``filterBy*`` to true/false to turn on/off corresponding filtration. Available filtrations:
323
324  * **By color**. This filter compares the intensity of a binary image at the center of a blob to ``blobColor``. If they differ, the blob is filtered out. Use ``blobColor = 0`` to extract dark blobs and ``blobColor = 255`` to extract light blobs.
325
326  * **By area**. Extracted blobs have an area between ``minArea`` (inclusive) and ``maxArea`` (exclusive).
327
328  * **By circularity**. Extracted blobs have circularity (:math:`\frac{4*\pi*Area}{perimeter * perimeter}`) between ``minCircularity`` (inclusive) and ``maxCircularity`` (exclusive).
329
330  * **By ratio of the minimum inertia to maximum inertia**. Extracted blobs have this ratio between ``minInertiaRatio`` (inclusive) and ``maxInertiaRatio`` (exclusive).
331
332  * **By convexity**. Extracted blobs have convexity (area / area of blob convex hull) between ``minConvexity`` (inclusive) and ``maxConvexity`` (exclusive).
333
334
335 Default values of parameters are tuned to extract dark circular blobs.
336
337 GridAdaptedFeatureDetector
338 --------------------------
339 .. ocv:class:: GridAdaptedFeatureDetector : public FeatureDetector
340
341 Class adapting a detector to partition the source image into a grid and detect points in each cell. ::
342
343     class GridAdaptedFeatureDetector : public FeatureDetector
344     {
345     public:
346         /*
347          * detector            Detector that will be adapted.
348          * maxTotalKeypoints   Maximum count of keypoints detected on the image.
349          *                     Only the strongest keypoints will be kept.
350          * gridRows            Grid row count.
351          * gridCols            Grid column count.
352          */
353         GridAdaptedFeatureDetector( const Ptr<FeatureDetector>& detector,
354                                     int maxTotalKeypoints, int gridRows=4,
355                                     int gridCols=4 );
356         virtual void read( const FileNode& fn );
357         virtual void write( FileStorage& fs ) const;
358     protected:
359         ...
360     };
361
362 PyramidAdaptedFeatureDetector
363 -----------------------------
364 .. ocv:class:: PyramidAdaptedFeatureDetector : public FeatureDetector
365
366 Class adapting a detector to detect points over multiple levels of a Gaussian pyramid. Consider using this class for detectors that are not inherently scaled. ::
367
368     class PyramidAdaptedFeatureDetector : public FeatureDetector
369     {
370     public:
371         PyramidAdaptedFeatureDetector( const Ptr<FeatureDetector>& detector,
372                                        int levels=2 );
373         virtual void read( const FileNode& fn );
374         virtual void write( FileStorage& fs ) const;
375     protected:
376         ...
377     };
378
379
380 DynamicAdaptedFeatureDetector
381 -----------------------------
382 .. ocv:class:: DynamicAdaptedFeatureDetector : public FeatureDetector
383
384 Adaptively adjusting detector that iteratively detects features until the desired number is found. ::
385
386        class DynamicAdaptedFeatureDetector: public FeatureDetector
387        {
388        public:
389            DynamicAdaptedFeatureDetector( const Ptr<AdjusterAdapter>& adjuster,
390                int min_features=400, int max_features=500, int max_iters=5 );
391            ...
392        };
393
394 If the detector is persisted, it "remembers" the parameters
395 used for the last detection. In this case, the detector may be used for consistent numbers
396 of keypoints in a set of temporally related images, such as video streams or
397 panorama series.
398
399 ``DynamicAdaptedFeatureDetector``  uses another detector, such as FAST or SURF, to do the dirty work,
400 with the help of ``AdjusterAdapter`` .
401 If the detected number of features is not large enough,
402 ``AdjusterAdapter`` adjusts the detection parameters so that the next detection
403 results in a bigger or smaller number of features.  This is repeated until either the number of desired features are found
404 or the parameters are maxed out.
405
406 Adapters can be easily implemented for any detector via the
407 ``AdjusterAdapter`` interface.
408
409 Beware that this is not thread-safe since the adjustment of parameters requires modification of the feature detector class instance.
410
411 Example of creating ``DynamicAdaptedFeatureDetector`` : ::
412
413     //sample usage:
414     //will create a detector that attempts to find
415     //100 - 110 FAST Keypoints, and will at most run
416     //FAST feature detection 10 times until that
417     //number of keypoints are found
418     Ptr<FeatureDetector> detector(new DynamicAdaptedFeatureDetector (100, 110, 10,
419                                   new FastAdjuster(20,true)));
420
421
422 DynamicAdaptedFeatureDetector::DynamicAdaptedFeatureDetector
423 ------------------------------------------------------------
424 The constructor
425
426 .. ocv:function:: DynamicAdaptedFeatureDetector::DynamicAdaptedFeatureDetector( const Ptr<AdjusterAdapter>& adjuster, int min_features=400, int max_features=500, int max_iters=5 )
427
428     :param adjuster:  :ocv:class:`AdjusterAdapter`  that detects features and adjusts parameters.
429
430     :param min_features: Minimum desired number of features.
431
432     :param max_features: Maximum desired number of features.
433
434     :param max_iters: Maximum number of times to try adjusting the feature detector parameters. For :ocv:class:`FastAdjuster` , this number can be high, but with ``Star`` or ``Surf``  many iterations can be time-consuming.  At each iteration the detector is rerun.
435
436 AdjusterAdapter
437 ---------------
438 .. ocv:class:: AdjusterAdapter : public FeatureDetector
439
440 Class providing an interface for adjusting parameters of a feature detector. This interface is used by :ocv:class:`DynamicAdaptedFeatureDetector` . It is a wrapper for :ocv:class:`FeatureDetector` that enables adjusting parameters after feature detection. ::
441
442      class AdjusterAdapter: public FeatureDetector
443      {
444      public:
445         virtual ~AdjusterAdapter() {}
446         virtual void tooFew(int min, int n_detected) = 0;
447         virtual void tooMany(int max, int n_detected) = 0;
448         virtual bool good() const = 0;
449         virtual Ptr<AdjusterAdapter> clone() const = 0;
450         static Ptr<AdjusterAdapter> create( const string& detectorType );
451      };
452
453
454 See
455 :ocv:class:`FastAdjuster`,
456 :ocv:class:`StarAdjuster`, and
457 :ocv:class:`SurfAdjuster` for concrete implementations.
458
459 AdjusterAdapter::tooFew
460 ---------------------------
461 Adjusts the detector parameters to detect more features.
462
463 .. ocv:function:: void AdjusterAdapter::tooFew(int min, int n_detected)
464
465     :param min: Minimum desired number of features.
466
467     :param n_detected: Number of features detected during the latest run.
468
469 Example: ::
470
471     void FastAdjuster::tooFew(int min, int n_detected)
472     {
473             thresh_--;
474     }
475
476 AdjusterAdapter::tooMany
477 ----------------------------
478 Adjusts the detector parameters to detect less features.
479
480 .. ocv:function:: void AdjusterAdapter::tooMany(int max, int n_detected)
481
482     :param max: Maximum desired number of features.
483
484     :param n_detected: Number of features detected during the latest run.
485
486 Example: ::
487
488     void FastAdjuster::tooMany(int min, int n_detected)
489     {
490             thresh_++;
491     }
492
493
494 AdjusterAdapter::good
495 ---------------------
496 Returns false if the detector parameters cannot be adjusted any more.
497
498 .. ocv:function:: bool AdjusterAdapter::good() const
499
500 Example: ::
501
502         bool FastAdjuster::good() const
503         {
504                 return (thresh_ > 1) && (thresh_ < 200);
505         }
506
507 AdjusterAdapter::create
508 -----------------------
509 Creates an adjuster adapter by name
510
511 .. ocv:function:: Ptr<AdjusterAdapter> AdjusterAdapter::create( const string& detectorType )
512
513     Creates an adjuster adapter by name ``detectorType``. The detector name is the same as in :ocv:func:`FeatureDetector::create`, but now supports ``"FAST"``, ``"STAR"``, and ``"SURF"`` only.
514
515 FastAdjuster
516 ------------
517 .. ocv:class:: FastAdjuster : public AdjusterAdapter
518
519 :ocv:class:`AdjusterAdapter` for :ocv:class:`FastFeatureDetector`. This class decreases or increases the threshold value by 1. ::
520
521         class FastAdjuster FastAdjuster: public AdjusterAdapter
522         {
523         public:
524                 FastAdjuster(int init_thresh = 20, bool nonmax = true);
525                 ...
526         };
527
528 StarAdjuster
529 ------------
530 .. ocv:class:: StarAdjuster : public AdjusterAdapter
531
532 :ocv:class:`AdjusterAdapter` for :ocv:class:`StarFeatureDetector`. This class adjusts the ``responseThreshhold`` of ``StarFeatureDetector``.  ::
533
534         class StarAdjuster: public AdjusterAdapter
535         {
536                 StarAdjuster(double initial_thresh = 30.0);
537                 ...
538         };
539
540 SurfAdjuster
541 ------------
542 .. ocv:class:: SurfAdjuster : public AdjusterAdapter
543
544 :ocv:class:`AdjusterAdapter` for ``SurfFeatureDetector``.  ::
545
546     class CV_EXPORTS SurfAdjuster: public AdjusterAdapter
547     {
548     public:
549         SurfAdjuster( double initial_thresh=400.f, double min_thresh=2, double max_thresh=1000 );
550
551         virtual void tooFew(int minv, int n_detected);
552         virtual void tooMany(int maxv, int n_detected);
553         virtual bool good() const;
554
555         virtual Ptr<AdjusterAdapter> clone() const;
556
557         ...
558     };