Coverage Report

Created: 2026-08-14 06:54

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/work/install-coverage/include/opencv4/opencv2/imgproc.hpp
Line
Count
Source
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_IMGPROC_HPP
44
#define OPENCV_IMGPROC_HPP
45
46
#include "opencv2/core.hpp"
47
48
/**
49
@defgroup imgproc Image Processing
50
51
This module offers a comprehensive suite of image processing functions, enabling tasks such as those listed above.
52
53
@{
54
    @defgroup imgproc_filter Image Filtering
55
56
    Functions and classes described in this section are used to perform various linear or non-linear
57
    filtering operations on 2D images (represented as Mat's). It means that for each pixel location
58
    \f$(x,y)\f$ in the source image (normally, rectangular), its neighborhood is considered and used to
59
    compute the response. In case of a linear filter, it is a weighted sum of pixel values. In case of
60
    morphological operations, it is the minimum or maximum values, and so on. The computed response is
61
    stored in the destination image at the same location \f$(x,y)\f$. It means that the output image
62
    will be of the same size as the input image. Normally, the functions support multi-channel arrays,
63
    in which case every channel is processed independently. Therefore, the output image will also have
64
    the same number of channels as the input one.
65
66
    Another common feature of the functions and classes described in this section is that, unlike
67
    simple arithmetic functions, they need to extrapolate values of some non-existing pixels. For
68
    example, if you want to smooth an image using a Gaussian \f$3 \times 3\f$ filter, then, when
69
    processing the left-most pixels in each row, you need pixels to the left of them, that is, outside
70
    of the image. You can let these pixels be the same as the left-most image pixels ("replicated
71
    border" extrapolation method), or assume that all the non-existing pixels are zeros ("constant
72
    border" extrapolation method), and so on. OpenCV enables you to specify the extrapolation method.
73
    For details, see #BorderTypes
74
75
    @anchor filter_depths
76
    ### Depth combinations
77
    Input depth (src.depth()) | Output depth (ddepth)
78
    --------------------------|----------------------
79
    CV_8U                     | -1/CV_16S/CV_32F/CV_64F
80
    CV_16U/CV_16S             | -1/CV_32F/CV_64F
81
    CV_32F                    | -1/CV_32F
82
    CV_64F                    | -1/CV_64F
83
84
    @note when ddepth=-1, the output image will have the same depth as the source.
85
86
    @note if you need double floating-point accuracy and using single floating-point input data
87
    (CV_32F input and CV_64F output depth combination), you can use @ref Mat.convertTo to convert
88
    the input data to the desired precision.
89
90
    @defgroup imgproc_transform Geometric Image Transformations
91
92
    The functions in this section perform various geometrical transformations of 2D images. They do not
93
    change the image content but deform the pixel grid and map this deformed grid to the destination
94
    image. In fact, to avoid sampling artifacts, the mapping is done in the reverse order, from
95
    destination to the source. That is, for each pixel \f$(x, y)\f$ of the destination image, the
96
    functions compute coordinates of the corresponding "donor" pixel in the source image and copy the
97
    pixel value:
98
99
    \f[\texttt{dst} (x,y)= \texttt{src} (f_x(x,y), f_y(x,y))\f]
100
101
    In case when you specify the forward mapping \f$\left<g_x, g_y\right>: \texttt{src} \rightarrow
102
    \texttt{dst}\f$, the OpenCV functions first compute the corresponding inverse mapping
103
    \f$\left<f_x, f_y\right>: \texttt{dst} \rightarrow \texttt{src}\f$ and then use the above formula.
104
105
    The actual implementations of the geometrical transformations, from the most generic remap and to
106
    the simplest and the fastest resize, need to solve two main problems with the above formula:
107
108
    - Extrapolation of non-existing pixels. Similarly to the filtering functions described in the
109
    previous section, for some \f$(x,y)\f$, either one of \f$f_x(x,y)\f$, or \f$f_y(x,y)\f$, or both
110
    of them may fall outside of the image. In this case, an extrapolation method needs to be used.
111
    OpenCV provides the same selection of extrapolation methods as in the filtering functions. In
112
    addition, it provides the method #BORDER_TRANSPARENT. This means that the corresponding pixels in
113
    the destination image will not be modified at all.
114
115
    - Interpolation of pixel values. Usually \f$f_x(x,y)\f$ and \f$f_y(x,y)\f$ are floating-point
116
    numbers. This means that \f$\left<f_x, f_y\right>\f$ can be either an affine or perspective
117
    transformation, or radial lens distortion correction, and so on. So, a pixel value at fractional
118
    coordinates needs to be retrieved. In the simplest case, the coordinates can be just rounded to the
119
    nearest integer coordinates and the corresponding pixel can be used. This is called a
120
    nearest-neighbor interpolation. However, a better result can be achieved by using more
121
    sophisticated [interpolation methods](https://en.wikipedia.org/wiki/Multivariate_interpolation) ,
122
    where a polynomial function is fit into some neighborhood of the computed pixel \f$(f_x(x,y),
123
    f_y(x,y))\f$, and then the value of the polynomial at \f$(f_x(x,y), f_y(x,y))\f$ is taken as the
124
    interpolated pixel value. In OpenCV, you can choose between several interpolation methods. See
125
    #resize for details.
126
127
    @note The geometrical transformations do not work with `CV_8S` or `CV_32S` images.
128
129
    @defgroup imgproc_misc Miscellaneous Image Transformations
130
    @defgroup imgproc_draw Drawing Functions
131
132
    Drawing functions work with matrices/images of arbitrary depth. The boundaries of the shapes can be
133
    rendered with antialiasing (implemented only for 8-bit images for now). All the functions include
134
    the parameter color that uses an RGB value (that may be constructed with the Scalar constructor )
135
    for color images and brightness for grayscale images. For color images, the channel ordering is
136
    normally *Blue, Green, Red*. This is what imshow, imread, and imwrite expect. So, if you form a
137
    color using the Scalar constructor, it should look like:
138
139
    \f[\texttt{Scalar} (blue \_ component, green \_ component, red \_ component[, alpha \_ component])\f]
140
141
    If you are using your own image rendering and I/O functions, you can use any channel ordering. The
142
    drawing functions process each channel independently and do not depend on the channel order or even
143
    on the used color space. The whole image can be converted from BGR to RGB or to a different color
144
    space using cvtColor .
145
146
    If a drawn figure is partially or completely outside the image, the drawing functions clip it. Also,
147
    many drawing functions can handle pixel coordinates specified with sub-pixel accuracy. This means
148
    that the coordinates can be passed as fixed-point numbers encoded as integers. The number of
149
    fractional bits is specified by the shift parameter and the real point coordinates are calculated as
150
    \f$\texttt{Point}(x,y)\rightarrow\texttt{Point2f}(x*2^{-shift},y*2^{-shift})\f$ . This feature is
151
    especially effective when rendering antialiased shapes.
152
153
    @note The functions do not support alpha-transparency when the target image is 4-channel. In this
154
    case, the color[3] is simply copied to the repainted pixels. Thus, if you want to paint
155
    semi-transparent shapes, you can paint them in a separate buffer and then blend it with the main
156
    image.
157
158
    @defgroup imgproc_color_conversions Color Space Conversions
159
    @defgroup imgproc_colormap ColorMaps in OpenCV
160
161
    The human perception isn't built for observing fine changes in grayscale images. Human eyes are more
162
    sensitive to observing changes between colors, so you often need to recolor your grayscale images to
163
    get a clue about them. OpenCV now comes with various colormaps to enhance the visualization in your
164
    computer vision application.
165
166
    In OpenCV you only need applyColorMap to apply a colormap on a given image. The following sample
167
    code reads the path to an image from command line, applies a Jet colormap on it and shows the
168
    result:
169
170
    @include snippets/imgproc_applyColorMap.cpp
171
172
    @see #ColormapTypes
173
174
    @defgroup imgproc_subdiv2d Planar Subdivision
175
176
    The Subdiv2D class described in this section is used to perform various planar subdivision on
177
    a set of 2D points (represented as vector of Point2f). OpenCV subdivides a plane into triangles
178
    using the Delaunay's algorithm, which corresponds to the dual graph of the Voronoi diagram.
179
    In the figure below, the Delaunay's triangulation is marked with black lines and the Voronoi
180
    diagram with red lines.
181
182
    ![Delaunay triangulation (black) and Voronoi (red)](pics/delaunay_voronoi.png)
183
184
    The subdivisions can be used for the 3D piece-wise transformation of a plane, morphing, fast
185
    location of points on the plane, building special graphs (such as NNG,RNG), and so forth.
186
187
    @defgroup imgproc_hist Histograms
188
    @defgroup imgproc_shape Structural Analysis and Shape Descriptors
189
    @defgroup imgproc_motion Motion Analysis and Object Tracking
190
    @defgroup imgproc_feature Feature Detection
191
    @defgroup imgproc_object Object Detection
192
    @defgroup imgproc_segmentation Image Segmentation
193
    @defgroup imgproc_hal Hardware Acceleration Layer
194
    @{
195
        @defgroup imgproc_hal_functions Functions
196
        @defgroup imgproc_hal_interface Interface
197
    @}
198
  @}
199
*/
200
201
namespace cv
202
{
203
204
/** @addtogroup imgproc
205
@{
206
*/
207
208
//! @addtogroup imgproc_filter
209
//! @{
210
211
enum SpecialFilter {
212
    FILTER_SCHARR = -1
213
};
214
215
//! type of morphological operation
216
enum MorphTypes{
217
    MORPH_ERODE    = 0, //!< see #erode
218
    MORPH_DILATE   = 1, //!< see #dilate
219
    MORPH_OPEN     = 2, //!< an opening operation
220
                        //!< \f[\texttt{dst} = \mathrm{open} ( \texttt{src} , \texttt{kernel} )= \mathrm{dilate} ( \mathrm{erode} ( \texttt{src} , \texttt{kernel} ))\f]
221
    MORPH_CLOSE    = 3, //!< a closing operation
222
                        //!< \f[\texttt{dst} = \mathrm{close} ( \texttt{src} , \texttt{kernel} )= \mathrm{erode} ( \mathrm{dilate} ( \texttt{src} , \texttt{kernel} ))\f]
223
    MORPH_GRADIENT = 4, //!< a morphological gradient
224
                        //!< \f[\texttt{dst} = \mathrm{morph\_grad} ( \texttt{src} , \texttt{kernel} )= \mathrm{dilate} ( \texttt{src} , \texttt{kernel} )- \mathrm{erode} ( \texttt{src} , \texttt{kernel} )\f]
225
    MORPH_TOPHAT   = 5, //!< "top hat"
226
                        //!< \f[\texttt{dst} = \mathrm{tophat} ( \texttt{src} , \texttt{kernel} )= \texttt{src} - \mathrm{open} ( \texttt{src} , \texttt{kernel} )\f]
227
    MORPH_BLACKHAT = 6, //!< "black hat"
228
                        //!< \f[\texttt{dst} = \mathrm{blackhat} ( \texttt{src} , \texttt{kernel} )= \mathrm{close} ( \texttt{src} , \texttt{kernel} )- \texttt{src}\f]
229
    MORPH_HITMISS  = 7  //!< "hit or miss"
230
                        //!<   .- Only supported for CV_8UC1 binary images. A tutorial can be found in the documentation
231
};
232
233
//! shape of the structuring element
234
enum MorphShapes {
235
    MORPH_RECT    = 0, //!< a rectangular structuring element:  \f[E_{ij}=1\f]
236
    MORPH_CROSS   = 1, //!< a cross-shaped structuring element:
237
                       //!< \f[E_{ij} = \begin{cases} 1 & \texttt{if } {i=\texttt{anchor.y } {or } {j=\texttt{anchor.x}}} \\0 & \texttt{otherwise} \end{cases}\f]
238
    MORPH_ELLIPSE = 2, //!< an elliptic structuring element, that is, a filled ellipse inscribed
239
                      //!< into the rectangle Rect(0, 0, esize.width, esize.height)
240
    MORPH_DIAMOND = 3  //!< a diamond structuring element defined by Manhattan distance
241
};
242
243
//! @} imgproc_filter
244
245
//! @addtogroup imgproc_transform
246
//! @{
247
248
//! interpolation algorithm
249
enum InterpolationFlags{
250
    /** nearest neighbor interpolation */
251
    INTER_NEAREST        = 0,
252
    /** bilinear interpolation */
253
    INTER_LINEAR         = 1,
254
    /** bicubic interpolation */
255
    INTER_CUBIC          = 2,
256
    /** resampling using pixel area relation. It may be a preferred method for image decimation, as
257
    it gives moire'-free results. But when the image is zoomed, it is similar to the INTER_NEAREST
258
    method. */
259
    INTER_AREA           = 3,
260
    /** Lanczos interpolation over 8x8 neighborhood */
261
    INTER_LANCZOS4       = 4,
262
    /** Bit exact bilinear interpolation */
263
    INTER_LINEAR_EXACT = 5,
264
    /** Bit exact nearest neighbor interpolation. This will produce same results as
265
    the nearest neighbor method in PIL, scikit-image or Matlab. */
266
    INTER_NEAREST_EXACT  = 6,
267
    /** mask for interpolation codes */
268
    INTER_MAX            = 7,
269
    /** flag, fills all of the destination image pixels. If some of them correspond to outliers in the
270
    source image, they are set to zero */
271
    WARP_FILL_OUTLIERS   = 8,
272
    /** flag, inverse transformation
273
274
    For example, #linearPolar or #logPolar transforms:
275
    - flag is __not__ set: \f$dst( \rho , \phi ) = src(x,y)\f$
276
    - flag is set: \f$dst(x,y) = src( \rho , \phi )\f$
277
    */
278
    WARP_INVERSE_MAP     = 16,
279
    WARP_RELATIVE_MAP    = 32
280
};
281
282
/** \brief Specify the polar mapping mode
283
@sa warpPolar
284
*/
285
enum WarpPolarMode
286
{
287
    WARP_POLAR_LINEAR = 0, ///< Remaps an image to/from polar space.
288
    WARP_POLAR_LOG = 256   ///< Remaps an image to/from semilog-polar space.
289
};
290
291
enum InterpolationMasks {
292
       INTER_BITS      = 5,
293
       INTER_BITS2     = INTER_BITS * 2,
294
       INTER_TAB_SIZE  = 1 << INTER_BITS,
295
       INTER_TAB_SIZE2 = INTER_TAB_SIZE * INTER_TAB_SIZE
296
     };
297
298
//! @} imgproc_transform
299
300
//! @addtogroup imgproc_misc
301
//! @{
302
303
//! Distance types for Distance Transform and M-estimators
304
//! @see distanceTransform, fitLine
305
enum DistanceTypes {
306
    DIST_USER    = -1,  //!< User defined distance
307
    DIST_L1      = 1,   //!< distance = |x1-x2| + |y1-y2|
308
    DIST_L2      = 2,   //!< the simple euclidean distance
309
    DIST_C       = 3,   //!< distance = max(|x1-x2|,|y1-y2|)
310
    DIST_L12     = 4,   //!< L1-L2 metric: distance = 2(sqrt(1+x*x/2) - 1))
311
    DIST_FAIR    = 5,   //!< distance = c^2(|x|/c-log(1+|x|/c)), c = 1.3998
312
    DIST_WELSCH  = 6,   //!< distance = c^2/2(1-exp(-(x/c)^2)), c = 2.9846
313
    DIST_HUBER   = 7    //!< distance = |x|<c ? x^2/2 : c(|x|-c/2), c=1.345
314
};
315
316
//! Mask size for distance transform
317
enum DistanceTransformMasks {
318
    DIST_MASK_3       = 3, //!< mask=3
319
    DIST_MASK_5       = 5, //!< mask=5
320
    DIST_MASK_PRECISE = 0  //!<
321
};
322
323
//! type of the threshold operation
324
//! ![threshold types](pics/threshold.png)
325
enum ThresholdTypes {
326
    THRESH_BINARY     = 0, //!< \f[\texttt{dst} (x,y) =  \fork{\texttt{maxval}}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{0}{otherwise}\f]
327
    THRESH_BINARY_INV = 1, //!< \f[\texttt{dst} (x,y) =  \fork{0}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{\texttt{maxval}}{otherwise}\f]
328
    THRESH_TRUNC      = 2, //!< \f[\texttt{dst} (x,y) =  \fork{\texttt{threshold}}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{\texttt{src}(x,y)}{otherwise}\f]
329
    THRESH_TOZERO     = 3, //!< \f[\texttt{dst} (x,y) =  \fork{\texttt{src}(x,y)}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{0}{otherwise}\f]
330
    THRESH_TOZERO_INV = 4, //!< \f[\texttt{dst} (x,y) =  \fork{0}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{\texttt{src}(x,y)}{otherwise}\f]
331
    THRESH_MASK       = 7,
332
    THRESH_OTSU       = 8, //!< flag, use Otsu algorithm to choose the optimal threshold value
333
    THRESH_TRIANGLE   = 16, //!< flag, use Triangle algorithm to choose the optimal threshold value
334
    THRESH_DRYRUN     = 128 //!< flag, compute threshold only (useful for OTSU/TRIANGLE) but does not actually run thresholding
335
};
336
337
//! adaptive threshold algorithm
338
//! @see adaptiveThreshold
339
enum AdaptiveThresholdTypes {
340
    /** the threshold value \f$T(x,y)\f$ is a mean of the \f$\texttt{blockSize} \times
341
    \texttt{blockSize}\f$ neighborhood of \f$(x, y)\f$ minus C */
342
    ADAPTIVE_THRESH_MEAN_C     = 0,
343
    /** the threshold value \f$T(x, y)\f$ is a weighted sum (cross-correlation with a Gaussian
344
    window) of the \f$\texttt{blockSize} \times \texttt{blockSize}\f$ neighborhood of \f$(x, y)\f$
345
    minus C . The default sigma (standard deviation) is used for the specified blockSize . See
346
    #getGaussianKernel*/
347
    ADAPTIVE_THRESH_GAUSSIAN_C = 1
348
};
349
350
//! class of the pixel in GrabCut algorithm
351
enum GrabCutClasses {
352
    GC_BGD    = 0,  //!< an obvious background pixels
353
    GC_FGD    = 1,  //!< an obvious foreground (object) pixel
354
    GC_PR_BGD = 2,  //!< a possible background pixel
355
    GC_PR_FGD = 3   //!< a possible foreground pixel
356
};
357
358
//! GrabCut algorithm flags
359
enum GrabCutModes {
360
    /** The function initializes the state and the mask using the provided rectangle. After that it
361
    runs iterCount iterations of the algorithm. */
362
    GC_INIT_WITH_RECT  = 0,
363
    /** The function initializes the state using the provided mask. Note that GC_INIT_WITH_RECT
364
    and GC_INIT_WITH_MASK can be combined. Then, all the pixels outside of the ROI are
365
    automatically initialized with GC_BGD .*/
366
    GC_INIT_WITH_MASK  = 1,
367
    /** The value means that the algorithm should just resume. */
368
    GC_EVAL            = 2,
369
    /** The value means that the algorithm should just run the grabCut algorithm (a single iteration) with the fixed model */
370
    GC_EVAL_FREEZE_MODEL = 3
371
};
372
373
//! distanceTransform algorithm flags
374
enum DistanceTransformLabelTypes {
375
    /** each connected component of zeros in src (as well as all the non-zero pixels closest to the
376
    connected component) will be assigned the same label */
377
    DIST_LABEL_CCOMP = 0,
378
    /** each zero pixel (and all the non-zero pixels closest to it) gets its own label. */
379
    DIST_LABEL_PIXEL = 1
380
};
381
382
//! floodfill algorithm flags
383
enum FloodFillFlags {
384
    /** If set, the difference between the current pixel and seed pixel is considered. Otherwise,
385
    the difference between neighbor pixels is considered (that is, the range is floating). */
386
    FLOODFILL_FIXED_RANGE = 1 << 16,
387
    /** If set, the function does not change the image ( newVal is ignored), and only fills the
388
    mask with the value specified in bits 8-16 of flags as described above. This option only make
389
    sense in function variants that have the mask parameter. */
390
    FLOODFILL_MASK_ONLY   = 1 << 17
391
};
392
393
//! @} imgproc_misc
394
395
//! @addtogroup imgproc_shape
396
//! @{
397
398
//! connected components statistics
399
enum ConnectedComponentsTypes {
400
    CC_STAT_LEFT   = 0, //!< The leftmost (x) coordinate which is the inclusive start of the bounding
401
                        //!< box in the horizontal direction.
402
    CC_STAT_TOP    = 1, //!< The topmost (y) coordinate which is the inclusive start of the bounding
403
                        //!< box in the vertical direction.
404
    CC_STAT_WIDTH  = 2, //!< The horizontal size of the bounding box
405
    CC_STAT_HEIGHT = 3, //!< The vertical size of the bounding box
406
    CC_STAT_AREA   = 4, //!< The total area (in pixels) of the connected component
407
#ifndef CV_DOXYGEN
408
    CC_STAT_MAX    = 5 //!< Max enumeration value. Used internally only for memory allocation
409
#endif
410
};
411
412
//! connected components algorithm
413
enum ConnectedComponentsAlgorithmsTypes {
414
    CCL_DEFAULT   = -1, //!< Spaghetti @cite Bolelli2019 algorithm for 8-way connectivity, Spaghetti4C @cite Bolelli2021 algorithm for 4-way connectivity.
415
    CCL_WU        = 0,  //!< SAUF @cite Wu2009 algorithm for 8-way connectivity, SAUF algorithm for 4-way connectivity. The parallel implementation described in @cite Bolelli2017 is available for SAUF.
416
    CCL_GRANA     = 1,  //!< BBDT @cite Grana2010 algorithm for 8-way connectivity, SAUF algorithm for 4-way connectivity. The parallel implementation described in @cite Bolelli2017 is available for both BBDT and SAUF.
417
    CCL_BOLELLI   = 2,  //!< Spaghetti @cite Bolelli2019 algorithm for 8-way connectivity, Spaghetti4C @cite Bolelli2021 algorithm for 4-way connectivity. The parallel implementation described in @cite Bolelli2017 is available for both Spaghetti and Spaghetti4C.
418
    CCL_SAUF      = 3,  //!< Same as CCL_WU. It is preferable to use the flag with the name of the algorithm (CCL_SAUF) rather than the one with the name of the first author (CCL_WU).
419
    CCL_BBDT      = 4,  //!< Same as CCL_GRANA. It is preferable to use the flag with the name of the algorithm (CCL_BBDT) rather than the one with the name of the first author (CCL_GRANA).
420
    CCL_SPAGHETTI = 5,  //!< Same as CCL_BOLELLI. It is preferable to use the flag with the name of the algorithm (CCL_SPAGHETTI) rather than the one with the name of the first author (CCL_BOLELLI).
421
};
422
423
//! mode of the contour retrieval algorithm
424
enum RetrievalModes {
425
    /** retrieves only the extreme outer contours. It sets `hierarchy[i][2]=hierarchy[i][3]=-1` for
426
    all the contours. */
427
    RETR_EXTERNAL  = 0,
428
    /** retrieves all of the contours without establishing any hierarchical relationships. */
429
    RETR_LIST      = 1,
430
    /** retrieves all of the contours and organizes them into a two-level hierarchy. At the top
431
    level, there are external boundaries of the components. At the second level, there are
432
    boundaries of the holes. If there is another contour inside a hole of a connected component, it
433
    is still put at the top level. */
434
    RETR_CCOMP     = 2,
435
    /** retrieves all of the contours and reconstructs a full hierarchy of nested contours.*/
436
    RETR_TREE      = 3,
437
    RETR_FLOODFILL = 4 //!<
438
};
439
440
//! the contour approximation algorithm
441
enum ContourApproximationModes {
442
    /** stores absolutely all the contour points. That is, any 2 subsequent points (x1,y1) and
443
    (x2,y2) of the contour will be either horizontal, vertical or diagonal neighbors, that is,
444
    max(abs(x1-x2),abs(y2-y1))==1. */
445
    CHAIN_APPROX_NONE      = 1,
446
    /** compresses horizontal, vertical, and diagonal segments and leaves only their end points.
447
    For example, an up-right rectangular contour is encoded with 4 points. */
448
    CHAIN_APPROX_SIMPLE    = 2,
449
    /** applies one of the flavors of the Teh-Chin chain approximation algorithm @cite TehChin89 */
450
    CHAIN_APPROX_TC89_L1   = 3,
451
    /** applies one of the flavors of the Teh-Chin chain approximation algorithm @cite TehChin89 */
452
    CHAIN_APPROX_TC89_KCOS = 4
453
};
454
455
/** @brief Shape matching methods
456
457
\f$A\f$ denotes object1,\f$B\f$ denotes object2
458
459
\f$\begin{array}{l} m^A_i =  \mathrm{sign} (h^A_i)  \cdot \log{h^A_i} \\ m^B_i =  \mathrm{sign} (h^B_i)  \cdot \log{h^B_i} \end{array}\f$
460
461
and \f$h^A_i, h^B_i\f$ are the Hu moments of \f$A\f$ and \f$B\f$ , respectively.
462
*/
463
enum ShapeMatchModes {
464
    CONTOURS_MATCH_I1  =1, //!< \f[I_1(A,B) =  \sum _{i=1...7}  \left |  \frac{1}{m^A_i} -  \frac{1}{m^B_i} \right |\f]
465
    CONTOURS_MATCH_I2  =2, //!< \f[I_2(A,B) =  \sum _{i=1...7}  \left | m^A_i - m^B_i  \right |\f]
466
    CONTOURS_MATCH_I3  =3  //!< \f[I_3(A,B) =  \max _{i=1...7}  \frac{ \left| m^A_i - m^B_i \right| }{ \left| m^A_i \right| }\f]
467
};
468
469
//! @} imgproc_shape
470
471
//! @addtogroup imgproc_feature
472
//! @{
473
474
//! Variants of a Hough transform
475
enum HoughModes {
476
477
    /** classical or standard Hough transform. Every line is represented by two floating-point
478
    numbers \f$(\rho, \theta)\f$ , where \f$\rho\f$ is a distance between (0,0) point and the line,
479
    and \f$\theta\f$ is the angle between x-axis and the normal to the line. Thus, the matrix must
480
    be (the created sequence will be) of CV_32FC2 type */
481
    HOUGH_STANDARD      = 0,
482
    /** probabilistic Hough transform (more efficient in case if the picture contains a few long
483
    linear segments). It returns line segments rather than the whole line. Each segment is
484
    represented by starting and ending points, and the matrix must be (the created sequence will
485
    be) of the CV_32SC4 type. */
486
    HOUGH_PROBABILISTIC = 1,
487
    /** multi-scale variant of the classical Hough transform. The lines are encoded the same way as
488
    HOUGH_STANDARD. */
489
    HOUGH_MULTI_SCALE   = 2,
490
    HOUGH_GRADIENT      = 3, //!< basically *21HT*, described in @cite Yuen90
491
    HOUGH_GRADIENT_ALT  = 4, //!< variation of HOUGH_GRADIENT to get better accuracy
492
};
493
494
//! Variants of Line Segment %Detector
495
enum LineSegmentDetectorModes {
496
    LSD_REFINE_NONE = 0, //!< No refinement applied
497
    LSD_REFINE_STD  = 1, //!< Standard refinement is applied. E.g. breaking arches into smaller straighter line approximations.
498
    LSD_REFINE_ADV  = 2  //!< Advanced refinement. Number of false alarms is calculated, lines are
499
                         //!< refined through increase of precision, decrement in size, etc.
500
};
501
502
//! @} imgproc_feature
503
504
/** Histogram comparison methods
505
  @ingroup imgproc_hist
506
*/
507
enum HistCompMethods {
508
    /** Correlation
509
    \f[d(H_1,H_2) =  \frac{\sum_I (H_1(I) - \bar{H_1}) (H_2(I) - \bar{H_2})}{\sqrt{\sum_I(H_1(I) - \bar{H_1})^2 \sum_I(H_2(I) - \bar{H_2})^2}}\f]
510
    where
511
    \f[\bar{H_k} =  \frac{1}{N} \sum _J H_k(J)\f]
512
    and \f$N\f$ is a total number of histogram bins. */
513
    HISTCMP_CORREL        = 0,
514
    /** Chi-Square
515
    \f[d(H_1,H_2) =  \sum _I  \frac{\left(H_1(I)-H_2(I)\right)^2}{H_1(I)}\f] */
516
    HISTCMP_CHISQR        = 1,
517
    /** Intersection
518
    \f[d(H_1,H_2) =  \sum _I  \min (H_1(I), H_2(I))\f] */
519
    HISTCMP_INTERSECT     = 2,
520
    /** Bhattacharyya distance
521
    (In fact, OpenCV computes Hellinger distance, which is related to Bhattacharyya coefficient.)
522
    \f[d(H_1,H_2) =  \sqrt{1 - \frac{1}{\sqrt{\bar{H_1} \bar{H_2} N^2}} \sum_I \sqrt{H_1(I) \cdot H_2(I)}}\f] */
523
    HISTCMP_BHATTACHARYYA = 3,
524
    HISTCMP_HELLINGER     = HISTCMP_BHATTACHARYYA, //!< Synonym for HISTCMP_BHATTACHARYYA
525
    /** Alternative Chi-Square
526
    \f[d(H_1,H_2) =  2 * \sum _I  \frac{\left(H_1(I)-H_2(I)\right)^2}{H_1(I)+H_2(I)}\f]
527
    This alternative formula is regularly used for texture comparison. See e.g. @cite Puzicha1997 */
528
    HISTCMP_CHISQR_ALT    = 4,
529
    /** Kullback-Leibler divergence
530
    \f[d(H_1,H_2) = \sum _I H_1(I) \log \left(\frac{H_1(I)}{H_2(I)}\right)\f] */
531
    HISTCMP_KL_DIV        = 5
532
};
533
534
/** the color conversion codes
535
@see @ref imgproc_color_conversions
536
@note The source image (src) must be of an appropriate type for the desired color conversion.
537
- `[8U]` means to support `CV_8U` src type.
538
- `[16U]` means to support `CV_16U` src type.
539
- `[32F]` means to support `CV_32F` src type.
540
@ingroup imgproc_color_conversions
541
 */
542
enum ColorConversionCodes {
543
    COLOR_BGR2BGRA     = 0, //!< [8U/16U/32F] add alpha channel to RGB or BGR image
544
    COLOR_RGB2RGBA     = COLOR_BGR2BGRA, //!< [8U/16U/32F]
545
546
    COLOR_BGRA2BGR     = 1, //!< [8U/16U/32F] remove alpha channel from RGB or BGR image
547
    COLOR_RGBA2RGB     = COLOR_BGRA2BGR, //!< [8U/16U/32F]
548
549
    COLOR_BGR2RGBA     = 2, //!< [8U/16U/32F] convert between RGB and BGR color spaces (with or without alpha channel)
550
    COLOR_RGB2BGRA     = COLOR_BGR2RGBA, //!< [8U/16U/32F]
551
552
    COLOR_RGBA2BGR     = 3, //!< [8U/16U/32F]
553
    COLOR_BGRA2RGB     = COLOR_RGBA2BGR, //!< [8U/16U/32F]
554
555
    COLOR_BGR2RGB      = 4, //!< [8U/16U/32F]
556
    COLOR_RGB2BGR      = COLOR_BGR2RGB, //!< [8U/16U/32F]
557
558
    COLOR_BGRA2RGBA    = 5, //!< [8U/16U/32F]
559
    COLOR_RGBA2BGRA    = COLOR_BGRA2RGBA, //!< [8U/16U/32F]
560
561
    COLOR_BGR2GRAY     = 6, //!< [8U/16U/32F] convert between RGB/BGR and grayscale, @ref color_convert_rgb_gray "color conversions"
562
    COLOR_RGB2GRAY     = 7, //!< [8U/16U/32F]
563
    COLOR_GRAY2BGR     = 8, //!< [8U/16U/32F]
564
    COLOR_GRAY2RGB     = COLOR_GRAY2BGR, //!< [8U/16U/32F]
565
    COLOR_GRAY2BGRA    = 9, //!< [8U/16U/32F]
566
    COLOR_GRAY2RGBA    = COLOR_GRAY2BGRA, //!< [8U/16U/32F]
567
    COLOR_BGRA2GRAY    = 10, //!< [8U/16U/32F]
568
    COLOR_RGBA2GRAY    = 11, //!< [8U/16U/32F]
569
570
    COLOR_BGR2BGR565   = 12, //!< [8U] convert between RGB/BGR and BGR565 (16-bit images)
571
    COLOR_RGB2BGR565   = 13, //!< [8U]
572
    COLOR_BGR5652BGR   = 14, //!< [8U]
573
    COLOR_BGR5652RGB   = 15, //!< [8U]
574
    COLOR_BGRA2BGR565  = 16, //!< [8U]
575
    COLOR_RGBA2BGR565  = 17, //!< [8U]
576
    COLOR_BGR5652BGRA  = 18, //!< [8U]
577
    COLOR_BGR5652RGBA  = 19, //!< [8U]
578
579
    COLOR_GRAY2BGR565  = 20, //!< [8U] convert between grayscale to BGR565 (16-bit images)
580
    COLOR_BGR5652GRAY  = 21, //!< [8U]
581
582
    COLOR_BGR2BGR555   = 22,  //!< [8U] convert between RGB/BGR and BGR555 (16-bit images)
583
    COLOR_RGB2BGR555   = 23,  //!< [8U]
584
    COLOR_BGR5552BGR   = 24,  //!< [8U]
585
    COLOR_BGR5552RGB   = 25,  //!< [8U]
586
    COLOR_BGRA2BGR555  = 26,  //!< [8U]
587
    COLOR_RGBA2BGR555  = 27,  //!< [8U]
588
    COLOR_BGR5552BGRA  = 28,  //!< [8U]
589
    COLOR_BGR5552RGBA  = 29,  //!< [8U]
590
591
    COLOR_GRAY2BGR555  = 30, //!< [8U] convert between grayscale and BGR555 (16-bit images)
592
    COLOR_BGR5552GRAY  = 31, //!< [8U]
593
594
    COLOR_BGR2XYZ      = 32, //!< [8U/16U/32F] convert RGB/BGR to CIE XYZ, @ref color_convert_rgb_xyz "color conversions"
595
    COLOR_RGB2XYZ      = 33, //!< [8U/16U/32F]
596
    COLOR_XYZ2BGR      = 34, //!< [8U/16U/32F]
597
    COLOR_XYZ2RGB      = 35, //!< [8U/16U/32F]
598
599
    COLOR_BGR2YCrCb    = 36, //!< [8U/16U/32F] convert RGB/BGR to luma-chroma (aka YCC), @ref color_convert_rgb_ycrcb "color conversions"
600
    COLOR_RGB2YCrCb    = 37, //!< [8U/16U/32F]
601
    COLOR_YCrCb2BGR    = 38, //!< [8U/16U/32F]
602
    COLOR_YCrCb2RGB    = 39, //!< [8U/16U/32F]
603
604
    COLOR_BGR2HSV      = 40, //!< [8U/32F] convert RGB/BGR to HSV (hue saturation value) with H range 0..180 if 8 bit image, @ref color_convert_rgb_hsv "color conversions"
605
    COLOR_RGB2HSV      = 41, //!< [8U/32F]
606
607
    COLOR_BGR2Lab      = 44, //!< [8U/32F] convert RGB/BGR to CIE Lab, @ref color_convert_rgb_lab "color conversions"
608
    COLOR_RGB2Lab      = 45, //!< [8U/32F]
609
610
    COLOR_BGR2Luv      = 50, //!< [8U/32F] convert RGB/BGR to CIE Luv, @ref color_convert_rgb_luv "color conversions"
611
    COLOR_RGB2Luv      = 51, //!< [8U/32F]
612
    COLOR_BGR2HLS      = 52, //!< [8U/32F] convert RGB/BGR to HLS (hue lightness saturation) with H range 0..180 if 8 bit image, @ref color_convert_rgb_hls "color conversions"
613
    COLOR_RGB2HLS      = 53, //!< [8U/32F]
614
615
    COLOR_HSV2BGR      = 54, //!< [8U/32F] backward conversions HSV to RGB/BGR with H range 0..180 if 8 bit image
616
    COLOR_HSV2RGB      = 55, //!< [8U/32F]
617
618
    COLOR_Lab2BGR      = 56, //!< [8U/32F]
619
    COLOR_Lab2RGB      = 57, //!< [8U/32F]
620
    COLOR_Luv2BGR      = 58, //!< [8U/32F]
621
    COLOR_Luv2RGB      = 59, //!< [8U/32F]
622
    COLOR_HLS2BGR      = 60, //!< [8U/32F] backward conversions HLS to RGB/BGR with H range 0..180 if 8 bit image
623
    COLOR_HLS2RGB      = 61, //!< [8U/32F]
624
625
    COLOR_BGR2HSV_FULL = 66, //!< [8U/32F] convert RGB/BGR to HSV (hue saturation value) with H range 0..255 if 8 bit image, @ref color_convert_rgb_hsv "color conversions"
626
    COLOR_RGB2HSV_FULL = 67, //!< [8U/32F]
627
    COLOR_BGR2HLS_FULL = 68, //!< [8U/32F] convert RGB/BGR to HLS (hue lightness saturation) with H range 0..255 if 8 bit image, @ref color_convert_rgb_hls "color conversions"
628
    COLOR_RGB2HLS_FULL = 69, //!< [8U/32F]
629
630
    COLOR_HSV2BGR_FULL = 70, //!< [8U/32F] backward conversions HSV to RGB/BGR with H range 0..255 if 8 bit image
631
    COLOR_HSV2RGB_FULL = 71, //!< [8U/32F]
632
    COLOR_HLS2BGR_FULL = 72, //!< [8U/32F] backward conversions HLS to RGB/BGR with H range 0..255 if 8 bit image
633
    COLOR_HLS2RGB_FULL = 73, //!< [8U/32F]
634
635
    COLOR_LBGR2Lab     = 74, //!< [8U/32F]
636
    COLOR_LRGB2Lab     = 75, //!< [8U/32F]
637
    COLOR_LBGR2Luv     = 76, //!< [8U/32F]
638
    COLOR_LRGB2Luv     = 77, //!< [8U/32F]
639
640
    COLOR_Lab2LBGR     = 78, //!< [8U/32F]
641
    COLOR_Lab2LRGB     = 79, //!< [8U/32F]
642
    COLOR_Luv2LBGR     = 80, //!< [8U/32F]
643
    COLOR_Luv2LRGB     = 81, //!< [8U/32F]
644
645
    COLOR_BGR2YUV      = 82, //!< [8U/16U/32F] convert between RGB/BGR and YUV
646
    COLOR_RGB2YUV      = 83, //!< [8U/16U/32F]
647
    COLOR_YUV2BGR      = 84, //!< [8U/16U/32F]
648
    COLOR_YUV2RGB      = 85, //!< [8U/16U/32F]
649
650
    COLOR_YUV2RGB_NV12  = 90, //!< [8U] convert between 4:2:0-subsampled YUV NV12 and RGB, two planes (in one or separate arrays): Y and U/V interleaved, see @ref color_convert_rgb_yuv_42x
651
    COLOR_YUV2BGR_NV12  = 91, //!< [8U] convert between 4:2:0-subsampled YUV NV12 and BGR, two planes (in one or separate arrays): Y and U/V interleaved, see @ref color_convert_rgb_yuv_42x
652
    COLOR_YUV2RGB_NV21  = 92, //!< [8U] convert between 4:2:0-subsampled YUV NV21 and RGB, two planes (in one or separate arrays): Y and V/U interleaved, see @ref color_convert_rgb_yuv_42x
653
    COLOR_YUV2BGR_NV21  = 93, //!< [8U] convert between 4:2:0-subsampled YUV NV21 and BGR, two planes (in one or separate arrays): Y and V/U interleaved, see @ref color_convert_rgb_yuv_42x
654
    COLOR_YUV420sp2RGB  = COLOR_YUV2RGB_NV21, //!< synonym to NV21
655
    COLOR_YUV420sp2BGR  = COLOR_YUV2BGR_NV21, //!< synonym to NV21
656
657
    COLOR_YUV2RGBA_NV12 = 94, //!< [8U] convert between 4:2:0-subsampled YUV NV12 and RGBA, two planes (in one or separate arrays): Y and U/V interleaved, see @ref color_convert_rgb_yuv_42x
658
    COLOR_YUV2BGRA_NV12 = 95, //!< [8U] convert between 4:2:0-subsampled YUV NV12 and BGRA, two planes (in one or separate arrays): Y and U/V interleaved, see @ref color_convert_rgb_yuv_42x
659
    COLOR_YUV2RGBA_NV21 = 96, //!< [8U] convert between 4:2:0-subsampled YUV NV21 and RGBA, two planes (in one or separate arrays): Y and V/U interleaved, see @ref color_convert_rgb_yuv_42x
660
    COLOR_YUV2BGRA_NV21 = 97, //!< [8U] convert between 4:2:0-subsampled YUV NV21 and BGRA, two planes (in one or separate arrays): Y and V/U interleaved, see @ref color_convert_rgb_yuv_42x
661
    COLOR_YUV420sp2RGBA = COLOR_YUV2RGBA_NV21, //!< synonym to NV21
662
    COLOR_YUV420sp2BGRA = COLOR_YUV2BGRA_NV21, //!< synonym to NV21
663
664
    COLOR_YUV2RGB_YV12  =  98, //!< [8U] convert between 4:2:0-subsampled YUV YV12 and RGB, three planes in one array: Y, V and U, see @ref color_convert_rgb_yuv_42x
665
    COLOR_YUV2BGR_YV12  =  99, //!< [8U] convert between 4:2:0-subsampled YUV YV12 and BGR, three planes in one array: Y, V and U, see @ref color_convert_rgb_yuv_42x
666
    COLOR_YUV2RGB_IYUV  = 100, //!< [8U] convert between 4:2:0-subsampled YUV IYUV and RGB, three planes in one array: Y, U and V, see @ref color_convert_rgb_yuv_42x
667
    COLOR_YUV2BGR_IYUV  = 101, //!< [8U] convert between 4:2:0-subsampled YUV IYUV and BGR, three planes in one array: Y, U and V, see @ref color_convert_rgb_yuv_42x
668
    COLOR_YUV2RGB_I420  = COLOR_YUV2RGB_IYUV, //!< synonym to IYUV
669
    COLOR_YUV2BGR_I420  = COLOR_YUV2BGR_IYUV, //!< synonym to IYUV
670
    COLOR_YUV420p2RGB   = COLOR_YUV2RGB_YV12, //!< synonym to YV12
671
    COLOR_YUV420p2BGR   = COLOR_YUV2BGR_YV12, //!< synonym to YV12
672
673
    COLOR_YUV2RGBA_YV12 = 102, //!< [8U] convert between 4:2:0-subsampled YUV YV12 and RGBA, three planes in one array: Y, V and U, see @ref color_convert_rgb_yuv_42x
674
    COLOR_YUV2BGRA_YV12 = 103, //!< [8U] convert between 4:2:0-subsampled YUV YV12 and BGRA, three planes in one array: Y, V and U, see @ref color_convert_rgb_yuv_42x
675
    COLOR_YUV2RGBA_IYUV = 104, //!< [8U] convert between 4:2:0-subsampled YUV YV12 and RGBA, three planes in one array: Y, U and V, see @ref color_convert_rgb_yuv_42x
676
    COLOR_YUV2BGRA_IYUV = 105, //!< [8U] convert between 4:2:0-subsampled YUV YV12 and BGRA, three planes in one array: Y, U and V, see @ref color_convert_rgb_yuv_42x
677
    COLOR_YUV2RGBA_I420 = COLOR_YUV2RGBA_IYUV, //!< synonym to IYUV
678
    COLOR_YUV2BGRA_I420 = COLOR_YUV2BGRA_IYUV, //!< synonym to IYUV
679
    COLOR_YUV420p2RGBA  = COLOR_YUV2RGBA_YV12, //!< synonym to YV12
680
    COLOR_YUV420p2BGRA  = COLOR_YUV2BGRA_YV12, //!< synonym to YV12
681
682
    COLOR_YUV2GRAY_420  = 106, //!< [8U] extract Y channel from YUV 4:2:0 image
683
    COLOR_YUV2GRAY_NV21 = COLOR_YUV2GRAY_420, //!< synonym to COLOR_YUV2GRAY_420
684
    COLOR_YUV2GRAY_NV12 = COLOR_YUV2GRAY_420, //!< synonym to COLOR_YUV2GRAY_420
685
    COLOR_YUV2GRAY_YV12 = COLOR_YUV2GRAY_420, //!< synonym to COLOR_YUV2GRAY_420
686
    COLOR_YUV2GRAY_IYUV = COLOR_YUV2GRAY_420, //!< synonym to COLOR_YUV2GRAY_420
687
    COLOR_YUV2GRAY_I420 = COLOR_YUV2GRAY_420, //!< synonym to COLOR_YUV2GRAY_420
688
    COLOR_YUV420sp2GRAY = COLOR_YUV2GRAY_420, //!< synonym to COLOR_YUV2GRAY_420
689
    COLOR_YUV420p2GRAY  = COLOR_YUV2GRAY_420, //!< synonym to COLOR_YUV2GRAY_420
690
691
    COLOR_YUV2RGB_UYVY = 107, //!< [8U] convert between YUV UYVY and RGB, YUV is 4:2:2-subsampled and interleaved as U/Y1/V/Y2, see @ref color_convert_rgb_yuv_42x
692
    COLOR_YUV2BGR_UYVY = 108, //!< [8U] convert between YUV UYVY and BGR, YUV is 4:2:2-subsampled and interleaved as U/Y1/V/Y2, see @ref color_convert_rgb_yuv_42x
693
    //COLOR_YUV2RGB_VYUY = 109, //!< convert between YUV VYUY and RGB, YUV is 4:2:2-subsampled and interleaved as V/Y1/U/Y2, see @ref color_convert_rgb_yuv_42x
694
    //COLOR_YUV2BGR_VYUY = 110, //!< convert between YUV VYUY and BGR, YUV is 4:2:2-subsampled and interleaved as V/Y1/U/Y2, see @ref color_convert_rgb_yuv_42x
695
    COLOR_YUV2RGB_Y422 = COLOR_YUV2RGB_UYVY, //!< synonym to UYVY
696
    COLOR_YUV2BGR_Y422 = COLOR_YUV2BGR_UYVY, //!< synonym to UYVY
697
    COLOR_YUV2RGB_UYNV = COLOR_YUV2RGB_UYVY, //!< synonym to UYVY
698
    COLOR_YUV2BGR_UYNV = COLOR_YUV2BGR_UYVY, //!< synonym to UYVY
699
700
    COLOR_YUV2RGBA_UYVY = 111, //!< [8U] convert between YUV UYVY and RGBA, YUV is 4:2:2-subsampled and interleaved as U/Y1/V/Y2, see @ref color_convert_rgb_yuv_42x
701
    COLOR_YUV2BGRA_UYVY = 112, //!< [8U] convert between YUV UYVY and BGRA, YUV is 4:2:2-subsampled and interleaved as U/Y1/V/Y2, see @ref color_convert_rgb_yuv_42x
702
    //COLOR_YUV2RGBA_VYUY = 113, //!< [8U] convert between YUV VYUY and RGBA, YUV is 4:2:2-subsampled and interleaved as V/Y1/U/Y2, see @ref color_convert_rgb_yuv_42x
703
    //COLOR_YUV2BGRA_VYUY = 114, //!< [8U] convert between YUV VYUY and BGRA, YUV is 4:2:2-subsampled and interleaved as V/Y1/U/Y2, see @ref color_convert_rgb_yuv_42x
704
    COLOR_YUV2RGBA_Y422 = COLOR_YUV2RGBA_UYVY, //!< synonym to UYVY
705
    COLOR_YUV2BGRA_Y422 = COLOR_YUV2BGRA_UYVY, //!< synonym to UYVY
706
    COLOR_YUV2RGBA_UYNV = COLOR_YUV2RGBA_UYVY, //!< synonym to UYVY
707
    COLOR_YUV2BGRA_UYNV = COLOR_YUV2BGRA_UYVY, //!< synonym to UYVY
708
709
    COLOR_YUV2RGB_YUY2 = 115, //!< [8U] convert between YUV YUY2 and RGB, YUV is 4:2:2-subsampled and interleaved as Y1/U/Y2/V, see @ref color_convert_rgb_yuv_42x
710
    COLOR_YUV2BGR_YUY2 = 116, //!< [8U] convert between YUV YUY2 and BGR, YUV is 4:2:2-subsampled and interleaved as Y1/U/Y2/V, see @ref color_convert_rgb_yuv_42x
711
    COLOR_YUV2RGB_YVYU = 117, //!< [8U] convert between YUV YVYU and RGB, YUV is 4:2:2-subsampled and interleaved as Y1/V/Y2/U, see @ref color_convert_rgb_yuv_42x
712
    COLOR_YUV2BGR_YVYU = 118, //!< [8U] convert between YUV YVYU and BGR, YUV is 4:2:2-subsampled and interleaved as Y1/V/Y2/U, see @ref color_convert_rgb_yuv_42x
713
    COLOR_YUV2RGB_YUYV = COLOR_YUV2RGB_YUY2, //!< synonym to YUY2
714
    COLOR_YUV2BGR_YUYV = COLOR_YUV2BGR_YUY2, //!< synonym to YUY2
715
    COLOR_YUV2RGB_YUNV = COLOR_YUV2RGB_YUY2, //!< synonym to YUY2
716
    COLOR_YUV2BGR_YUNV = COLOR_YUV2BGR_YUY2, //!< synonym to YUY2
717
718
    COLOR_YUV2RGBA_YUY2 = 119, //!< [8U] convert between YUV YUY2 and RGBA, YUV is 4:2:2-subsampled and interleaved as Y1/U/Y2/V, see @ref color_convert_rgb_yuv_42x
719
    COLOR_YUV2BGRA_YUY2 = 120, //!< [8U] convert between YUV YUY2 and BGRA, YUV is 4:2:2-subsampled and interleaved as Y1/U/Y2/V, see @ref color_convert_rgb_yuv_42x
720
    COLOR_YUV2RGBA_YVYU = 121, //!< [8U] convert between YUV YVYU and RGBA, YUV is 4:2:2-subsampled and interleaved as Y1/V/Y2/U, see @ref color_convert_rgb_yuv_42x
721
    COLOR_YUV2BGRA_YVYU = 122, //!< [8U] convert between YUV YVYU and BGRA, YUV is 4:2:2-subsampled and interleaved as Y1/V/Y2/U, see @ref color_convert_rgb_yuv_42x
722
    COLOR_YUV2RGBA_YUYV = COLOR_YUV2RGBA_YUY2, //!< synonym to YUY2
723
    COLOR_YUV2BGRA_YUYV = COLOR_YUV2BGRA_YUY2, //!< synonym to YUY2
724
    COLOR_YUV2RGBA_YUNV = COLOR_YUV2RGBA_YUY2, //!< synonym to YUY2
725
    COLOR_YUV2BGRA_YUNV = COLOR_YUV2BGRA_YUY2, //!< synonym to YUY2
726
727
    COLOR_YUV2GRAY_UYVY = 123, //!< [8U] extract Y channel from YUV 4:2:2 image
728
    COLOR_YUV2GRAY_YUY2 = 124, //!< [8U] extract Y channel from YUV 4:2:2 image
729
    //CV_YUV2GRAY_VYUY  = CV_YUV2GRAY_UYVY, //!< synonym to COLOR_YUV2GRAY_UYVY
730
    COLOR_YUV2GRAY_Y422 = COLOR_YUV2GRAY_UYVY, //!< synonym to COLOR_YUV2GRAY_UYVY
731
    COLOR_YUV2GRAY_UYNV = COLOR_YUV2GRAY_UYVY, //!< synonym to COLOR_YUV2GRAY_UYVY
732
    COLOR_YUV2GRAY_YVYU = COLOR_YUV2GRAY_YUY2, //!< synonym to COLOR_YUV2GRAY_YUY2
733
    COLOR_YUV2GRAY_YUYV = COLOR_YUV2GRAY_YUY2, //!< synonym to COLOR_YUV2GRAY_YUY2
734
    COLOR_YUV2GRAY_YUNV = COLOR_YUV2GRAY_YUY2, //!< synonym to COLOR_YUV2GRAY_YUY2
735
736
    //! alpha premultiplication
737
    COLOR_RGBA2mRGBA    = 125, //!< [8U]
738
    COLOR_mRGBA2RGBA    = 126, //!< [8U]
739
740
    COLOR_RGB2YUV_I420  = 127, //!< [8U] convert between RGB and 4:2:0-subsampled YUV I420, three planes in one array: Y, U and V, see @ref color_convert_rgb_yuv_42x
741
    COLOR_BGR2YUV_I420  = 128, //!< [8U] convert between BGR and 4:2:0-subsampled YUV I420, three planes in one array: Y, U and V, see @ref color_convert_rgb_yuv_42x
742
    COLOR_RGB2YUV_IYUV  = COLOR_RGB2YUV_I420, //!< synonym to I420
743
    COLOR_BGR2YUV_IYUV  = COLOR_BGR2YUV_I420, //!< synonym to I420
744
745
    COLOR_RGBA2YUV_I420 = 129, //!< [8U] convert between RGBA and 4:2:0-subsampled YUV I420, three planes in one array: Y, U and V, see @ref color_convert_rgb_yuv_42x
746
    COLOR_BGRA2YUV_I420 = 130, //!< [8U] convert between BGRA and 4:2:0-subsampled YUV I420, three planes in one array: Y, U and V, see @ref color_convert_rgb_yuv_42x
747
    COLOR_RGBA2YUV_IYUV = COLOR_RGBA2YUV_I420, //!< synonym to I420
748
    COLOR_BGRA2YUV_IYUV = COLOR_BGRA2YUV_I420, //!< synonym to I420
749
    COLOR_RGB2YUV_YV12  = 131, //!< [8U] convert between RGB and 4:2:0-subsampled YUV YV12, three planes in one array: Y, V and U, see @ref color_convert_rgb_yuv_42x
750
    COLOR_BGR2YUV_YV12  = 132, //!< [8U] convert between BGR and 4:2:0-subsampled YUV YV12, three planes in one array: Y, V and U, see @ref color_convert_rgb_yuv_42x
751
    COLOR_RGBA2YUV_YV12 = 133, //!< [8U] convert between RGBA and 4:2:0-subsampled YUV YV12, three planes in one array: Y, V and U, see @ref color_convert_rgb_yuv_42x
752
    COLOR_BGRA2YUV_YV12 = 134, //!< [8U] convert between BGRA and 4:2:0-subsampled YUV YV12, three planes in one array: Y, V and U, see @ref color_convert_rgb_yuv_42x
753
754
    //! Demosaicing, see @ref color_convert_bayer "color conversions" for additional information
755
    COLOR_BayerBG2BGR = 46, //!< [8U/16U] equivalent to RGGB Bayer pattern
756
    COLOR_BayerGB2BGR = 47, //!< [8U/16U] equivalent to GRBG Bayer pattern
757
    COLOR_BayerRG2BGR = 48, //!< [8U/16U] equivalent to BGGR Bayer pattern
758
    COLOR_BayerGR2BGR = 49, //!< [8U/16U] equivalent to GBRG Bayer pattern
759
760
    COLOR_BayerRGGB2BGR = COLOR_BayerBG2BGR, //!< [8U/16U]
761
    COLOR_BayerGRBG2BGR = COLOR_BayerGB2BGR, //!< [8U/16U]
762
    COLOR_BayerBGGR2BGR = COLOR_BayerRG2BGR, //!< [8U/16U]
763
    COLOR_BayerGBRG2BGR = COLOR_BayerGR2BGR, //!< [8U/16U]
764
765
    COLOR_BayerRGGB2RGB = COLOR_BayerBGGR2BGR, //!< [8U/16U]
766
    COLOR_BayerGRBG2RGB = COLOR_BayerGBRG2BGR, //!< [8U/16U]
767
    COLOR_BayerBGGR2RGB = COLOR_BayerRGGB2BGR, //!< [8U/16U]
768
    COLOR_BayerGBRG2RGB = COLOR_BayerGRBG2BGR, //!< [8U/16U]
769
770
    COLOR_BayerBG2RGB = COLOR_BayerRG2BGR, //!< [8U/16U] equivalent to RGGB Bayer pattern
771
    COLOR_BayerGB2RGB = COLOR_BayerGR2BGR, //!< [8U/16U] equivalent to GRBG Bayer pattern
772
    COLOR_BayerRG2RGB = COLOR_BayerBG2BGR, //!< [8U/16U] equivalent to BGGR Bayer pattern
773
    COLOR_BayerGR2RGB = COLOR_BayerGB2BGR, //!< [8U/16U] equivalent to GBRG Bayer pattern
774
775
    COLOR_BayerBG2GRAY = 86, //!< [8U/16U] equivalent to RGGB Bayer pattern
776
    COLOR_BayerGB2GRAY = 87, //!< [8U/16U] equivalent to GRBG Bayer pattern
777
    COLOR_BayerRG2GRAY = 88, //!< [8U/16U] equivalent to BGGR Bayer pattern
778
    COLOR_BayerGR2GRAY = 89, //!< [8U/16U] equivalent to GBRG Bayer pattern
779
780
    COLOR_BayerRGGB2GRAY = COLOR_BayerBG2GRAY, //!< [8U/16U]
781
    COLOR_BayerGRBG2GRAY = COLOR_BayerGB2GRAY, //!< [8U/16U]
782
    COLOR_BayerBGGR2GRAY = COLOR_BayerRG2GRAY, //!< [8U/16U]
783
    COLOR_BayerGBRG2GRAY = COLOR_BayerGR2GRAY, //!< [8U/16U]
784
785
    //! Demosaicing using Variable Number of Gradients
786
    COLOR_BayerBG2BGR_VNG = 62, //!< [8U] equivalent to RGGB Bayer pattern
787
    COLOR_BayerGB2BGR_VNG = 63, //!< [8U] equivalent to GRBG Bayer pattern
788
    COLOR_BayerRG2BGR_VNG = 64, //!< [8U] equivalent to BGGR Bayer pattern
789
    COLOR_BayerGR2BGR_VNG = 65, //!< [8U] equivalent to GBRG Bayer pattern
790
791
    COLOR_BayerRGGB2BGR_VNG = COLOR_BayerBG2BGR_VNG, //!< [8U]
792
    COLOR_BayerGRBG2BGR_VNG = COLOR_BayerGB2BGR_VNG, //!< [8U]
793
    COLOR_BayerBGGR2BGR_VNG = COLOR_BayerRG2BGR_VNG, //!< [8U]
794
    COLOR_BayerGBRG2BGR_VNG = COLOR_BayerGR2BGR_VNG, //!< [8U]
795
796
    COLOR_BayerRGGB2RGB_VNG = COLOR_BayerBGGR2BGR_VNG, //!< [8U]
797
    COLOR_BayerGRBG2RGB_VNG = COLOR_BayerGBRG2BGR_VNG, //!< [8U]
798
    COLOR_BayerBGGR2RGB_VNG = COLOR_BayerRGGB2BGR_VNG, //!< [8U]
799
    COLOR_BayerGBRG2RGB_VNG = COLOR_BayerGRBG2BGR_VNG, //!< [8U]
800
801
    COLOR_BayerBG2RGB_VNG = COLOR_BayerRG2BGR_VNG, //!< [8U] equivalent to RGGB Bayer pattern
802
    COLOR_BayerGB2RGB_VNG = COLOR_BayerGR2BGR_VNG, //!< [8U] equivalent to GRBG Bayer pattern
803
    COLOR_BayerRG2RGB_VNG = COLOR_BayerBG2BGR_VNG, //!< [8U] equivalent to BGGR Bayer pattern
804
    COLOR_BayerGR2RGB_VNG = COLOR_BayerGB2BGR_VNG, //!< [8U] equivalent to GBRG Bayer pattern
805
806
    //! Edge-Aware Demosaicing
807
    COLOR_BayerBG2BGR_EA  = 135, //!< [8U/16U] equivalent to RGGB Bayer pattern
808
    COLOR_BayerGB2BGR_EA  = 136, //!< [8U/16U] equivalent to GRBG Bayer pattern
809
    COLOR_BayerRG2BGR_EA  = 137, //!< [8U/16U] equivalent to BGGR Bayer pattern
810
    COLOR_BayerGR2BGR_EA  = 138, //!< [8U/16U] equivalent to GBRG Bayer pattern
811
812
    COLOR_BayerRGGB2BGR_EA  = COLOR_BayerBG2BGR_EA, //!< [8U/16U]
813
    COLOR_BayerGRBG2BGR_EA  = COLOR_BayerGB2BGR_EA, //!< [8U/16U]
814
    COLOR_BayerBGGR2BGR_EA  = COLOR_BayerRG2BGR_EA, //!< [8U/16U]
815
    COLOR_BayerGBRG2BGR_EA  = COLOR_BayerGR2BGR_EA, //!< [8U/16U]
816
817
    COLOR_BayerRGGB2RGB_EA  = COLOR_BayerBGGR2BGR_EA, //!< [8U/16U]
818
    COLOR_BayerGRBG2RGB_EA  = COLOR_BayerGBRG2BGR_EA, //!< [8U/16U]
819
    COLOR_BayerBGGR2RGB_EA  = COLOR_BayerRGGB2BGR_EA, //!< [8U/16U]
820
    COLOR_BayerGBRG2RGB_EA  = COLOR_BayerGRBG2BGR_EA, //!< [8U/16U]
821
822
    COLOR_BayerBG2RGB_EA  = COLOR_BayerRG2BGR_EA, //!< [8U/16U] equivalent to RGGB Bayer pattern
823
    COLOR_BayerGB2RGB_EA  = COLOR_BayerGR2BGR_EA, //!< [8U/16U] equivalent to GRBG Bayer pattern
824
    COLOR_BayerRG2RGB_EA  = COLOR_BayerBG2BGR_EA, //!< [8U/16U] equivalent to BGGR Bayer pattern
825
    COLOR_BayerGR2RGB_EA  = COLOR_BayerGB2BGR_EA, //!< [8U/16U] equivalent to GBRG Bayer pattern
826
827
    //! Demosaicing with alpha channel
828
    COLOR_BayerBG2BGRA = 139, //!< [8U/16U] equivalent to RGGB Bayer pattern
829
    COLOR_BayerGB2BGRA = 140, //!< [8U/16U] equivalent to GRBG Bayer pattern
830
    COLOR_BayerRG2BGRA = 141, //!< [8U/16U] equivalent to BGGR Bayer pattern
831
    COLOR_BayerGR2BGRA = 142, //!< [8U/16U] equivalent to GBRG Bayer pattern
832
833
    COLOR_BayerRGGB2BGRA = COLOR_BayerBG2BGRA, //!< [8U/16U]
834
    COLOR_BayerGRBG2BGRA = COLOR_BayerGB2BGRA, //!< [8U/16U]
835
    COLOR_BayerBGGR2BGRA = COLOR_BayerRG2BGRA, //!< [8U/16U]
836
    COLOR_BayerGBRG2BGRA = COLOR_BayerGR2BGRA, //!< [8U/16U]
837
838
    COLOR_BayerRGGB2RGBA = COLOR_BayerBGGR2BGRA, //!< [8U/16U]
839
    COLOR_BayerGRBG2RGBA = COLOR_BayerGBRG2BGRA, //!< [8U/16U]
840
    COLOR_BayerBGGR2RGBA = COLOR_BayerRGGB2BGRA, //!< [8U/16U]
841
    COLOR_BayerGBRG2RGBA = COLOR_BayerGRBG2BGRA, //!< [8U/16U]
842
843
    COLOR_BayerBG2RGBA = COLOR_BayerRG2BGRA, //!< [8U/16U] equivalent to RGGB Bayer pattern
844
    COLOR_BayerGB2RGBA = COLOR_BayerGR2BGRA, //!< [8U/16U] equivalent to GRBG Bayer pattern
845
    COLOR_BayerRG2RGBA = COLOR_BayerBG2BGRA, //!< [8U/16U] equivalent to BGGR Bayer pattern
846
    COLOR_BayerGR2RGBA = COLOR_BayerGB2BGRA, //!< [8U/16U] equivalent to GBRG Bayer pattern
847
848
    COLOR_RGB2YUV_UYVY = 143, //!< [8U] convert between RGB and YUV UYVU, YUV is 4:2:2 and interleaved as U/Y1/V/Y2, see @ref color_convert_rgb_yuv_42x
849
    COLOR_BGR2YUV_UYVY = 144, //!< [8U] convert between BGR and YUV UYVU, YUV is 4:2:2 and interleaved as U/Y1/V/Y2, see @ref color_convert_rgb_yuv_42x
850
    COLOR_RGB2YUV_Y422 = COLOR_RGB2YUV_UYVY, //!< synonym to UYVY
851
    COLOR_BGR2YUV_Y422 = COLOR_BGR2YUV_UYVY, //!< synonym to UYVY
852
    COLOR_RGB2YUV_UYNV = COLOR_RGB2YUV_UYVY, //!< synonym to UYVY
853
    COLOR_BGR2YUV_UYNV = COLOR_BGR2YUV_UYVY, //!< synonym to UYVY
854
855
    COLOR_RGBA2YUV_UYVY = 145, //!< [8U] convert between RGBA and YUV UYVU, YUV is 4:2:2 and interleaved as U/Y1/V/Y2, see @ref color_convert_rgb_yuv_42x
856
    COLOR_BGRA2YUV_UYVY = 146, //!< [8U] convert between BGRA and YUV UYVU, YUV is 4:2:2 and interleaved as U/Y1/V/Y2, see @ref color_convert_rgb_yuv_42x
857
    COLOR_RGBA2YUV_Y422 = COLOR_RGBA2YUV_UYVY, //!< synonym to UYVY
858
    COLOR_BGRA2YUV_Y422 = COLOR_BGRA2YUV_UYVY, //!< synonym to UYVY
859
    COLOR_RGBA2YUV_UYNV = COLOR_RGBA2YUV_UYVY, //!< synonym to UYVY
860
    COLOR_BGRA2YUV_UYNV = COLOR_BGRA2YUV_UYVY, //!< synonym to UYVY
861
862
    COLOR_RGB2YUV_YUY2 = 147, //!< [8U] convert between RGB and YUV YUY2, YUV is 4:2:2 and interleaved as Y1/U/Y2/V, see @ref color_convert_rgb_yuv_42x
863
    COLOR_BGR2YUV_YUY2 = 148, //!< [8U] convert between BGR and YUV YUY2, YUV is 4:2:2 and interleaved as Y1/U/Y2/V, see @ref color_convert_rgb_yuv_42x
864
    COLOR_RGB2YUV_YVYU = 149, //!< [8U] convert between RGB and YUV YVYU, YUV is 4:2:2 and interleaved as Y1/V/Y2/U, see @ref color_convert_rgb_yuv_42x
865
    COLOR_BGR2YUV_YVYU = 150, //!< [8U] convert between BGR and YUV YVYU, YUV is 4:2:2 and interleaved as Y1/V/Y2/U, see @ref color_convert_rgb_yuv_42x
866
    COLOR_RGB2YUV_YUYV = COLOR_RGB2YUV_YUY2, //!< synonym to YUY2
867
    COLOR_BGR2YUV_YUYV = COLOR_BGR2YUV_YUY2, //!< synonym to YUY2
868
    COLOR_RGB2YUV_YUNV = COLOR_RGB2YUV_YUY2, //!< synonym to YUY2
869
    COLOR_BGR2YUV_YUNV = COLOR_BGR2YUV_YUY2, //!< synonym to YUY2
870
871
    COLOR_RGBA2YUV_YUY2 = 151, //!< [8U] convert between RGBA and YUV YUY2, YUV is 4:2:2 and interleaved as Y1/U/Y2/V, see @ref color_convert_rgb_yuv_42x
872
    COLOR_BGRA2YUV_YUY2 = 152, //!< [8U] convert between BGRA and YUV YUY2, YUV is 4:2:2 and interleaved as Y1/U/Y2/V, see @ref color_convert_rgb_yuv_42x
873
    COLOR_RGBA2YUV_YVYU = 153, //!< [8U] convert between RGBA and YUV YVYU, YUV is 4:2:2 and interleaved as Y1/V/Y2/U, see @ref color_convert_rgb_yuv_42x
874
    COLOR_BGRA2YUV_YVYU = 154, //!< [8U] convert between BGRA and YUV YVYU, YUV is 4:2:2 and interleaved as Y1/V/Y2/U, see @ref color_convert_rgb_yuv_42x
875
    COLOR_RGBA2YUV_YUYV = COLOR_RGBA2YUV_YUY2, //!< synonym to YUY2
876
    COLOR_BGRA2YUV_YUYV = COLOR_BGRA2YUV_YUY2, //!< synonym to YUY2
877
    COLOR_RGBA2YUV_YUNV = COLOR_RGBA2YUV_YUY2, //!< synonym to YUY2
878
    COLOR_BGRA2YUV_YUNV = COLOR_BGRA2YUV_YUY2, //!< synonym to YUY2
879
880
    COLOR_COLORCVT_MAX  = 155
881
};
882
883
//! @addtogroup imgproc_shape
884
//! @{
885
886
//! types of intersection between rectangles
887
enum RectanglesIntersectTypes {
888
    INTERSECT_NONE = 0, //!< No intersection
889
    INTERSECT_PARTIAL  = 1, //!< There is a partial intersection
890
    INTERSECT_FULL  = 2 //!< One of the rectangle is fully enclosed in the other
891
};
892
893
/** types of line
894
@ingroup imgproc_draw
895
*/
896
enum LineTypes {
897
    FILLED  = -1,
898
    LINE_4  = 4, //!< 4-connected line
899
    LINE_8  = 8, //!< 8-connected line
900
    LINE_AA = 16 //!< antialiased line
901
};
902
903
/** Only a subset of Hershey fonts <https://en.wikipedia.org/wiki/Hershey_fonts> are supported
904
@ingroup imgproc_draw
905
*/
906
enum HersheyFonts {
907
    FONT_HERSHEY_SIMPLEX        = 0, //!< normal size sans-serif font
908
    FONT_HERSHEY_PLAIN          = 1, //!< small size sans-serif font
909
    FONT_HERSHEY_DUPLEX         = 2, //!< normal size sans-serif font (more complex than FONT_HERSHEY_SIMPLEX)
910
    FONT_HERSHEY_COMPLEX        = 3, //!< normal size serif font
911
    FONT_HERSHEY_TRIPLEX        = 4, //!< normal size serif font (more complex than FONT_HERSHEY_COMPLEX)
912
    FONT_HERSHEY_COMPLEX_SMALL  = 5, //!< smaller version of FONT_HERSHEY_COMPLEX
913
    FONT_HERSHEY_SCRIPT_SIMPLEX = 6, //!< hand-writing style font
914
    FONT_HERSHEY_SCRIPT_COMPLEX = 7, //!< more complex variant of FONT_HERSHEY_SCRIPT_SIMPLEX
915
    FONT_ITALIC                 = 16 //!< flag for italic font
916
};
917
918
/** Possible set of marker types used for the cv::drawMarker function
919
@ingroup imgproc_draw
920
*/
921
enum MarkerTypes
922
{
923
    MARKER_CROSS = 0,           //!< A crosshair marker shape
924
    MARKER_TILTED_CROSS = 1,    //!< A 45 degree tilted crosshair marker shape
925
    MARKER_STAR = 2,            //!< A star marker shape, combination of cross and tilted cross
926
    MARKER_DIAMOND = 3,         //!< A diamond marker shape
927
    MARKER_SQUARE = 4,          //!< A square marker shape
928
    MARKER_TRIANGLE_UP = 5,     //!< An upwards pointing triangle marker shape
929
    MARKER_TRIANGLE_DOWN = 6    //!< A downwards pointing triangle marker shape
930
};
931
932
/** @brief finds arbitrary template in the grayscale image using Generalized Hough Transform
933
*/
934
class CV_EXPORTS_W GeneralizedHough : public Algorithm
935
{
936
public:
937
    //! set template to search
938
    CV_WRAP virtual void setTemplate(InputArray templ, Point templCenter = Point(-1, -1)) = 0;
939
    CV_WRAP virtual void setTemplate(InputArray edges, InputArray dx, InputArray dy, Point templCenter = Point(-1, -1)) = 0;
940
941
    //! find template on image
942
    CV_WRAP virtual void detect(InputArray image, OutputArray positions, OutputArray votes = noArray()) = 0;
943
    CV_WRAP virtual void detect(InputArray edges, InputArray dx, InputArray dy, OutputArray positions, OutputArray votes = noArray()) = 0;
944
945
    //! Canny low threshold.
946
    CV_WRAP virtual void setCannyLowThresh(int cannyLowThresh) = 0;
947
    CV_WRAP virtual int getCannyLowThresh() const = 0;
948
949
    //! Canny high threshold.
950
    CV_WRAP virtual void setCannyHighThresh(int cannyHighThresh) = 0;
951
    CV_WRAP virtual int getCannyHighThresh() const = 0;
952
953
    //! Minimum distance between the centers of the detected objects.
954
    CV_WRAP virtual void setMinDist(double minDist) = 0;
955
    CV_WRAP virtual double getMinDist() const = 0;
956
957
    //! Inverse ratio of the accumulator resolution to the image resolution.
958
    CV_WRAP virtual void setDp(double dp) = 0;
959
    CV_WRAP virtual double getDp() const = 0;
960
961
    //! Maximal size of inner buffers.
962
    CV_WRAP virtual void setMaxBufferSize(int maxBufferSize) = 0;
963
    CV_WRAP virtual int getMaxBufferSize() const = 0;
964
};
965
966
/** @brief finds arbitrary template in the grayscale image using Generalized Hough Transform
967
968
Detects position only without translation and rotation @cite Ballard1981 .
969
*/
970
class CV_EXPORTS_W GeneralizedHoughBallard : public GeneralizedHough
971
{
972
public:
973
    //! R-Table levels.
974
    CV_WRAP virtual void setLevels(int levels) = 0;
975
    CV_WRAP virtual int getLevels() const = 0;
976
977
    //! The accumulator threshold for the template centers at the detection stage. The smaller it is, the more false positions may be detected.
978
    CV_WRAP virtual void setVotesThreshold(int votesThreshold) = 0;
979
    CV_WRAP virtual int getVotesThreshold() const = 0;
980
};
981
982
/** @brief finds arbitrary template in the grayscale image using Generalized Hough Transform
983
984
Detects position, translation and rotation @cite Guil1999 .
985
*/
986
class CV_EXPORTS_W GeneralizedHoughGuil : public GeneralizedHough
987
{
988
public:
989
    //! Angle difference in degrees between two points in feature.
990
    CV_WRAP virtual void setXi(double xi) = 0;
991
    CV_WRAP virtual double getXi() const = 0;
992
993
    //! Feature table levels.
994
    CV_WRAP virtual void setLevels(int levels) = 0;
995
    CV_WRAP virtual int getLevels() const = 0;
996
997
    //! Maximal difference between angles that treated as equal.
998
    CV_WRAP virtual void setAngleEpsilon(double angleEpsilon) = 0;
999
    CV_WRAP virtual double getAngleEpsilon() const = 0;
1000
1001
    //! Minimal rotation angle to detect in degrees.
1002
    CV_WRAP virtual void setMinAngle(double minAngle) = 0;
1003
    CV_WRAP virtual double getMinAngle() const = 0;
1004
1005
    //! Maximal rotation angle to detect in degrees.
1006
    CV_WRAP virtual void setMaxAngle(double maxAngle) = 0;
1007
    CV_WRAP virtual double getMaxAngle() const = 0;
1008
1009
    //! Angle step in degrees.
1010
    CV_WRAP virtual void setAngleStep(double angleStep) = 0;
1011
    CV_WRAP virtual double getAngleStep() const = 0;
1012
1013
    //! Angle votes threshold.
1014
    CV_WRAP virtual void setAngleThresh(int angleThresh) = 0;
1015
    CV_WRAP virtual int getAngleThresh() const = 0;
1016
1017
    //! Minimal scale to detect.
1018
    CV_WRAP virtual void setMinScale(double minScale) = 0;
1019
    CV_WRAP virtual double getMinScale() const = 0;
1020
1021
    //! Maximal scale to detect.
1022
    CV_WRAP virtual void setMaxScale(double maxScale) = 0;
1023
    CV_WRAP virtual double getMaxScale() const = 0;
1024
1025
    //! Scale step.
1026
    CV_WRAP virtual void setScaleStep(double scaleStep) = 0;
1027
    CV_WRAP virtual double getScaleStep() const = 0;
1028
1029
    //! Scale votes threshold.
1030
    CV_WRAP virtual void setScaleThresh(int scaleThresh) = 0;
1031
    CV_WRAP virtual int getScaleThresh() const = 0;
1032
1033
    //! Position votes threshold.
1034
    CV_WRAP virtual void setPosThresh(int posThresh) = 0;
1035
    CV_WRAP virtual int getPosThresh() const = 0;
1036
};
1037
1038
//! @} imgproc_shape
1039
1040
//! @addtogroup imgproc_hist
1041
//! @{
1042
1043
/** @brief Base class for Contrast Limited Adaptive Histogram Equalization.
1044
*/
1045
class CV_EXPORTS_W CLAHE : public Algorithm
1046
{
1047
public:
1048
    /** @brief Equalizes the histogram of a grayscale image using Contrast Limited Adaptive Histogram Equalization.
1049
1050
    @param src Source image of type CV_8UC1 or CV_16UC1.
1051
    @param dst Destination image.
1052
     */
1053
    CV_WRAP virtual void apply(InputArray src, OutputArray dst) = 0;
1054
1055
    /** @brief Sets threshold for contrast limiting.
1056
1057
    @param clipLimit threshold value.
1058
    */
1059
    CV_WRAP virtual void setClipLimit(double clipLimit) = 0;
1060
1061
    //! Returns threshold value for contrast limiting.
1062
    CV_WRAP virtual double getClipLimit() const = 0;
1063
1064
    /** @brief Sets size of grid for histogram equalization. Input image will be divided into
1065
    equally sized rectangular tiles.
1066
1067
    @param tileGridSize defines the number of tiles in row and column.
1068
    */
1069
    CV_WRAP virtual void setTilesGridSize(Size tileGridSize) = 0;
1070
1071
    //!@brief Returns Size defines the number of tiles in row and column.
1072
    CV_WRAP virtual Size getTilesGridSize() const = 0;
1073
1074
    /** @brief Sets bit shift parameter for histogram bins.
1075
1076
    @param bitShift bit shift value (default is 0).
1077
    */
1078
    CV_WRAP virtual void setBitShift(int bitShift) = 0;
1079
1080
    /** @brief Returns the bit shift parameter for histogram bins.
1081
1082
    @return current bit shift value.
1083
    */
1084
    CV_WRAP virtual int getBitShift() const = 0;
1085
1086
    CV_WRAP virtual void collectGarbage() = 0;
1087
};
1088
1089
//! @} imgproc_hist
1090
1091
//! @addtogroup imgproc_subdiv2d
1092
//! @{
1093
1094
class CV_EXPORTS_W Subdiv2D
1095
{
1096
public:
1097
    /** Subdiv2D point location cases */
1098
    enum { PTLOC_ERROR        = -2, //!< Point location error
1099
           PTLOC_OUTSIDE_RECT = -1, //!< Point outside the subdivision bounding rect
1100
           PTLOC_INSIDE       = 0, //!< Point inside some facet
1101
           PTLOC_VERTEX       = 1, //!< Point coincides with one of the subdivision vertices
1102
           PTLOC_ON_EDGE      = 2  //!< Point on some edge
1103
         };
1104
1105
    /** Subdiv2D edge type navigation (see: getEdge()) */
1106
    enum { NEXT_AROUND_ORG   = 0x00,
1107
           NEXT_AROUND_DST   = 0x22,
1108
           PREV_AROUND_ORG   = 0x11,
1109
           PREV_AROUND_DST   = 0x33,
1110
           NEXT_AROUND_LEFT  = 0x13,
1111
           NEXT_AROUND_RIGHT = 0x31,
1112
           PREV_AROUND_LEFT  = 0x20,
1113
           PREV_AROUND_RIGHT = 0x02
1114
         };
1115
1116
    /** creates an empty Subdiv2D object.
1117
    To create a new empty Delaunay subdivision you need to use the #initDelaunay function.
1118
     */
1119
    CV_WRAP Subdiv2D();
1120
1121
    /** @overload
1122
1123
    @param rect Rectangle that includes all of the 2D points that are to be added to the subdivision.
1124
1125
    The function creates an empty Delaunay subdivision where 2D points can be added using the function
1126
    insert() . All of the points to be added must be within the specified rectangle, otherwise a runtime
1127
    error is raised.
1128
     */
1129
    CV_WRAP Subdiv2D(Rect rect);
1130
1131
    /** @overload */
1132
    CV_WRAP Subdiv2D(Rect2f rect2f);
1133
1134
    /** @overload
1135
1136
    @brief Creates a new empty Delaunay subdivision
1137
1138
    @param rect Rectangle that includes all of the 2D points that are to be added to the subdivision.
1139
1140
     */
1141
    CV_WRAP void initDelaunay(Rect rect);
1142
1143
    /** @overload
1144
1145
    @brief Creates a new empty Delaunay subdivision
1146
1147
    @param rect Rectangle that includes all of the 2d points that are to be added to the subdivision.
1148
1149
     */
1150
    CV_WRAP_AS(initDelaunay2f) CV_WRAP void initDelaunay(Rect2f rect);
1151
1152
    /** @brief Insert a single point into a Delaunay triangulation.
1153
1154
    @param pt Point to insert.
1155
1156
    The function inserts a single point into a subdivision and modifies the subdivision topology
1157
    appropriately. If a point with the same coordinates exists already, no new point is added.
1158
    @returns the ID of the point.
1159
1160
    @note If the point is outside of the triangulation specified rect a runtime error is raised.
1161
     */
1162
    CV_WRAP int insert(Point2f pt);
1163
1164
    /** @brief Insert multiple points into a Delaunay triangulation.
1165
1166
    @param ptvec Points to insert.
1167
1168
    The function inserts a vector of points into a subdivision and modifies the subdivision topology
1169
    appropriately.
1170
     */
1171
    CV_WRAP void insert(const std::vector<Point2f>& ptvec);
1172
1173
    /** @brief Returns the location of a point within a Delaunay triangulation.
1174
1175
    @param pt Point to locate.
1176
    @param edge Output edge that the point belongs to or is located to the right of it.
1177
    @param vertex Optional output vertex the input point coincides with.
1178
1179
    The function locates the input point within the subdivision and gives one of the triangle edges
1180
    or vertices.
1181
1182
    @returns an integer which specify one of the following five cases for point location:
1183
    -  The point falls into some facet. The function returns #PTLOC_INSIDE and edge will contain one of
1184
       edges of the facet.
1185
    -  The point falls onto the edge. The function returns #PTLOC_ON_EDGE and edge will contain this edge.
1186
    -  The point coincides with one of the subdivision vertices. The function returns #PTLOC_VERTEX and
1187
       vertex will contain a pointer to the vertex.
1188
    -  The point is outside the subdivision reference rectangle. The function returns #PTLOC_OUTSIDE_RECT
1189
       and no pointers are filled.
1190
    -  One of input arguments is invalid. A runtime error is raised or, if silent or "parent" error
1191
       processing mode is selected, #PTLOC_ERROR is returned.
1192
     */
1193
    CV_WRAP int locate(Point2f pt, CV_OUT int& edge, CV_OUT int& vertex);
1194
1195
    /** @brief Finds the subdivision vertex closest to the given point.
1196
1197
    @param pt Input point.
1198
    @param nearestPt Output subdivision vertex point.
1199
1200
    The function is another function that locates the input point within the subdivision. It finds the
1201
    subdivision vertex that is the closest to the input point. It is not necessarily one of vertices
1202
    of the facet containing the input point, though the facet (located using locate() ) is used as a
1203
    starting point.
1204
1205
    @returns vertex ID.
1206
     */
1207
    CV_WRAP int findNearest(Point2f pt, CV_OUT Point2f* nearestPt = 0);
1208
1209
    /** @brief Returns a list of all edges.
1210
1211
    @param edgeList Output vector.
1212
1213
    The function gives each edge as a 4 numbers vector, where each two are one of the edge
1214
    vertices. i.e. org_x = v[0], org_y = v[1], dst_x = v[2], dst_y = v[3].
1215
     */
1216
    CV_WRAP void getEdgeList(CV_OUT std::vector<Vec4f>& edgeList) const;
1217
1218
    /** @brief Returns a list of the leading edge ID connected to each triangle.
1219
1220
    @param leadingEdgeList Output vector.
1221
1222
    The function gives one edge ID for each triangle.
1223
     */
1224
    CV_WRAP void getLeadingEdgeList(CV_OUT std::vector<int>& leadingEdgeList) const;
1225
1226
    /** @brief Returns a list of all triangles.
1227
1228
    @param triangleList Output vector.
1229
1230
    The function gives each triangle as a 6 numbers vector, where each two are one of the triangle
1231
    vertices. i.e. p1_x = v[0], p1_y = v[1], p2_x = v[2], p2_y = v[3], p3_x = v[4], p3_y = v[5].
1232
     */
1233
    CV_WRAP void getTriangleList(CV_OUT std::vector<Vec6f>& triangleList) const;
1234
1235
    /** @brief Returns a list of all Voronoi facets.
1236
1237
    @param idx Vector of vertices IDs to consider. For all vertices you can pass empty vector.
1238
    @param facetList Output vector of the Voronoi facets.
1239
    @param facetCenters Output vector of the Voronoi facets center points.
1240
1241
     */
1242
    CV_WRAP void getVoronoiFacetList(const std::vector<int>& idx, CV_OUT std::vector<std::vector<Point2f> >& facetList,
1243
                                     CV_OUT std::vector<Point2f>& facetCenters);
1244
1245
    /** @brief Returns vertex location from vertex ID.
1246
1247
    @param vertex vertex ID.
1248
    @param firstEdge Optional. The first edge ID which is connected to the vertex.
1249
    @returns vertex (x,y)
1250
1251
     */
1252
    CV_WRAP Point2f getVertex(int vertex, CV_OUT int* firstEdge = 0) const;
1253
1254
    /** @brief Returns one of the edges related to the given edge.
1255
1256
    @param edge Subdivision edge ID.
1257
    @param nextEdgeType Parameter specifying which of the related edges to return.
1258
    The following values are possible:
1259
    -   NEXT_AROUND_ORG next around the edge origin ( eOnext on the picture below if e is the input edge)
1260
    -   NEXT_AROUND_DST next around the edge vertex ( eDnext )
1261
    -   PREV_AROUND_ORG previous around the edge origin (reversed eRnext )
1262
    -   PREV_AROUND_DST previous around the edge destination (reversed eLnext )
1263
    -   NEXT_AROUND_LEFT next around the left facet ( eLnext )
1264
    -   NEXT_AROUND_RIGHT next around the right facet ( eRnext )
1265
    -   PREV_AROUND_LEFT previous around the left facet (reversed eOnext )
1266
    -   PREV_AROUND_RIGHT previous around the right facet (reversed eDnext )
1267
1268
    ![sample output](pics/quadedge.png)
1269
1270
    @returns edge ID related to the input edge.
1271
     */
1272
    CV_WRAP int getEdge( int edge, int nextEdgeType ) const;
1273
1274
    /** @brief Returns next edge around the edge origin.
1275
1276
    @param edge Subdivision edge ID.
1277
1278
    @returns an integer which is next edge ID around the edge origin: eOnext on the
1279
    picture above if e is the input edge).
1280
     */
1281
    CV_WRAP int nextEdge(int edge) const;
1282
1283
    /** @brief Returns another edge of the same quad-edge.
1284
1285
    @param edge Subdivision edge ID.
1286
    @param rotate Parameter specifying which of the edges of the same quad-edge as the input
1287
    one to return. The following values are possible:
1288
    -   0 - the input edge ( e on the picture below if e is the input edge)
1289
    -   1 - the rotated edge ( eRot )
1290
    -   2 - the reversed edge (reversed e (in green))
1291
    -   3 - the reversed rotated edge (reversed eRot (in green))
1292
1293
    @returns one of the edges ID of the same quad-edge as the input edge.
1294
     */
1295
    CV_WRAP int rotateEdge(int edge, int rotate) const;
1296
    CV_WRAP int symEdge(int edge) const;
1297
1298
    /** @brief Returns the edge origin.
1299
1300
    @param edge Subdivision edge ID.
1301
    @param orgpt Output vertex location.
1302
1303
    @returns vertex ID.
1304
     */
1305
    CV_WRAP int edgeOrg(int edge, CV_OUT Point2f* orgpt = 0) const;
1306
1307
    /** @brief Returns the edge destination.
1308
1309
    @param edge Subdivision edge ID.
1310
    @param dstpt Output vertex location.
1311
1312
    @returns vertex ID.
1313
     */
1314
    CV_WRAP int edgeDst(int edge, CV_OUT Point2f* dstpt = 0) const;
1315
1316
protected:
1317
    int newEdge();
1318
    void deleteEdge(int edge);
1319
    int newPoint(Point2f pt, bool isvirtual, int firstEdge = 0);
1320
    void deletePoint(int vtx);
1321
    void setEdgePoints( int edge, int orgPt, int dstPt );
1322
    void splice( int edgeA, int edgeB );
1323
    int connectEdges( int edgeA, int edgeB );
1324
    void swapEdges( int edge );
1325
    int isRightOf(Point2f pt, int edge) const;
1326
    void calcVoronoi();
1327
    void clearVoronoi();
1328
    void checkSubdiv() const;
1329
1330
    struct CV_EXPORTS Vertex
1331
    {
1332
        Vertex();
1333
        Vertex(Point2f pt, bool isvirtual, int firstEdge=0);
1334
        bool isvirtual() const;
1335
        bool isfree() const;
1336
1337
        int firstEdge;
1338
        int type;
1339
        Point2f pt;
1340
    };
1341
1342
    struct CV_EXPORTS QuadEdge
1343
    {
1344
        QuadEdge();
1345
        QuadEdge(int edgeidx);
1346
        bool isfree() const;
1347
1348
        int next[4];
1349
        int pt[4];
1350
    };
1351
1352
    //! All of the vertices
1353
    std::vector<Vertex> vtx;
1354
    //! All of the edges
1355
    std::vector<QuadEdge> qedges;
1356
    int freeQEdge;
1357
    int freePoint;
1358
    bool validGeometry;
1359
1360
    int recentEdge;
1361
    //! Top left corner of the bounding rect
1362
    Point2f topLeft;
1363
    //! Bottom right corner of the bounding rect
1364
    Point2f bottomRight;
1365
};
1366
1367
//! @} imgproc_subdiv2d
1368
1369
//! @addtogroup imgproc_feature
1370
//! @{
1371
1372
/** @example samples/cpp/lsd_lines.cpp
1373
An example using the LineSegmentDetector
1374
\image html building_lsd.png "Sample output image" width=434 height=300
1375
*/
1376
1377
/** @brief Line segment detector class
1378
1379
following the algorithm described at @cite Rafael12 .
1380
1381
@note Implementation has been removed from OpenCV version 3.4.6 to 3.4.15 and version 4.1.0 to 4.5.3 due original code license conflict.
1382
restored again after [Computation of a NFA](https://github.com/rafael-grompone-von-gioi/binomial_nfa) code published under the MIT license.
1383
*/
1384
class CV_EXPORTS_W LineSegmentDetector : public Algorithm
1385
{
1386
public:
1387
1388
    /** @brief Finds lines in the input image.
1389
1390
    This is the output of the default parameters of the algorithm on the above shown image.
1391
1392
    ![image](pics/building_lsd.png)
1393
1394
    @param image A grayscale (CV_8UC1) input image. If only a roi needs to be selected, use:
1395
    `lsd_ptr-\>detect(image(roi), lines, ...); lines += Scalar(roi.x, roi.y, roi.x, roi.y);`
1396
    @param lines A vector of Vec4f elements specifying the beginning and ending point of a line. Where
1397
    Vec4f is (x1, y1, x2, y2), point 1 is the start, point 2 - end. Returned lines are strictly
1398
    oriented depending on the gradient.
1399
    @param width Vector of widths of the regions, where the lines are found. E.g. Width of line.
1400
    @param prec Vector of precisions with which the lines are found.
1401
    @param nfa Vector containing number of false alarms in the line region, with precision of 10%. The
1402
    bigger the value, logarithmically better the detection.
1403
    - -1 corresponds to 10 mean false alarms
1404
    - 0 corresponds to 1 mean false alarm
1405
    - 1 corresponds to 0.1 mean false alarms
1406
    This vector will be calculated only when the objects type is #LSD_REFINE_ADV.
1407
    */
1408
    CV_WRAP virtual void detect(InputArray image, OutputArray lines,
1409
                        OutputArray width = noArray(), OutputArray prec = noArray(),
1410
                        OutputArray nfa = noArray()) = 0;
1411
1412
    /** @brief Draws the line segments on a given image.
1413
    @param image The image, where the lines will be drawn. Should be bigger or equal to the image,
1414
    where the lines were found.
1415
    @param lines A vector of the lines that needed to be drawn.
1416
     */
1417
    CV_WRAP virtual void drawSegments(InputOutputArray image, InputArray lines) = 0;
1418
1419
    /** @brief Draws two groups of lines in blue and red, counting the non overlapping (mismatching) pixels.
1420
1421
    @param size The size of the image, where lines1 and lines2 were found.
1422
    @param lines1 The first group of lines that needs to be drawn. It is visualized in blue color.
1423
    @param lines2 The second group of lines. They visualized in red color.
1424
    @param image Optional image, where the lines will be drawn. The image should be color(3-channel)
1425
    in order for lines1 and lines2 to be drawn in the above mentioned colors.
1426
     */
1427
    CV_WRAP virtual int compareSegments(const Size& size, InputArray lines1, InputArray lines2, InputOutputArray image = noArray()) = 0;
1428
1429
0
    virtual ~LineSegmentDetector() { }
1430
};
1431
1432
/** @brief Creates a smart pointer to a LineSegmentDetector object and initializes it.
1433
1434
The LineSegmentDetector algorithm is defined using the standard values. Only advanced users may want
1435
to edit those, as to tailor it for their own application.
1436
1437
@param refine The way found lines will be refined, see #LineSegmentDetectorModes
1438
@param scale The scale of the image that will be used to find the lines. Range (0..1].
1439
@param sigma_scale Sigma for Gaussian filter. It is computed as sigma = sigma_scale/scale.
1440
@param quant Bound to the quantization error on the gradient norm.
1441
@param ang_th Gradient angle tolerance in degrees.
1442
@param log_eps Detection threshold: -log10(NFA) \> log_eps. Used only when advance refinement is chosen.
1443
@param density_th Minimal density of aligned region points in the enclosing rectangle.
1444
@param n_bins Number of bins in pseudo-ordering of gradient modulus.
1445
 */
1446
CV_EXPORTS_W Ptr<LineSegmentDetector> createLineSegmentDetector(
1447
    int refine = LSD_REFINE_STD, double scale = 0.8,
1448
    double sigma_scale = 0.6, double quant = 2.0, double ang_th = 22.5,
1449
    double log_eps = 0, double density_th = 0.7, int n_bins = 1024);
1450
1451
//! @} imgproc_feature
1452
1453
//! @addtogroup imgproc_filter
1454
//! @{
1455
1456
/** @brief Returns Gaussian filter coefficients.
1457
1458
The function computes and returns the \f$\texttt{ksize} \times 1\f$ matrix of Gaussian filter
1459
coefficients:
1460
1461
\f[G_i= \alpha *e^{-(i-( \texttt{ksize} -1)/2)^2/(2* \texttt{sigma}^2)},\f]
1462
1463
where \f$i=0..\texttt{ksize}-1\f$ and \f$\alpha\f$ is the scale factor chosen so that \f$\sum_i G_i=1\f$.
1464
1465
Two of such generated kernels can be passed to sepFilter2D. Those functions automatically recognize
1466
smoothing kernels (a symmetrical kernel with sum of weights equal to 1) and handle them accordingly.
1467
You may also use the higher-level GaussianBlur.
1468
@param ksize Aperture size. It should be odd ( \f$\texttt{ksize} \mod 2 = 1\f$ ) and positive.
1469
@param sigma Gaussian standard deviation. If it is non-positive, it is computed from ksize as
1470
`sigma = 0.3*((ksize-1)*0.5 - 1) + 0.8`.
1471
@param ktype Type of filter coefficients. It can be CV_32F or CV_64F .
1472
@sa  sepFilter2D, getDerivKernels, getStructuringElement, GaussianBlur
1473
 */
1474
CV_EXPORTS_W Mat getGaussianKernel( int ksize, double sigma, int ktype = CV_64F );
1475
1476
/** @brief Returns filter coefficients for computing spatial image derivatives.
1477
1478
The function computes and returns the filter coefficients for spatial image derivatives. When
1479
`ksize=FILTER_SCHARR`, the Scharr \f$3 \times 3\f$ kernels are generated (see #Scharr). Otherwise, Sobel
1480
kernels are generated (see #Sobel). The filters are normally passed to #sepFilter2D or to
1481
1482
@param kx Output matrix of row filter coefficients. It has the type ktype .
1483
@param ky Output matrix of column filter coefficients. It has the type ktype .
1484
@param dx Derivative order in respect of x.
1485
@param dy Derivative order in respect of y.
1486
@param ksize Aperture size. It can be FILTER_SCHARR, 1, 3, 5, or 7.
1487
@param normalize Flag indicating whether to normalize (scale down) the filter coefficients or not.
1488
Theoretically, the coefficients should have the denominator \f$=2^{ksize*2-dx-dy-2}\f$. If you are
1489
going to filter floating-point images, you are likely to use the normalized kernels. But if you
1490
compute derivatives of an 8-bit image, store the results in a 16-bit image, and wish to preserve
1491
all the fractional bits, you may want to set normalize=false .
1492
@param ktype Type of filter coefficients. It can be CV_32f or CV_64F .
1493
 */
1494
CV_EXPORTS_W void getDerivKernels( OutputArray kx, OutputArray ky,
1495
                                   int dx, int dy, int ksize,
1496
                                   bool normalize = false, int ktype = CV_32F );
1497
1498
/** @brief Returns Gabor filter coefficients.
1499
1500
For more details about gabor filter equations and parameters, see: [Gabor
1501
Filter](https://en.wikipedia.org/wiki/Gabor_filter).
1502
1503
@param ksize Size of the filter returned.
1504
@param sigma Standard deviation of the gaussian envelope.
1505
@param theta Orientation of the normal to the parallel stripes of a Gabor function.
1506
@param lambd Wavelength of the sinusoidal factor.
1507
@param gamma Spatial aspect ratio.
1508
@param psi Phase offset.
1509
@param ktype Type of filter coefficients. It can be CV_32F or CV_64F .
1510
 */
1511
CV_EXPORTS_W Mat getGaborKernel( Size ksize, double sigma, double theta, double lambd,
1512
                                 double gamma, double psi = CV_PI*0.5, int ktype = CV_64F );
1513
1514
//! returns "magic" border value for erosion and dilation. It is automatically transformed to Scalar::all(-DBL_MAX) for dilation.
1515
0
static inline Scalar morphologyDefaultBorderValue() { return Scalar::all(DBL_MAX); }
Unexecuted instantiation: generateusergallerycollage_fuzzer.cc:cv::morphologyDefaultBorderValue()
Unexecuted instantiation: imread_fuzzer.cc:cv::morphologyDefaultBorderValue()
Unexecuted instantiation: imdecode_fuzzer.cc:cv::morphologyDefaultBorderValue()
Unexecuted instantiation: filestorage_read_string_fuzzer.cc:cv::morphologyDefaultBorderValue()
Unexecuted instantiation: filestorage_read_file_fuzzer.cc:cv::morphologyDefaultBorderValue()
Unexecuted instantiation: core_fuzzer.cc:cv::morphologyDefaultBorderValue()
Unexecuted instantiation: imencode_fuzzer.cc:cv::morphologyDefaultBorderValue()
Unexecuted instantiation: filestorage_read_filename_fuzzer.cc:cv::morphologyDefaultBorderValue()
1516
1517
/** @brief Returns a structuring element of the specified size and shape for morphological operations.
1518
1519
The function constructs and returns the structuring element that can be further passed to #erode,
1520
#dilate or #morphologyEx. But you can also construct an arbitrary binary mask yourself and use it as
1521
the structuring element.
1522
1523
@param shape Element shape that could be one of #MorphShapes
1524
@param ksize Size of the structuring element.
1525
@param anchor Anchor position within the element. The default value \f$(-1, -1)\f$ means that the
1526
anchor is at the center. Note that only the shape of a cross-shaped element depends on the anchor
1527
position. In other cases the anchor just regulates how much the result of the morphological
1528
operation is shifted.
1529
 */
1530
CV_EXPORTS_W Mat getStructuringElement(int shape, Size ksize, Point anchor = Point(-1,-1));
1531
1532
/** @example samples/cpp/tutorial_code/ImgProc/Smoothing/Smoothing.cpp
1533
Sample code for simple filters
1534
![Sample screenshot](Smoothing_Tutorial_Result_Median_Filter.jpg)
1535
Check @ref tutorial_gausian_median_blur_bilateral_filter "the corresponding tutorial" for more details
1536
 */
1537
1538
/** @brief Blurs an image using the median filter.
1539
1540
The function smoothes an image using the median filter with the \f$\texttt{ksize} \times
1541
\texttt{ksize}\f$ aperture. Each channel of a multi-channel image is processed independently.
1542
In-place operation is supported.
1543
1544
@note The median filter uses #BORDER_REPLICATE internally to cope with border pixels, see #BorderTypes
1545
1546
@param src input 1-, 3-, or 4-channel image; when ksize is 3 or 5, the image depth should be
1547
CV_8U, CV_16U, or CV_32F, for larger aperture sizes, it can only be CV_8U.
1548
@param dst destination array of the same size and type as src.
1549
@param ksize aperture linear size; it must be odd and greater than 1, for example: 3, 5, 7 ...
1550
@sa  bilateralFilter, blur, boxFilter, GaussianBlur
1551
 */
1552
CV_EXPORTS_W void medianBlur( InputArray src, OutputArray dst, int ksize );
1553
1554
/** @brief Blurs an image using a Gaussian filter.
1555
1556
The function convolves the source image with the specified Gaussian kernel. In-place filtering is
1557
supported.
1558
1559
@param src input image; the image can have any number of channels, which are processed
1560
independently, but the depth should be CV_8U, CV_16U, CV_16S, CV_32F or CV_64F.
1561
@param dst output image of the same size and type as src.
1562
@param ksize Gaussian kernel size. ksize.width and ksize.height can differ but they both must be
1563
positive and odd. Or, they can be zero's and then they are computed from sigma.
1564
@param sigmaX Gaussian kernel standard deviation in X direction.
1565
@param sigmaY Gaussian kernel standard deviation in Y direction; if sigmaY is zero, it is set to be
1566
equal to sigmaX, if both sigmas are zeros, they are computed from ksize.width and ksize.height,
1567
respectively (see #getGaussianKernel for details); to fully control the result regardless of
1568
possible future modifications of all this semantics, it is recommended to specify all of ksize,
1569
sigmaX, and sigmaY.
1570
@param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported.
1571
@param hint Implementation modfication flags. See #AlgorithmHint
1572
1573
@sa  sepFilter2D, filter2D, blur, boxFilter, bilateralFilter, medianBlur
1574
 */
1575
CV_EXPORTS_W void GaussianBlur( InputArray src, OutputArray dst, Size ksize,
1576
                                double sigmaX, double sigmaY = 0,
1577
                                int borderType = BORDER_DEFAULT,
1578
                                AlgorithmHint hint = cv::ALGO_HINT_DEFAULT );
1579
1580
/** @brief Applies the bilateral filter to an image.
1581
1582
The function applies bilateral filtering to the input image, as described in
1583
https://homepages.inf.ed.ac.uk/rbf/CVonline/LOCAL_COPIES/MANDUCHI1/Bilateral_Filtering.html
1584
bilateralFilter can reduce unwanted noise very well while keeping edges fairly sharp. However, it is
1585
very slow compared to most filters.
1586
1587
_Sigma values_: For simplicity, you can set the 2 sigma values to be the same. If they are small (\<
1588
10), the filter will not have much effect, whereas if they are large (\> 150), they will have a very
1589
strong effect, making the image look "cartoonish".
1590
1591
_Filter size_: Large filters (d \> 5) are very slow, so it is recommended to use d=5 for real-time
1592
applications, and perhaps d=9 for offline applications that need heavy noise filtering.
1593
1594
This filter does not work inplace.
1595
@param src Source 8-bit or floating-point, 1-channel or 3-channel image.
1596
@param dst Destination image of the same size and type as src .
1597
@param d Diameter of each pixel neighborhood that is used during filtering. If it is non-positive,
1598
it is computed from sigmaSpace.
1599
@param sigmaColor Filter sigma in the color space. A larger value of the parameter means that
1600
farther colors within the pixel neighborhood (see sigmaSpace) will be mixed together, resulting
1601
in larger areas of semi-equal color.
1602
@param sigmaSpace Filter sigma in the coordinate space. A larger value of the parameter means that
1603
farther pixels will influence each other as long as their colors are close enough (see sigmaColor
1604
). When d\>0, it specifies the neighborhood size regardless of sigmaSpace. Otherwise, d is
1605
proportional to sigmaSpace.
1606
@param borderType border mode used to extrapolate pixels outside of the image, see #BorderTypes
1607
 */
1608
CV_EXPORTS_W void bilateralFilter( InputArray src, OutputArray dst, int d,
1609
                                   double sigmaColor, double sigmaSpace,
1610
                                   int borderType = BORDER_DEFAULT );
1611
1612
/** @brief Blurs an image using the box filter.
1613
1614
The function smooths an image using the kernel:
1615
1616
\f[\texttt{K} =  \alpha \begin{bmatrix} 1 & 1 & 1 &  \cdots & 1 & 1  \\ 1 & 1 & 1 &  \cdots & 1 & 1  \\ \hdotsfor{6} \\ 1 & 1 & 1 &  \cdots & 1 & 1 \end{bmatrix}\f]
1617
1618
where
1619
1620
\f[\alpha = \begin{cases} \frac{1}{\texttt{ksize.width*ksize.height}} & \texttt{when } \texttt{normalize=true}  \\1 & \texttt{otherwise}\end{cases}\f]
1621
1622
Unnormalized box filter is useful for computing various integral characteristics over each pixel
1623
neighborhood, such as covariance matrices of image derivatives (used in dense optical flow
1624
algorithms, and so on). If you need to compute pixel sums over variable-size windows, use #integral.
1625
1626
@param src input image.
1627
@param dst output image of the same size and type as src.
1628
@param ddepth the output image depth (-1 to use src.depth()).
1629
@param ksize blurring kernel size.
1630
@param anchor anchor point; default value Point(-1,-1) means that the anchor is at the kernel
1631
center.
1632
@param normalize flag, specifying whether the kernel is normalized by its area or not.
1633
@param borderType border mode used to extrapolate pixels outside of the image, see #BorderTypes. #BORDER_WRAP is not supported.
1634
@sa  blur, bilateralFilter, GaussianBlur, medianBlur, integral
1635
 */
1636
CV_EXPORTS_W void boxFilter( InputArray src, OutputArray dst, int ddepth,
1637
                             Size ksize, Point anchor = Point(-1,-1),
1638
                             bool normalize = true,
1639
                             int borderType = BORDER_DEFAULT );
1640
1641
/** @brief Calculates the normalized sum of squares of the pixel values overlapping the filter.
1642
1643
For every pixel \f$ (x, y) \f$ in the source image, the function calculates the sum of squares of those neighboring
1644
pixel values which overlap the filter placed over the pixel \f$ (x, y) \f$.
1645
1646
The unnormalized square box filter can be useful in computing local image statistics such as the local
1647
variance and standard deviation around the neighborhood of a pixel.
1648
1649
@param src input image
1650
@param dst output image of the same size and type as src
1651
@param ddepth the output image depth (-1 to use src.depth())
1652
@param ksize kernel size
1653
@param anchor kernel anchor point. The default value of Point(-1, -1) denotes that the anchor is at the kernel
1654
center.
1655
@param normalize flag, specifying whether the kernel is to be normalized by it's area or not.
1656
@param borderType border mode used to extrapolate pixels outside of the image, see #BorderTypes. #BORDER_WRAP is not supported.
1657
@sa boxFilter
1658
*/
1659
CV_EXPORTS_W void sqrBoxFilter( InputArray src, OutputArray dst, int ddepth,
1660
                                Size ksize, Point anchor = Point(-1, -1),
1661
                                bool normalize = true,
1662
                                int borderType = BORDER_DEFAULT );
1663
1664
/** @brief Blurs an image using the normalized box filter.
1665
1666
The function smooths an image using the kernel:
1667
1668
\f[\texttt{K} =  \frac{1}{\texttt{ksize.width*ksize.height}} \begin{bmatrix} 1 & 1 & 1 &  \cdots & 1 & 1  \\ 1 & 1 & 1 &  \cdots & 1 & 1  \\ \hdotsfor{6} \\ 1 & 1 & 1 &  \cdots & 1 & 1  \\ \end{bmatrix}\f]
1669
1670
The call `blur(src, dst, ksize, anchor, borderType)` is equivalent to `boxFilter(src, dst, src.type(), ksize,
1671
anchor, true, borderType)`.
1672
1673
@param src input image; it can have any number of channels, which are processed independently, but
1674
the depth should be CV_8U, CV_16U, CV_16S, CV_32F or CV_64F.
1675
@param dst output image of the same size and type as src.
1676
@param ksize blurring kernel size.
1677
@param anchor anchor point; default value Point(-1,-1) means that the anchor is at the kernel
1678
center.
1679
@param borderType border mode used to extrapolate pixels outside of the image, see #BorderTypes. #BORDER_WRAP is not supported.
1680
@sa  boxFilter, bilateralFilter, GaussianBlur, medianBlur
1681
 */
1682
CV_EXPORTS_W void blur( InputArray src, OutputArray dst,
1683
                        Size ksize, Point anchor = Point(-1,-1),
1684
                        int borderType = BORDER_DEFAULT );
1685
1686
/** @brief Blurs an image using the stackBlur.
1687
1688
The function applies and stackBlur to an image.
1689
stackBlur can generate similar results as Gaussian blur, and the time consumption does not increase with the increase of kernel size.
1690
It creates a kind of moving stack of colors whilst scanning through the image. Thereby it just has to add one new block of color to the right side
1691
of the stack and remove the leftmost color. The remaining colors on the topmost layer of the stack are either added on or reduced by one,
1692
depending on if they are on the right or on the left side of the stack. The only supported borderType is BORDER_REPLICATE.
1693
Original paper was proposed by Mario Klingemann, which can be found https://underdestruction.com/2004/02/25/stackblur-2004.
1694
1695
@param src input image. The number of channels can be arbitrary, but the depth should be one of
1696
CV_8U, CV_16U, CV_16S or CV_32F.
1697
@param dst output image of the same size and type as src.
1698
@param ksize stack-blurring kernel size. The ksize.width and ksize.height can differ but they both must be
1699
positive and odd.
1700
*/
1701
CV_EXPORTS_W void stackBlur(InputArray src, OutputArray dst, Size ksize);
1702
1703
/** @brief Convolves an image with the kernel.
1704
1705
The function applies an arbitrary linear filter to an image. In-place operation is supported. When
1706
the aperture is partially outside the image, the function interpolates outlier pixel values
1707
according to the specified border mode.
1708
1709
The function does actually compute correlation, not the convolution:
1710
1711
\f[\texttt{dst} (x,y) =  \sum _{ \substack{0\leq x' < \texttt{kernel.cols}\\{0\leq y' < \texttt{kernel.rows}}}}  \texttt{kernel} (x',y')* \texttt{src} (x+x'- \texttt{anchor.x} ,y+y'- \texttt{anchor.y} )\f]
1712
1713
That is, the kernel is not mirrored around the anchor point. If you need a real convolution, flip
1714
the kernel using #flip and set the new anchor to `(kernel.cols - anchor.x - 1, kernel.rows -
1715
anchor.y - 1)`.
1716
1717
The function uses the DFT-based algorithm in case of sufficiently large kernels (~`11 x 11` or
1718
larger) and the direct algorithm for small kernels.
1719
1720
@param src input image.
1721
@param dst output image of the same size and the same number of channels as src.
1722
@param ddepth desired depth of the destination image, see @ref filter_depths "combinations"
1723
@param kernel convolution kernel (or rather a correlation kernel), a single-channel floating point
1724
matrix; if you want to apply different kernels to different channels, split the image into
1725
separate color planes using split and process them individually.
1726
@param anchor anchor of the kernel that indicates the relative position of a filtered point within
1727
the kernel; the anchor should lie within the kernel; default value (-1,-1) means that the anchor
1728
is at the kernel center.
1729
@param delta optional value added to the filtered pixels before storing them in dst.
1730
@param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported.
1731
@sa  sepFilter2D, dft, matchTemplate
1732
 */
1733
CV_EXPORTS_W void filter2D( InputArray src, OutputArray dst, int ddepth,
1734
                            InputArray kernel, Point anchor = Point(-1,-1),
1735
                            double delta = 0, int borderType = BORDER_DEFAULT );
1736
1737
/** @brief Applies a separable linear filter to an image.
1738
1739
The function applies a separable linear filter to the image. That is, first, every row of src is
1740
filtered with the 1D kernel kernelX. Then, every column of the result is filtered with the 1D
1741
kernel kernelY. The final result shifted by delta is stored in dst .
1742
1743
@param src Source image.
1744
@param dst Destination image of the same size and the same number of channels as src .
1745
@param ddepth Destination image depth, see @ref filter_depths "combinations"
1746
@param kernelX Coefficients for filtering each row.
1747
@param kernelY Coefficients for filtering each column.
1748
@param anchor Anchor position within the kernel. The default value \f$(-1,-1)\f$ means that the anchor
1749
is at the kernel center.
1750
@param delta Value added to the filtered results before storing them.
1751
@param borderType Pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported.
1752
@sa  filter2D, Sobel, GaussianBlur, boxFilter, blur
1753
 */
1754
CV_EXPORTS_W void sepFilter2D( InputArray src, OutputArray dst, int ddepth,
1755
                               InputArray kernelX, InputArray kernelY,
1756
                               Point anchor = Point(-1,-1),
1757
                               double delta = 0, int borderType = BORDER_DEFAULT );
1758
1759
/** @example samples/cpp/tutorial_code/ImgTrans/Sobel_Demo.cpp
1760
Sample code using Sobel and/or Scharr OpenCV functions to make a simple Edge Detector
1761
![Sample screenshot](Sobel_Derivatives_Tutorial_Result.jpg)
1762
Check @ref tutorial_sobel_derivatives "the corresponding tutorial" for more details
1763
*/
1764
1765
/** @brief Calculates the first, second, third, or mixed image derivatives using an extended Sobel operator.
1766
1767
In all cases except one, the \f$\texttt{ksize} \times \texttt{ksize}\f$ separable kernel is used to
1768
calculate the derivative. When \f$\texttt{ksize = 1}\f$, the \f$3 \times 1\f$ or \f$1 \times 3\f$
1769
kernel is used (that is, no Gaussian smoothing is done). `ksize = 1` can only be used for the first
1770
or the second x- or y- derivatives.
1771
1772
There is also the special value `ksize = #FILTER_SCHARR (-1)` that corresponds to the \f$3\times3\f$ Scharr
1773
filter that may give more accurate results than the \f$3\times3\f$ Sobel. The Scharr aperture is
1774
1775
\f[\vecthreethree{-3}{0}{3}{-10}{0}{10}{-3}{0}{3}\f]
1776
1777
for the x-derivative, or transposed for the y-derivative.
1778
1779
The function calculates an image derivative by convolving the image with the appropriate kernel:
1780
1781
\f[\texttt{dst} =  \frac{\partial^{xorder+yorder} \texttt{src}}{\partial x^{xorder} \partial y^{yorder}}\f]
1782
1783
The Sobel operators combine Gaussian smoothing and differentiation, so the result is more or less
1784
resistant to the noise. Most often, the function is called with ( xorder = 1, yorder = 0, ksize = 3)
1785
or ( xorder = 0, yorder = 1, ksize = 3) to calculate the first x- or y- image derivative. The first
1786
case corresponds to a kernel of:
1787
1788
\f[\vecthreethree{-1}{0}{1}{-2}{0}{2}{-1}{0}{1}\f]
1789
1790
The second case corresponds to a kernel of:
1791
1792
\f[\vecthreethree{-1}{-2}{-1}{0}{0}{0}{1}{2}{1}\f]
1793
1794
@param src input image.
1795
@param dst output image of the same size and the same number of channels as src .
1796
@param ddepth output image depth, see @ref filter_depths "combinations"; in the case of
1797
    8-bit input images it will result in truncated derivatives.
1798
@param dx order of the derivative x.
1799
@param dy order of the derivative y.
1800
@param ksize size of the extended Sobel kernel; it must be 1, 3, 5, or 7.
1801
@param scale optional scale factor for the computed derivative values; by default, no scaling is
1802
applied (see #getDerivKernels for details).
1803
@param delta optional delta value that is added to the results prior to storing them in dst.
1804
@param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported.
1805
@sa  Scharr, Laplacian, sepFilter2D, filter2D, GaussianBlur, cartToPolar
1806
 */
1807
CV_EXPORTS_W void Sobel( InputArray src, OutputArray dst, int ddepth,
1808
                         int dx, int dy, int ksize = 3,
1809
                         double scale = 1, double delta = 0,
1810
                         int borderType = BORDER_DEFAULT );
1811
1812
/** @brief Calculates the first order image derivative in both x and y using a Sobel operator
1813
1814
Equivalent to calling:
1815
1816
@code
1817
Sobel( src, dx, CV_16SC1, 1, 0, 3 );
1818
Sobel( src, dy, CV_16SC1, 0, 1, 3 );
1819
@endcode
1820
1821
@param src input image.
1822
@param dx output image with first-order derivative in x.
1823
@param dy output image with first-order derivative in y.
1824
@param ksize size of Sobel kernel. It must be 3.
1825
@param borderType pixel extrapolation method, see #BorderTypes.
1826
                  Only #BORDER_DEFAULT=#BORDER_REFLECT_101 and #BORDER_REPLICATE are supported.
1827
1828
@sa Sobel
1829
 */
1830
1831
CV_EXPORTS_W void spatialGradient( InputArray src, OutputArray dx,
1832
                                   OutputArray dy, int ksize = 3,
1833
                                   int borderType = BORDER_DEFAULT );
1834
1835
/** @brief Calculates the first x- or y- image derivative using Scharr operator.
1836
1837
The function computes the first x- or y- spatial image derivative using the Scharr operator. The
1838
call
1839
1840
\f[\texttt{Scharr(src, dst, ddepth, dx, dy, scale, delta, borderType)}\f]
1841
1842
is equivalent to
1843
1844
\f[\texttt{Sobel(src, dst, ddepth, dx, dy, FILTER_SCHARR, scale, delta, borderType)} .\f]
1845
1846
@param src input image.
1847
@param dst output image of the same size and the same number of channels as src.
1848
@param ddepth output image depth, see @ref filter_depths "combinations"
1849
@param dx order of the derivative x.
1850
@param dy order of the derivative y.
1851
@param scale optional scale factor for the computed derivative values; by default, no scaling is
1852
applied (see #getDerivKernels for details).
1853
@param delta optional delta value that is added to the results prior to storing them in dst.
1854
@param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported.
1855
@sa  cartToPolar
1856
 */
1857
CV_EXPORTS_W void Scharr( InputArray src, OutputArray dst, int ddepth,
1858
                          int dx, int dy, double scale = 1, double delta = 0,
1859
                          int borderType = BORDER_DEFAULT );
1860
1861
/** @example samples/cpp/laplace.cpp
1862
An example using Laplace transformations for edge detection
1863
*/
1864
1865
/** @brief Calculates the Laplacian of an image.
1866
1867
The function calculates the Laplacian of the source image by adding up the second x and y
1868
derivatives calculated using the Sobel operator:
1869
1870
\f[\texttt{dst} =  \Delta \texttt{src} =  \frac{\partial^2 \texttt{src}}{\partial x^2} +  \frac{\partial^2 \texttt{src}}{\partial y^2}\f]
1871
1872
This is done when `ksize > 1`. When `ksize == 1`, the Laplacian is computed by filtering the image
1873
with the following \f$3 \times 3\f$ aperture:
1874
1875
\f[\vecthreethree {0}{1}{0}{1}{-4}{1}{0}{1}{0}\f]
1876
1877
@param src Source image.
1878
@param dst Destination image of the same size and the same number of channels as src .
1879
@param ddepth Desired depth of the destination image, see @ref filter_depths "combinations".
1880
@param ksize Aperture size used to compute the second-derivative filters. See #getDerivKernels for
1881
details. The size must be positive and odd.
1882
@param scale Optional scale factor for the computed Laplacian values. By default, no scaling is
1883
applied. See #getDerivKernels for details.
1884
@param delta Optional delta value that is added to the results prior to storing them in dst .
1885
@param borderType Pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported.
1886
@sa  Sobel, Scharr
1887
 */
1888
CV_EXPORTS_W void Laplacian( InputArray src, OutputArray dst, int ddepth,
1889
                             int ksize = 1, double scale = 1, double delta = 0,
1890
                             int borderType = BORDER_DEFAULT );
1891
1892
//! @} imgproc_filter
1893
1894
//! @addtogroup imgproc_feature
1895
//! @{
1896
1897
/** @example samples/cpp/edge.cpp
1898
This program demonstrates usage of the Canny edge detector
1899
1900
Check @ref tutorial_canny_detector "the corresponding tutorial" for more details
1901
*/
1902
1903
/** @brief Finds edges in an image using the Canny algorithm @cite Canny86 .
1904
1905
The function finds edges in the input image and marks them in the output map edges using the
1906
Canny algorithm. The smallest value between threshold1 and threshold2 is used for edge linking. The
1907
largest value is used to find initial segments of strong edges. See
1908
<https://en.wikipedia.org/wiki/Canny_edge_detector>
1909
1910
@param image 8-bit input image.
1911
@param edges output edge map; single channels 8-bit image, which has the same size as image .
1912
@param threshold1 first threshold for the hysteresis procedure.
1913
@param threshold2 second threshold for the hysteresis procedure.
1914
@param apertureSize aperture size for the Sobel operator.
1915
@param L2gradient a flag, indicating whether a more accurate \f$L_2\f$ norm
1916
\f$=\sqrt{(dI/dx)^2 + (dI/dy)^2}\f$ should be used to calculate the image gradient magnitude (
1917
L2gradient=true ), or whether the default \f$L_1\f$ norm \f$=|dI/dx|+|dI/dy|\f$ is enough (
1918
L2gradient=false ).
1919
 */
1920
CV_EXPORTS_W void Canny( InputArray image, OutputArray edges,
1921
                         double threshold1, double threshold2,
1922
                         int apertureSize = 3, bool L2gradient = false );
1923
1924
/** \overload
1925
1926
Finds edges in an image using the Canny algorithm with custom image gradient.
1927
1928
@param dx 16-bit x derivative of input image (CV_16SC1 or CV_16SC3).
1929
@param dy 16-bit y derivative of input image (same type as dx).
1930
@param edges output edge map; single channels 8-bit image, which has the same size as image .
1931
@param threshold1 first threshold for the hysteresis procedure.
1932
@param threshold2 second threshold for the hysteresis procedure.
1933
@param L2gradient a flag, indicating whether a more accurate \f$L_2\f$ norm
1934
\f$=\sqrt{(dI/dx)^2 + (dI/dy)^2}\f$ should be used to calculate the image gradient magnitude (
1935
L2gradient=true ), or whether the default \f$L_1\f$ norm \f$=|dI/dx|+|dI/dy|\f$ is enough (
1936
L2gradient=false ).
1937
 */
1938
CV_EXPORTS_W void Canny( InputArray dx, InputArray dy,
1939
                         OutputArray edges,
1940
                         double threshold1, double threshold2,
1941
                         bool L2gradient = false );
1942
1943
/** @brief Calculates the minimal eigenvalue of gradient matrices for corner detection.
1944
1945
The function is similar to cornerEigenValsAndVecs but it calculates and stores only the minimal
1946
eigenvalue of the covariance matrix of derivatives, that is, \f$\min(\lambda_1, \lambda_2)\f$ in terms
1947
of the formulae in the cornerEigenValsAndVecs description.
1948
1949
@param src Input single-channel 8-bit or floating-point image.
1950
@param dst Image to store the minimal eigenvalues. It has the type CV_32FC1 and the same size as
1951
src .
1952
@param blockSize Neighborhood size (see the details on #cornerEigenValsAndVecs ).
1953
@param ksize Aperture parameter for the Sobel operator.
1954
@param borderType Pixel extrapolation method. See #BorderTypes. #BORDER_WRAP is not supported.
1955
 */
1956
CV_EXPORTS_W void cornerMinEigenVal( InputArray src, OutputArray dst,
1957
                                     int blockSize, int ksize = 3,
1958
                                     int borderType = BORDER_DEFAULT );
1959
1960
/** @brief Harris corner detector.
1961
1962
The function runs the Harris corner detector on the image. Similarly to cornerMinEigenVal and
1963
cornerEigenValsAndVecs , for each pixel \f$(x, y)\f$ it calculates a \f$2\times2\f$ gradient covariance
1964
matrix \f$M^{(x,y)}\f$ over a \f$\texttt{blockSize} \times \texttt{blockSize}\f$ neighborhood. Then, it
1965
computes the following characteristic:
1966
1967
\f[\texttt{dst} (x,y) =  \mathrm{det} M^{(x,y)} - k  \cdot \left ( \mathrm{tr} M^{(x,y)} \right )^2\f]
1968
1969
Corners in the image can be found as the local maxima of this response map.
1970
1971
@param src Input single-channel 8-bit or floating-point image.
1972
@param dst Image to store the Harris detector responses. It has the type CV_32FC1 and the same
1973
size as src .
1974
@param blockSize Neighborhood size (see the details on #cornerEigenValsAndVecs ).
1975
@param ksize Aperture parameter for the Sobel operator.
1976
@param k Harris detector free parameter. See the formula above.
1977
@param borderType Pixel extrapolation method. See #BorderTypes. #BORDER_WRAP is not supported.
1978
 */
1979
CV_EXPORTS_W void cornerHarris( InputArray src, OutputArray dst, int blockSize,
1980
                                int ksize, double k,
1981
                                int borderType = BORDER_DEFAULT );
1982
1983
/** @brief Calculates eigenvalues and eigenvectors of image blocks for corner detection.
1984
1985
For every pixel \f$p\f$ , the function cornerEigenValsAndVecs considers a blockSize \f$\times\f$ blockSize
1986
neighborhood \f$S(p)\f$ . It calculates the covariation matrix of derivatives over the neighborhood as:
1987
1988
\f[M =  \begin{bmatrix} \sum _{S(p)}(dI/dx)^2 &  \sum _{S(p)}dI/dx dI/dy  \\ \sum _{S(p)}dI/dx dI/dy &  \sum _{S(p)}(dI/dy)^2 \end{bmatrix}\f]
1989
1990
where the derivatives are computed using the Sobel operator.
1991
1992
After that, it finds eigenvectors and eigenvalues of \f$M\f$ and stores them in the destination image as
1993
\f$(\lambda_1, \lambda_2, x_1, y_1, x_2, y_2)\f$ where
1994
1995
-   \f$\lambda_1, \lambda_2\f$ are the non-sorted eigenvalues of \f$M\f$
1996
-   \f$x_1, y_1\f$ are the eigenvectors corresponding to \f$\lambda_1\f$
1997
-   \f$x_2, y_2\f$ are the eigenvectors corresponding to \f$\lambda_2\f$
1998
1999
The output of the function can be used for robust edge or corner detection.
2000
2001
@param src Input single-channel 8-bit or floating-point image.
2002
@param dst Image to store the results. It has the same size as src and the type CV_32FC(6) .
2003
@param blockSize Neighborhood size (see details below).
2004
@param ksize Aperture parameter for the Sobel operator.
2005
@param borderType Pixel extrapolation method. See #BorderTypes. #BORDER_WRAP is not supported.
2006
2007
@sa  cornerMinEigenVal, cornerHarris, preCornerDetect
2008
 */
2009
CV_EXPORTS_W void cornerEigenValsAndVecs( InputArray src, OutputArray dst,
2010
                                          int blockSize, int ksize,
2011
                                          int borderType = BORDER_DEFAULT );
2012
2013
/** @brief Calculates a feature map for corner detection.
2014
2015
The function calculates the complex spatial derivative-based function of the source image
2016
2017
\f[\texttt{dst} = (D_x  \texttt{src} )^2  \cdot D_{yy}  \texttt{src} + (D_y  \texttt{src} )^2  \cdot D_{xx}  \texttt{src} - 2 D_x  \texttt{src} \cdot D_y  \texttt{src} \cdot D_{xy}  \texttt{src}\f]
2018
2019
where \f$D_x\f$,\f$D_y\f$ are the first image derivatives, \f$D_{xx}\f$,\f$D_{yy}\f$ are the second image
2020
derivatives, and \f$D_{xy}\f$ is the mixed derivative.
2021
2022
The corners can be found as local maximums of the functions, as shown below:
2023
@code
2024
    Mat corners, dilated_corners;
2025
    preCornerDetect(image, corners, 3);
2026
    // dilation with 3x3 rectangular structuring element
2027
    dilate(corners, dilated_corners, Mat(), 1);
2028
    Mat corner_mask = corners == dilated_corners;
2029
@endcode
2030
2031
@param src Source single-channel 8-bit of floating-point image.
2032
@param dst Output image that has the type CV_32F and the same size as src .
2033
@param ksize %Aperture size of the Sobel .
2034
@param borderType Pixel extrapolation method. See #BorderTypes. #BORDER_WRAP is not supported.
2035
 */
2036
CV_EXPORTS_W void preCornerDetect( InputArray src, OutputArray dst, int ksize,
2037
                                   int borderType = BORDER_DEFAULT );
2038
2039
/** @brief Refines the corner locations.
2040
2041
The function iterates to find the sub-pixel accurate location of corners or radial saddle
2042
points as described in @cite forstner1987fast, and as shown on the figure below.
2043
2044
![image](pics/cornersubpix.png)
2045
2046
Sub-pixel accurate corner locator is based on the observation that every vector from the center \f$q\f$
2047
to a point \f$p\f$ located within a neighborhood of \f$q\f$ is orthogonal to the image gradient at \f$p\f$
2048
subject to image and measurement noise. Consider the expression:
2049
2050
\f[\epsilon _i = {DI_{p_i}}^T  \cdot (q - p_i)\f]
2051
2052
where \f${DI_{p_i}}\f$ is an image gradient at one of the points \f$p_i\f$ in a neighborhood of \f$q\f$ . The
2053
value of \f$q\f$ is to be found so that \f$\epsilon_i\f$ is minimized. A system of equations may be set up
2054
with \f$\epsilon_i\f$ set to zero:
2055
2056
\f[\sum _i(DI_{p_i}  \cdot {DI_{p_i}}^T) \cdot q -  \sum _i(DI_{p_i}  \cdot {DI_{p_i}}^T  \cdot p_i)\f]
2057
2058
where the gradients are summed within a neighborhood ("search window") of \f$q\f$ . Calling the first
2059
gradient term \f$G\f$ and the second gradient term \f$b\f$ gives:
2060
2061
\f[q = G^{-1}  \cdot b\f]
2062
2063
The algorithm sets the center of the neighborhood window at this new center \f$q\f$ and then iterates
2064
until the center stays within a set threshold.
2065
2066
@param image Input single-channel, 8-bit or float image.
2067
@param corners Initial coordinates of the input corners and refined coordinates provided for
2068
output.
2069
@param winSize Half of the side length of the search window. For example, if winSize=Size(5,5) ,
2070
then a \f$(5*2+1) \times (5*2+1) = 11 \times 11\f$ search window is used.
2071
@param zeroZone Half of the size of the dead region in the middle of the search zone over which
2072
the summation in the formula below is not done. It is used sometimes to avoid possible
2073
singularities of the autocorrelation matrix. The value of (-1,-1) indicates that there is no such
2074
a size.
2075
@param criteria Criteria for termination of the iterative process of corner refinement. That is,
2076
the process of corner position refinement stops either after criteria.maxCount iterations or when
2077
the corner position moves by less than criteria.epsilon on some iteration.
2078
 */
2079
CV_EXPORTS_W void cornerSubPix( InputArray image, InputOutputArray corners,
2080
                                Size winSize, Size zeroZone,
2081
                                TermCriteria criteria );
2082
2083
/** @brief Determines strong corners on an image.
2084
2085
The function finds the most prominent corners in the image or in the specified image region, as
2086
described in @cite Shi94
2087
2088
-   Function calculates the corner quality measure at every source image pixel using the
2089
    #cornerMinEigenVal or #cornerHarris .
2090
-   Function performs a non-maximum suppression (the local maximums in *3 x 3* neighborhood are
2091
    retained).
2092
-   The corners with the minimal eigenvalue less than
2093
    \f$\texttt{qualityLevel} \cdot \max_{x,y} qualityMeasureMap(x,y)\f$ are rejected.
2094
-   The remaining corners are sorted by the quality measure in the descending order.
2095
-   Function throws away each corner for which there is a stronger corner at a distance less than
2096
    maxDistance.
2097
2098
The function can be used to initialize a point-based tracker of an object.
2099
2100
@note If the function is called with different values A and B of the parameter qualityLevel , and
2101
A \> B, the vector of returned corners with qualityLevel=A will be the prefix of the output vector
2102
with qualityLevel=B .
2103
2104
@param image Input 8-bit or floating-point 32-bit, single-channel image.
2105
@param corners Output vector of detected corners.
2106
@param maxCorners Maximum number of corners to return. If there are more corners than are found,
2107
the strongest of them is returned. `maxCorners <= 0` implies that no limit on the maximum is set
2108
and all detected corners are returned.
2109
@param qualityLevel Parameter characterizing the minimal accepted quality of image corners. The
2110
parameter value is multiplied by the best corner quality measure, which is the minimal eigenvalue
2111
(see #cornerMinEigenVal ) or the Harris function response (see #cornerHarris ). The corners with the
2112
quality measure less than the product are rejected. For example, if the best corner has the
2113
quality measure = 1500, and the qualityLevel=0.01 , then all the corners with the quality measure
2114
less than 15 are rejected.
2115
@param minDistance Minimum possible Euclidean distance between the returned corners.
2116
@param mask Optional region of interest. If the image is not empty (it needs to have the type
2117
CV_8UC1 and the same size as image ), it specifies the region in which the corners are detected.
2118
@param blockSize Size of an average block for computing a derivative covariation matrix over each
2119
pixel neighborhood. See cornerEigenValsAndVecs .
2120
@param useHarrisDetector Parameter indicating whether to use a Harris detector (see #cornerHarris)
2121
or #cornerMinEigenVal.
2122
@param k Free parameter of the Harris detector.
2123
2124
@sa  cornerMinEigenVal, cornerHarris, calcOpticalFlowPyrLK, estimateRigidTransform,
2125
 */
2126
2127
CV_EXPORTS_W void goodFeaturesToTrack( InputArray image, OutputArray corners,
2128
                                     int maxCorners, double qualityLevel, double minDistance,
2129
                                     InputArray mask = noArray(), int blockSize = 3,
2130
                                     bool useHarrisDetector = false, double k = 0.04 );
2131
2132
CV_EXPORTS_W void goodFeaturesToTrack( InputArray image, OutputArray corners,
2133
                                     int maxCorners, double qualityLevel, double minDistance,
2134
                                     InputArray mask, int blockSize,
2135
                                     int gradientSize, bool useHarrisDetector = false,
2136
                                     double k = 0.04 );
2137
2138
/** @brief Same as above, but returns also quality measure of the detected corners.
2139
2140
@param image Input 8-bit or floating-point 32-bit, single-channel image.
2141
@param corners Output vector of detected corners.
2142
@param maxCorners Maximum number of corners to return. If there are more corners than are found,
2143
the strongest of them is returned. `maxCorners <= 0` implies that no limit on the maximum is set
2144
and all detected corners are returned.
2145
@param qualityLevel Parameter characterizing the minimal accepted quality of image corners. The
2146
parameter value is multiplied by the best corner quality measure, which is the minimal eigenvalue
2147
(see #cornerMinEigenVal ) or the Harris function response (see #cornerHarris ). The corners with the
2148
quality measure less than the product are rejected. For example, if the best corner has the
2149
quality measure = 1500, and the qualityLevel=0.01 , then all the corners with the quality measure
2150
less than 15 are rejected.
2151
@param minDistance Minimum possible Euclidean distance between the returned corners.
2152
@param mask Region of interest. If the image is not empty (it needs to have the type
2153
CV_8UC1 and the same size as image ), it specifies the region in which the corners are detected.
2154
@param cornersQuality Output vector of quality measure of the detected corners.
2155
@param blockSize Size of an average block for computing a derivative covariation matrix over each
2156
pixel neighborhood. See cornerEigenValsAndVecs .
2157
@param gradientSize Aperture parameter for the Sobel operator used for derivatives computation.
2158
See cornerEigenValsAndVecs .
2159
@param useHarrisDetector Parameter indicating whether to use a Harris detector (see #cornerHarris)
2160
or #cornerMinEigenVal.
2161
@param k Free parameter of the Harris detector.
2162
 */
2163
CV_EXPORTS CV_WRAP_AS(goodFeaturesToTrackWithQuality) void goodFeaturesToTrack(
2164
        InputArray image, OutputArray corners,
2165
        int maxCorners, double qualityLevel, double minDistance,
2166
        InputArray mask, OutputArray cornersQuality, int blockSize = 3,
2167
        int gradientSize = 3, bool useHarrisDetector = false, double k = 0.04);
2168
2169
/** @example samples/cpp/tutorial_code/ImgTrans/houghlines.cpp
2170
An example using the Hough line detector
2171
![Sample input image](Hough_Lines_Tutorial_Original_Image.jpg) ![Output image](Hough_Lines_Tutorial_Result.jpg)
2172
*/
2173
2174
/** @brief Finds lines in a binary image using the standard Hough transform.
2175
2176
The function implements the standard or standard multi-scale Hough transform algorithm for line
2177
detection. See <https://homepages.inf.ed.ac.uk/rbf/HIPR2/hough.htm> for a good explanation of Hough
2178
transform.
2179
2180
@param image 8-bit, single-channel binary source image. The image may be modified by the function.
2181
@param lines Output vector of lines. Each line is represented by a 2 or 3 element vector
2182
\f$(\rho, \theta)\f$ or \f$(\rho, \theta, \textrm{votes})\f$, where \f$\rho\f$ is the distance from
2183
the coordinate origin \f$(0,0)\f$ (top-left corner of the image), \f$\theta\f$ is the line rotation
2184
angle in radians ( \f$0 \sim \textrm{vertical line}, \pi/2 \sim \textrm{horizontal line}\f$ ), and
2185
\f$\textrm{votes}\f$ is the value of accumulator.
2186
@param rho Distance resolution of the accumulator in pixels.
2187
@param theta Angle resolution of the accumulator in radians.
2188
@param threshold %Accumulator threshold parameter. Only those lines are returned that get enough
2189
votes ( \f$>\texttt{threshold}\f$ ).
2190
@param srn For the multi-scale Hough transform, it is a divisor for the distance resolution rho.
2191
The coarse accumulator distance resolution is rho and the accurate accumulator resolution is
2192
rho/srn. If both srn=0 and stn=0, the classical Hough transform is used. Otherwise, both these
2193
parameters should be positive.
2194
@param stn For the multi-scale Hough transform, it is a divisor for the distance resolution theta.
2195
@param min_theta For standard and multi-scale Hough transform, minimum angle to check for lines.
2196
Must fall between 0 and max_theta.
2197
@param max_theta For standard and multi-scale Hough transform, an upper bound for the angle.
2198
Must fall between min_theta and CV_PI. The actual maximum angle in the accumulator may be slightly
2199
less than max_theta, depending on the parameters min_theta and theta.
2200
@param use_edgeval True if you want to use weighted Hough transform.
2201
 */
2202
CV_EXPORTS_W void HoughLines( InputArray image, OutputArray lines,
2203
                              double rho, double theta, int threshold,
2204
                              double srn = 0, double stn = 0,
2205
                              double min_theta = 0, double max_theta = CV_PI,
2206
                              bool use_edgeval = false );
2207
2208
/** @brief Finds line segments in a binary image using the probabilistic Hough transform.
2209
2210
The function implements the probabilistic Hough transform algorithm for line detection, described
2211
in @cite Matas00
2212
2213
See the line detection example below:
2214
@include snippets/imgproc_HoughLinesP.cpp
2215
This is a sample picture the function parameters have been tuned for:
2216
2217
![image](pics/building.jpg)
2218
2219
And this is the output of the above program in case of the probabilistic Hough transform:
2220
2221
![image](pics/houghp.png)
2222
2223
@param image 8-bit, single-channel binary source image. The image may be modified by the function.
2224
@param lines Output vector of lines. Each line is represented by a 4-element vector
2225
\f$(x_1, y_1, x_2, y_2)\f$ , where \f$(x_1,y_1)\f$ and \f$(x_2, y_2)\f$ are the ending points of each detected
2226
line segment.
2227
@param rho Distance resolution of the accumulator in pixels.
2228
@param theta Angle resolution of the accumulator in radians.
2229
@param threshold %Accumulator threshold parameter. Only those lines are returned that get enough
2230
votes ( \f$>\texttt{threshold}\f$ ).
2231
@param minLineLength Minimum line length. Line segments shorter than that are rejected.
2232
@param maxLineGap Maximum allowed gap between points on the same line to link them.
2233
2234
@sa LineSegmentDetector
2235
 */
2236
CV_EXPORTS_W void HoughLinesP( InputArray image, OutputArray lines,
2237
                               double rho, double theta, int threshold,
2238
                               double minLineLength = 0, double maxLineGap = 0 );
2239
2240
/** @brief Finds lines in a set of points using the standard Hough transform.
2241
2242
The function finds lines in a set of points using a modification of the Hough transform.
2243
@include snippets/imgproc_HoughLinesPointSet.cpp
2244
@param point Input vector of points. Each vector must be encoded as a Point vector \f$(x,y)\f$. Type must be CV_32FC2 or CV_32SC2.
2245
@param lines Output vector of found lines. Each vector is encoded as a vector<Vec3d> \f$(votes, rho, theta)\f$.
2246
The larger the value of 'votes', the higher the reliability of the Hough line.
2247
@param lines_max Max count of Hough lines.
2248
@param threshold %Accumulator threshold parameter. Only those lines are returned that get enough
2249
votes ( \f$>\texttt{threshold}\f$ ).
2250
@param min_rho Minimum value for \f$\rho\f$ for the accumulator (Note: \f$\rho\f$ can be negative. The absolute value \f$|\rho|\f$ is the distance of a line to the origin.).
2251
@param max_rho Maximum value for \f$\rho\f$ for the accumulator.
2252
@param rho_step Distance resolution of the accumulator.
2253
@param min_theta Minimum angle value of the accumulator in radians.
2254
@param max_theta Upper bound for the angle value of the accumulator in radians. The actual maximum
2255
angle may be slightly less than max_theta, depending on the parameters min_theta and theta_step.
2256
@param theta_step Angle resolution of the accumulator in radians.
2257
 */
2258
CV_EXPORTS_W void HoughLinesPointSet( InputArray point, OutputArray lines, int lines_max, int threshold,
2259
                                      double min_rho, double max_rho, double rho_step,
2260
                                      double min_theta, double max_theta, double theta_step );
2261
2262
/** @example samples/cpp/tutorial_code/ImgTrans/houghcircles.cpp
2263
An example using the Hough circle detector
2264
*/
2265
2266
/** @brief Finds circles in a grayscale image using the Hough transform.
2267
2268
The function finds circles in a grayscale image using a modification of the Hough transform.
2269
2270
Example: :
2271
@include snippets/imgproc_HoughLinesCircles.cpp
2272
2273
@note Usually the function detects the centers of circles well. However, it may fail to find correct
2274
radii. You can assist to the function by specifying the radius range ( minRadius and maxRadius ) if
2275
you know it. Or, in the case of #HOUGH_GRADIENT method you may set maxRadius to a negative number
2276
to return centers only without radius search, and find the correct radius using an additional procedure.
2277
2278
It also helps to smooth image a bit unless it's already soft. For example,
2279
GaussianBlur() with 7x7 kernel and 1.5x1.5 sigma or similar blurring may help.
2280
2281
@param image 8-bit, single-channel, grayscale input image.
2282
@param circles Output vector of found circles. Each vector is encoded as  3 or 4 element
2283
floating-point vector \f$(x, y, radius)\f$ or \f$(x, y, radius, votes)\f$ .
2284
@param method Detection method, see #HoughModes. The available methods are #HOUGH_GRADIENT and #HOUGH_GRADIENT_ALT.
2285
@param dp Inverse ratio of the accumulator resolution to the image resolution. For example, if
2286
dp=1 , the accumulator has the same resolution as the input image. If dp=2 , the accumulator has
2287
half as big width and height. For #HOUGH_GRADIENT_ALT the recommended value is dp=1.5,
2288
unless some small very circles need to be detected.
2289
@param minDist Minimum distance between the centers of the detected circles. If the parameter is
2290
too small, multiple neighbor circles may be falsely detected in addition to a true one. If it is
2291
too large, some circles may be missed.
2292
@param param1 First method-specific parameter. In case of #HOUGH_GRADIENT and #HOUGH_GRADIENT_ALT,
2293
it is the higher threshold of the two passed to the Canny edge detector (the lower one is twice smaller).
2294
Note that #HOUGH_GRADIENT_ALT uses #Scharr algorithm to compute image derivatives, so the threshold value
2295
should normally be higher, such as 300 or normally exposed and contrasty images.
2296
@param param2 Second method-specific parameter. In case of #HOUGH_GRADIENT, it is the
2297
accumulator threshold for the circle centers at the detection stage. The smaller it is, the more
2298
false circles may be detected. Circles, corresponding to the larger accumulator values, will be
2299
returned first. In the case of #HOUGH_GRADIENT_ALT algorithm, this is the circle "perfectness" measure.
2300
The closer it to 1, the better shaped circles algorithm selects. In most cases 0.9 should be fine.
2301
If you want get better detection of small circles, you may decrease it to 0.85, 0.8 or even less.
2302
But then also try to limit the search range [minRadius, maxRadius] to avoid many false circles.
2303
@param minRadius Minimum circle radius.
2304
@param maxRadius Maximum circle radius. If <= 0, uses the maximum image dimension. If < 0, #HOUGH_GRADIENT returns
2305
centers without finding the radius. #HOUGH_GRADIENT_ALT always computes circle radiuses.
2306
2307
@sa fitEllipse, minEnclosingCircle
2308
 */
2309
CV_EXPORTS_W void HoughCircles( InputArray image, OutputArray circles,
2310
                               int method, double dp, double minDist,
2311
                               double param1 = 100, double param2 = 100,
2312
                               int minRadius = 0, int maxRadius = 0 );
2313
2314
//! @} imgproc_feature
2315
2316
//! @addtogroup imgproc_filter
2317
//! @{
2318
2319
/** @example samples/cpp/tutorial_code/ImgProc/Morphology_2.cpp
2320
Advanced morphology Transformations sample code
2321
![Sample screenshot](Morphology_2_Tutorial_Result.jpg)
2322
Check @ref tutorial_opening_closing_hats "the corresponding tutorial" for more details
2323
*/
2324
2325
/** @brief Erodes an image by using a specific structuring element.
2326
2327
The function erodes the source image using the specified structuring element that determines the
2328
shape of a pixel neighborhood over which the minimum is taken:
2329
2330
\f[\texttt{dst} (x,y) =  \min _{(x',y'):  \, \texttt{kernel} (x',y') \ne0 } \texttt{src} (x+x',y+y')\f]
2331
2332
The function supports the in-place mode. Erosion can be applied several ( iterations ) times. In
2333
case of multi-channel images, each channel is processed independently.
2334
2335
@param src input image; the number of channels can be arbitrary, but the depth should be one of
2336
CV_8U, CV_16U, CV_16S, CV_32F or CV_64F.
2337
@param dst output image of the same size and type as src.
2338
@param kernel structuring element used for erosion; if `kernel=Mat()`, a `3 x 3` rectangular
2339
structuring element is used. Kernel can be created using #getStructuringElement.
2340
@param anchor position of the anchor within the element; default value (-1, -1) means that the
2341
anchor is at the element center.
2342
@param iterations number of times erosion is applied.
2343
@param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported.
2344
@param borderValue border value in case of a constant border
2345
@sa  dilate, morphologyEx, getStructuringElement
2346
 */
2347
CV_EXPORTS_W void erode( InputArray src, OutputArray dst, InputArray kernel,
2348
                         Point anchor = Point(-1,-1), int iterations = 1,
2349
                         int borderType = BORDER_CONSTANT,
2350
                         const Scalar& borderValue = morphologyDefaultBorderValue() );
2351
2352
/** @example samples/cpp/tutorial_code/ImgProc/Morphology_1.cpp
2353
Erosion and Dilation sample code
2354
![Sample Screenshot-Erosion](Morphology_1_Tutorial_Erosion_Result.jpg)![Sample Screenshot-Dilation](Morphology_1_Tutorial_Dilation_Result.jpg)
2355
Check @ref tutorial_erosion_dilatation "the corresponding tutorial" for more details
2356
*/
2357
2358
/** @brief Dilates an image by using a specific structuring element.
2359
2360
The function dilates the source image using the specified structuring element that determines the
2361
shape of a pixel neighborhood over which the maximum is taken:
2362
\f[\texttt{dst} (x,y) =  \max _{(x',y'):  \, \texttt{kernel} (x',y') \ne0 } \texttt{src} (x+x',y+y')\f]
2363
2364
The function supports the in-place mode. Dilation can be applied several ( iterations ) times. In
2365
case of multi-channel images, each channel is processed independently.
2366
2367
@param src input image; the number of channels can be arbitrary, but the depth should be one of
2368
CV_8U, CV_16U, CV_16S, CV_32F or CV_64F.
2369
@param dst output image of the same size and type as src.
2370
@param kernel structuring element used for dilation; if `kernel=Mat()`, a `3 x 3` rectangular
2371
structuring element is used. Kernel can be created using #getStructuringElement
2372
@param anchor position of the anchor within the element; default value (-1, -1) means that the
2373
anchor is at the element center.
2374
@param iterations number of times dilation is applied.
2375
@param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported.
2376
@param borderValue border value in case of a constant border
2377
@sa  erode, morphologyEx, getStructuringElement
2378
 */
2379
CV_EXPORTS_W void dilate( InputArray src, OutputArray dst, InputArray kernel,
2380
                          Point anchor = Point(-1,-1), int iterations = 1,
2381
                          int borderType = BORDER_CONSTANT,
2382
                          const Scalar& borderValue = morphologyDefaultBorderValue() );
2383
2384
/** @brief Performs advanced morphological transformations.
2385
2386
The function cv::morphologyEx can perform advanced morphological transformations using an erosion and dilation as
2387
basic operations.
2388
2389
Any of the operations can be done in-place. In case of multi-channel images, each channel is
2390
processed independently.
2391
2392
@param src Source image. The number of channels can be arbitrary. The depth should be one of
2393
CV_8U, CV_16U, CV_16S, CV_32F or CV_64F.
2394
@param dst Destination image of the same size and type as source image.
2395
@param op Type of a morphological operation, see #MorphTypes
2396
@param kernel Structuring element. It can be created using #getStructuringElement.
2397
@param anchor Anchor position with the kernel. Negative values mean that the anchor is at the
2398
kernel center.
2399
@param iterations Number of times erosion and dilation are applied.
2400
@param borderType Pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported.
2401
@param borderValue Border value in case of a constant border. The default value has a special
2402
meaning.
2403
@sa  dilate, erode, getStructuringElement
2404
@note The number of iterations is the number of times erosion or dilatation operation will be applied.
2405
For instance, an opening operation (#MORPH_OPEN) with two iterations is equivalent to apply
2406
successively: erode -> erode -> dilate -> dilate (and not erode -> dilate -> erode -> dilate).
2407
 */
2408
CV_EXPORTS_W void morphologyEx( InputArray src, OutputArray dst,
2409
                                int op, InputArray kernel,
2410
                                Point anchor = Point(-1,-1), int iterations = 1,
2411
                                int borderType = BORDER_CONSTANT,
2412
                                const Scalar& borderValue = morphologyDefaultBorderValue() );
2413
2414
//! @} imgproc_filter
2415
2416
//! @addtogroup imgproc_transform
2417
//! @{
2418
2419
/** @brief Resizes an image.
2420
2421
The function resize resizes the image src down to or up to the specified size. Note that the
2422
initial dst type or size are not taken into account. Instead, the size and type are derived from
2423
the `src`,`dsize`,`fx`, and `fy`. If you want to resize src so that it fits the pre-created dst,
2424
you may call the function as follows:
2425
@code
2426
    // explicitly specify dsize=dst.size(); fx and fy will be computed from that.
2427
    resize(src, dst, dst.size(), 0, 0, interpolation);
2428
@endcode
2429
If you want to decimate the image by factor of 2 in each direction, you can call the function this
2430
way:
2431
@code
2432
    // specify fx and fy and let the function compute the destination image size.
2433
    resize(src, dst, Size(), 0.5, 0.5, interpolation);
2434
@endcode
2435
To shrink an image, it will generally look best with #INTER_AREA interpolation, whereas to
2436
enlarge an image, it will generally look best with #INTER_CUBIC (slow) or #INTER_LINEAR
2437
(faster but still looks OK).
2438
2439
@param src input image.
2440
@param dst output image; it has the size dsize (when it is non-zero) or the size computed from
2441
src.size(), fx, and fy; the type of dst is the same as of src.
2442
@param dsize output image size; if it equals zero (`None` in Python), it is computed as:
2443
 \f[\texttt{dsize = Size(round(fx*src.cols), round(fy*src.rows))}\f]
2444
 Either dsize or both fx and fy must be non-zero.
2445
@param fx scale factor along the horizontal axis; when it equals 0, it is computed as
2446
\f[\texttt{(double)dsize.width/src.cols}\f]
2447
@param fy scale factor along the vertical axis; when it equals 0, it is computed as
2448
\f[\texttt{(double)dsize.height/src.rows}\f]
2449
@param interpolation interpolation method, see #InterpolationFlags
2450
2451
@sa  warpAffine, warpPerspective, remap
2452
 */
2453
CV_EXPORTS_W void resize( InputArray src, OutputArray dst,
2454
                          Size dsize, double fx = 0, double fy = 0,
2455
                          int interpolation = INTER_LINEAR );
2456
2457
/** @brief Applies an affine transformation to an image.
2458
2459
The function warpAffine transforms the source image using the specified matrix:
2460
2461
\f[\texttt{dst} (x,y) =  \texttt{src} ( \texttt{M} _{11} x +  \texttt{M} _{12} y +  \texttt{M} _{13}, \texttt{M} _{21} x +  \texttt{M} _{22} y +  \texttt{M} _{23})\f]
2462
2463
when the flag #WARP_INVERSE_MAP is set. Otherwise, the transformation is first inverted
2464
with #invertAffineTransform and then put in the formula above instead of M. The function cannot
2465
operate in-place.
2466
2467
@param src input image.
2468
@param dst output image that has the size dsize and the same type as src .
2469
@param M \f$2\times 3\f$ transformation matrix.
2470
@param dsize size of the output image.
2471
@param flags combination of interpolation methods (see #InterpolationFlags) and the optional
2472
flag #WARP_INVERSE_MAP that means that M is the inverse transformation (
2473
\f$\texttt{dst}\rightarrow\texttt{src}\f$ ).
2474
@param borderMode pixel extrapolation method (see #BorderTypes); when
2475
borderMode=#BORDER_TRANSPARENT, it means that the pixels in the destination image corresponding to
2476
the "outliers" in the source image are not modified by the function.
2477
@param borderValue value used in case of a constant border; by default, it is 0.
2478
2479
@sa  warpPerspective, resize, remap, getRectSubPix, transform
2480
 */
2481
CV_EXPORTS_W void warpAffine( InputArray src, OutputArray dst,
2482
                              InputArray M, Size dsize,
2483
                              int flags = INTER_LINEAR,
2484
                              int borderMode = BORDER_CONSTANT,
2485
                              const Scalar& borderValue = Scalar());
2486
2487
/** @example samples/cpp/warpPerspective_demo.cpp
2488
An example program shows using cv::getPerspectiveTransform and cv::warpPerspective for image warping
2489
*/
2490
2491
/** @brief Applies a perspective transformation to an image.
2492
2493
The function warpPerspective transforms the source image using the specified matrix:
2494
2495
\f[\texttt{dst} (x,y) =  \texttt{src} \left ( \frac{M_{11} x + M_{12} y + M_{13}}{M_{31} x + M_{32} y + M_{33}} ,
2496
     \frac{M_{21} x + M_{22} y + M_{23}}{M_{31} x + M_{32} y + M_{33}} \right )\f]
2497
2498
when the flag #WARP_INVERSE_MAP is set. Otherwise, the transformation is first inverted with invert
2499
and then put in the formula above instead of M. The function cannot operate in-place.
2500
2501
@param src input image.
2502
@param dst output image that has the size dsize and the same type as src .
2503
@param M \f$3\times 3\f$ transformation matrix.
2504
@param dsize size of the output image.
2505
@param flags combination of interpolation methods (#INTER_LINEAR or #INTER_NEAREST) and the
2506
optional flag #WARP_INVERSE_MAP, that sets M as the inverse transformation (
2507
\f$\texttt{dst}\rightarrow\texttt{src}\f$ ).
2508
@param borderMode pixel extrapolation method (#BORDER_CONSTANT or #BORDER_REPLICATE).
2509
@param borderValue value used in case of a constant border; by default, it equals 0.
2510
2511
@sa  warpAffine, resize, remap, getRectSubPix, perspectiveTransform
2512
 */
2513
CV_EXPORTS_W void warpPerspective( InputArray src, OutputArray dst,
2514
                                   InputArray M, Size dsize,
2515
                                   int flags = INTER_LINEAR,
2516
                                   int borderMode = BORDER_CONSTANT,
2517
                                   const Scalar& borderValue = Scalar());
2518
2519
/** @brief Applies a generic geometrical transformation to an image.
2520
2521
The function remap transforms the source image using the specified map:
2522
2523
\f[\texttt{dst} (x,y) =  \texttt{src} (map_x(x,y),map_y(x,y))\f]
2524
2525
with the WARP_RELATIVE_MAP flag :
2526
2527
\f[\texttt{dst} (x,y) =  \texttt{src} (x+map_x(x,y),y+map_y(x,y))\f]
2528
2529
where values of pixels with non-integer coordinates are computed using one of available
2530
interpolation methods. \f$map_x\f$ and \f$map_y\f$ can be encoded as separate floating-point maps
2531
in \f$map_1\f$ and \f$map_2\f$ respectively, or interleaved floating-point maps of \f$(x,y)\f$ in
2532
\f$map_1\f$, or fixed-point maps created by using #convertMaps. Fixed-point maps
2533
use a more compact representation, which can reduce memory bandwidth and benefit
2534
repeated remap calls that reuse the same map. Performance gains vary by hardware
2535
and are typically modest; measure before converting. In the converted case,
2536
\f$map_1\f$ contains pairs (cvFloor(x),
2537
cvFloor(y)) and \f$map_2\f$ contains indices in a table of interpolation coefficients.
2538
2539
This function cannot operate in-place.
2540
2541
@param src Source image.
2542
@param dst Destination image. It has the same size as map1 and the same type as src .
2543
@param map1 The first map of either (x,y) points or just x values having the type CV_16SC2 ,
2544
CV_32FC1, or CV_32FC2. See #convertMaps for details on converting a floating point
2545
representation to fixed-point.
2546
@param map2 The second map of y values having the type CV_16UC1, CV_32FC1, or none (empty map
2547
if map1 is (x,y) points), respectively.
2548
@param interpolation Interpolation method (see #InterpolationFlags). The methods #INTER_AREA
2549
#INTER_LINEAR_EXACT and #INTER_NEAREST_EXACT are not supported by this function.
2550
The extra flag WARP_RELATIVE_MAP can be ORed to the interpolation method
2551
(e.g. INTER_LINEAR | WARP_RELATIVE_MAP)
2552
@param borderMode Pixel extrapolation method (see #BorderTypes). When
2553
borderMode=#BORDER_TRANSPARENT, it means that the pixels in the destination image that
2554
corresponds to the "outliers" in the source image are not modified by the function.
2555
@param borderValue Value used in case of a constant border. By default, it is 0.
2556
@note
2557
Due to current implementation limitations the size of an input and output images should be less than 32767x32767.
2558
 */
2559
CV_EXPORTS_W void remap( InputArray src, OutputArray dst,
2560
                         InputArray map1, InputArray map2,
2561
                         int interpolation, int borderMode = BORDER_CONSTANT,
2562
                         const Scalar& borderValue = Scalar());
2563
2564
/** @brief Converts image transformation maps from one representation to another.
2565
2566
The function converts a pair of maps for remap from one representation to another. The following
2567
options ( (map1.type(), map2.type()) \f$\rightarrow\f$ (dstmap1.type(), dstmap2.type()) ) are
2568
supported:
2569
2570
- \f$\texttt{(CV_32FC1, CV_32FC1)} \rightarrow \texttt{(CV_16SC2, CV_16UC1)}\f$. This is the
2571
most frequently used conversion operation, in which the original floating-point maps (see #remap)
2572
are converted to a more compact and much faster fixed-point representation. The first output array
2573
contains the rounded coordinates and the second array (created only when nninterpolation=false )
2574
contains indices in the interpolation tables.
2575
2576
- \f$\texttt{(CV_32FC2)} \rightarrow \texttt{(CV_16SC2, CV_16UC1)}\f$. The same as above but
2577
the original maps are stored in one 2-channel matrix.
2578
2579
- Reverse conversion. Obviously, the reconstructed floating-point maps will not be exactly the same
2580
as the originals.
2581
2582
@param map1 The first input map of type CV_16SC2, CV_32FC1, or CV_32FC2 .
2583
@param map2 The second input map of type CV_16UC1, CV_32FC1, or none (empty matrix),
2584
respectively.
2585
@param dstmap1 The first output map that has the type dstmap1type and the same size as src .
2586
@param dstmap2 The second output map.
2587
@param dstmap1type Type of the first output map that should be CV_16SC2, CV_32FC1, or
2588
CV_32FC2 .
2589
@param nninterpolation Flag indicating whether the fixed-point maps are used for the
2590
nearest-neighbor or for a more complex interpolation.
2591
2592
@sa  remap, undistort, initUndistortRectifyMap
2593
 */
2594
CV_EXPORTS_W void convertMaps( InputArray map1, InputArray map2,
2595
                               OutputArray dstmap1, OutputArray dstmap2,
2596
                               int dstmap1type, bool nninterpolation = false );
2597
2598
/** @brief Calculates an affine matrix of 2D rotation.
2599
2600
The function calculates the following matrix:
2601
2602
\f[\begin{bmatrix} \alpha &  \beta & (1- \alpha )  \cdot \texttt{center.x} -  \beta \cdot \texttt{center.y} \\ - \beta &  \alpha &  \beta \cdot \texttt{center.x} + (1- \alpha )  \cdot \texttt{center.y} \end{bmatrix}\f]
2603
2604
where
2605
2606
\f[\begin{array}{l} \alpha =  \texttt{scale} \cdot \cos \texttt{angle} , \\ \beta =  \texttt{scale} \cdot \sin \texttt{angle} \end{array}\f]
2607
2608
The transformation maps the rotation center to itself. If this is not the target, adjust the shift.
2609
2610
@param center Center of the rotation in the source image.
2611
@param angle Rotation angle in degrees. Positive values mean counter-clockwise rotation (the
2612
coordinate origin is assumed to be the top-left corner).
2613
@param scale Isotropic scale factor.
2614
2615
@sa  getAffineTransform, warpAffine, transform
2616
 */
2617
CV_EXPORTS_W Mat getRotationMatrix2D(Point2f center, double angle, double scale);
2618
2619
/** @sa getRotationMatrix2D */
2620
CV_EXPORTS Matx23d getRotationMatrix2D_(Point2f center, double angle, double scale);
2621
2622
inline
2623
Mat getRotationMatrix2D(Point2f center, double angle, double scale)
2624
0
{
2625
0
    return Mat(getRotationMatrix2D_(center, angle, scale), true);
2626
0
}
2627
2628
/** @brief Calculates an affine transform from three pairs of the corresponding points.
2629
2630
The function calculates the \f$2 \times 3\f$ matrix of an affine transform so that:
2631
2632
\f[\begin{bmatrix} x'_i \\ y'_i \end{bmatrix} = \texttt{map_matrix} \cdot \begin{bmatrix} x_i \\ y_i \\ 1 \end{bmatrix}\f]
2633
2634
where
2635
2636
\f[dst(i)=(x'_i,y'_i), src(i)=(x_i, y_i), i=0,1,2\f]
2637
2638
@param src Coordinates of triangle vertices in the source image.
2639
@param dst Coordinates of the corresponding triangle vertices in the destination image.
2640
2641
@sa  warpAffine, transform
2642
 */
2643
CV_EXPORTS Mat getAffineTransform( const Point2f src[], const Point2f dst[] );
2644
2645
/** @brief Inverts an affine transformation.
2646
2647
The function computes an inverse affine transformation represented by \f$2 \times 3\f$ matrix M:
2648
2649
\f[\begin{bmatrix} a_{11} & a_{12} & b_1  \\ a_{21} & a_{22} & b_2 \end{bmatrix}\f]
2650
2651
The result is also a \f$2 \times 3\f$ matrix of the same type as M.
2652
2653
@param M Original affine transformation.
2654
@param iM Output reverse affine transformation.
2655
 */
2656
CV_EXPORTS_W void invertAffineTransform( InputArray M, OutputArray iM );
2657
2658
/** @brief Calculates a perspective transform from four pairs of the corresponding points.
2659
2660
The function calculates the \f$3 \times 3\f$ matrix of a perspective transform so that:
2661
2662
\f[\begin{bmatrix} t_i x'_i \\ t_i y'_i \\ t_i \end{bmatrix} = \texttt{map_matrix} \cdot \begin{bmatrix} x_i \\ y_i \\ 1 \end{bmatrix}\f]
2663
2664
where
2665
2666
\f[dst(i)=(x'_i,y'_i), src(i)=(x_i, y_i), i=0,1,2,3\f]
2667
2668
@param src Coordinates of quadrangle vertices in the source image.
2669
@param dst Coordinates of the corresponding quadrangle vertices in the destination image.
2670
@param solveMethod method passed to cv::solve (#DecompTypes)
2671
2672
@sa  findHomography, warpPerspective, perspectiveTransform
2673
 */
2674
CV_EXPORTS_W Mat getPerspectiveTransform(InputArray src, InputArray dst, int solveMethod = DECOMP_LU);
2675
2676
/** @overload */
2677
CV_EXPORTS Mat getPerspectiveTransform(const Point2f src[], const Point2f dst[], int solveMethod = DECOMP_LU);
2678
2679
2680
CV_EXPORTS_W Mat getAffineTransform( InputArray src, InputArray dst );
2681
2682
/** @brief Retrieves a pixel rectangle from an image with sub-pixel accuracy.
2683
2684
The function getRectSubPix extracts pixels from src:
2685
2686
\f[patch(x, y) = src(x +  \texttt{center.x} - ( \texttt{dst.cols} -1)*0.5, y +  \texttt{center.y} - ( \texttt{dst.rows} -1)*0.5)\f]
2687
2688
where the values of the pixels at non-integer coordinates are retrieved using bilinear
2689
interpolation. Every channel of multi-channel images is processed independently. Also
2690
the image should be a single channel or three channel image. While the center of the
2691
rectangle must be inside the image, parts of the rectangle may be outside.
2692
2693
@param image Source image.
2694
@param patchSize Size of the extracted patch.
2695
@param center Floating point coordinates of the center of the extracted rectangle within the
2696
source image. The center must be inside the image.
2697
@param patch Extracted patch that has the size patchSize and the same number of channels as src .
2698
@param patchType Depth of the extracted pixels. By default, they have the same depth as src .
2699
2700
@sa  warpAffine, warpPerspective
2701
 */
2702
CV_EXPORTS_W void getRectSubPix( InputArray image, Size patchSize,
2703
                                 Point2f center, OutputArray patch, int patchType = -1 );
2704
2705
/** @example samples/cpp/polar_transforms.cpp
2706
An example using the cv::linearPolar and cv::logPolar operations
2707
*/
2708
2709
/** @brief Remaps an image to semilog-polar coordinates space.
2710
2711
@deprecated This function produces same result as cv::warpPolar(src, dst, src.size(), center, maxRadius, flags+WARP_POLAR_LOG);
2712
2713
@internal
2714
Transform the source image using the following transformation (See @ref polar_remaps_reference_image "Polar remaps reference image d)"):
2715
\f[\begin{array}{l}
2716
  dst( \rho , \phi ) = src(x,y) \\
2717
  dst.size() \leftarrow src.size()
2718
\end{array}\f]
2719
2720
where
2721
\f[\begin{array}{l}
2722
  I = (dx,dy) = (x - center.x,y - center.y) \\
2723
  \rho = M \cdot log_e(\texttt{magnitude} (I)) ,\\
2724
  \phi = Kangle \cdot \texttt{angle} (I) \\
2725
\end{array}\f]
2726
2727
and
2728
\f[\begin{array}{l}
2729
  M = src.cols / log_e(maxRadius) \\
2730
  Kangle = src.rows / 2\Pi \\
2731
\end{array}\f]
2732
2733
The function emulates the human "foveal" vision and can be used for fast scale and
2734
rotation-invariant template matching, for object tracking and so forth.
2735
@param src Source image
2736
@param dst Destination image. It will have same size and type as src.
2737
@param center The transformation center; where the output precision is maximal
2738
@param M Magnitude scale parameter. It determines the radius of the bounding circle to transform too.
2739
@param flags A combination of interpolation methods, see #InterpolationFlags
2740
2741
@note
2742
-   The function can not operate in-place.
2743
-   To calculate magnitude and angle in degrees #cartToPolar is used internally thus angles are measured from 0 to 360 with accuracy about 0.3 degrees.
2744
2745
@sa cv::linearPolar
2746
@endinternal
2747
*/
2748
CV_EXPORTS_W void logPolar( InputArray src, OutputArray dst,
2749
                            Point2f center, double M, int flags );
2750
2751
/** @brief Remaps an image to polar coordinates space.
2752
2753
@deprecated This function produces same result as cv::warpPolar(src, dst, src.size(), center, maxRadius, flags)
2754
2755
@internal
2756
Transform the source image using the following transformation (See @ref polar_remaps_reference_image "Polar remaps reference image c)"):
2757
\f[\begin{array}{l}
2758
  dst( \rho , \phi ) = src(x,y) \\
2759
  dst.size() \leftarrow src.size()
2760
\end{array}\f]
2761
2762
where
2763
\f[\begin{array}{l}
2764
  I = (dx,dy) = (x - center.x,y - center.y) \\
2765
  \rho = Kmag \cdot \texttt{magnitude} (I) ,\\
2766
  \phi = angle \cdot \texttt{angle} (I)
2767
\end{array}\f]
2768
2769
and
2770
\f[\begin{array}{l}
2771
  Kx = src.cols / maxRadius \\
2772
  Ky = src.rows / 2\Pi
2773
\end{array}\f]
2774
2775
2776
@param src Source image
2777
@param dst Destination image. It will have same size and type as src.
2778
@param center The transformation center;
2779
@param maxRadius The radius of the bounding circle to transform. It determines the inverse magnitude scale parameter too.
2780
@param flags A combination of interpolation methods, see #InterpolationFlags
2781
2782
@note
2783
-   The function can not operate in-place.
2784
-   To calculate magnitude and angle in degrees #cartToPolar is used internally thus angles are measured from 0 to 360 with accuracy about 0.3 degrees.
2785
2786
@sa cv::logPolar
2787
@endinternal
2788
*/
2789
CV_EXPORTS_W void linearPolar( InputArray src, OutputArray dst,
2790
                               Point2f center, double maxRadius, int flags );
2791
2792
2793
/** \brief Remaps an image to polar or semilog-polar coordinates space
2794
2795
@anchor polar_remaps_reference_image
2796
![Polar remaps reference](pics/polar_remap_doc.png)
2797
2798
Transform the source image using the following transformation:
2799
\f[
2800
dst(\rho , \phi ) = src(x,y)
2801
\f]
2802
2803
where
2804
\f[
2805
\begin{array}{l}
2806
\vec{I} = (x - center.x, \;y - center.y) \\
2807
\phi = Kangle \cdot \texttt{angle} (\vec{I}) \\
2808
\rho = \left\{\begin{matrix}
2809
Klin \cdot \texttt{magnitude} (\vec{I}) & default \\
2810
Klog \cdot log_e(\texttt{magnitude} (\vec{I})) & if \; semilog \\
2811
\end{matrix}\right.
2812
\end{array}
2813
\f]
2814
2815
and
2816
\f[
2817
\begin{array}{l}
2818
Kangle = dsize.height / 2\Pi \\
2819
Klin = dsize.width / maxRadius \\
2820
Klog = dsize.width / log_e(maxRadius) \\
2821
\end{array}
2822
\f]
2823
2824
2825
\par Linear vs semilog mapping
2826
2827
Polar mapping can be linear or semi-log. Add one of #WarpPolarMode to `flags` to specify the polar mapping mode.
2828
2829
Linear is the default mode.
2830
2831
The semilog mapping emulates the human "foveal" vision that permit very high acuity on the line of sight (central vision)
2832
in contrast to peripheral vision where acuity is minor.
2833
2834
\par Option on `dsize`:
2835
2836
- if both values in `dsize <=0 ` (default),
2837
the destination image will have (almost) same area of source bounding circle:
2838
\f[\begin{array}{l}
2839
dsize.area  \leftarrow (maxRadius^2 \cdot \Pi) \\
2840
dsize.width = \texttt{cvRound}(maxRadius) \\
2841
dsize.height = \texttt{cvRound}(maxRadius \cdot \Pi) \\
2842
\end{array}\f]
2843
2844
2845
- if only `dsize.height <= 0`,
2846
the destination image area will be proportional to the bounding circle area but scaled by `Kx * Kx`:
2847
\f[\begin{array}{l}
2848
dsize.height = \texttt{cvRound}(dsize.width \cdot \Pi) \\
2849
\end{array}
2850
\f]
2851
2852
- if both values in `dsize > 0 `,
2853
the destination image will have the given size therefore the area of the bounding circle will be scaled to `dsize`.
2854
2855
2856
\par Reverse mapping
2857
2858
You can get reverse mapping adding #WARP_INVERSE_MAP to `flags`
2859
\snippet polar_transforms.cpp InverseMap
2860
2861
In addiction, to calculate the original coordinate from a polar mapped coordinate \f$(rho, phi)->(x, y)\f$:
2862
\snippet polar_transforms.cpp InverseCoordinate
2863
2864
@param src Source image.
2865
@param dst Destination image. It will have same type as src.
2866
@param dsize The destination image size (see description for valid options).
2867
@param center The transformation center.
2868
@param maxRadius The radius of the bounding circle to transform. It determines the inverse magnitude scale parameter too.
2869
@param flags A combination of interpolation methods, #InterpolationFlags + #WarpPolarMode.
2870
            - Add #WARP_POLAR_LINEAR to select linear polar mapping (default)
2871
            - Add #WARP_POLAR_LOG to select semilog polar mapping
2872
            - Add #WARP_INVERSE_MAP for reverse mapping.
2873
@note
2874
-  The function can not operate in-place.
2875
-  To calculate magnitude and angle in degrees #cartToPolar is used internally thus angles are measured from 0 to 360 with accuracy about 0.3 degrees.
2876
-  This function uses #remap. Due to current implementation limitations the size of an input and output images should be less than 32767x32767.
2877
2878
@sa cv::remap
2879
*/
2880
CV_EXPORTS_W void warpPolar(InputArray src, OutputArray dst, Size dsize,
2881
                            Point2f center, double maxRadius, int flags);
2882
2883
2884
//! @} imgproc_transform
2885
2886
//! @addtogroup imgproc_misc
2887
//! @{
2888
2889
/** @brief Calculates the integral of an image.
2890
2891
The function calculates one or more integral images for the source image as follows:
2892
2893
\f[\texttt{sum} (X,Y) =  \sum _{x<X,y<Y}  \texttt{image} (x,y)\f]
2894
2895
\f[\texttt{sqsum} (X,Y) =  \sum _{x<X,y<Y}  \texttt{image} (x,y)^2\f]
2896
2897
\f[\texttt{tilted} (X,Y) =  \sum _{y<Y,abs(x-X+1) \leq Y-y-1}  \texttt{image} (x,y)\f]
2898
2899
Using these integral images, you can calculate sum, mean, and standard deviation over a specific
2900
up-right or rotated rectangular region of the image in a constant time, for example:
2901
2902
\f[\sum _{x_1 \leq x < x_2,  \, y_1  \leq y < y_2}  \texttt{image} (x,y) =  \texttt{sum} (x_2,y_2)- \texttt{sum} (x_1,y_2)- \texttt{sum} (x_2,y_1)+ \texttt{sum} (x_1,y_1)\f]
2903
2904
It makes possible to do a fast blurring or fast block correlation with a variable window size, for
2905
example. In case of multi-channel images, sums for each channel are accumulated independently.
2906
2907
As a practical example, the next figure shows the calculation of the integral of a straight
2908
rectangle Rect(4,4,3,2) and of a tilted rectangle Rect(5,1,2,3) . The selected pixels in the
2909
original image are shown, as well as the relative pixels in the integral images sum and tilted .
2910
2911
![integral calculation example](pics/integral.png)
2912
2913
@param src input image as \f$W \times H\f$, 8-bit or floating-point (32f or 64f).
2914
@param sum integral image as \f$(W+1)\times (H+1)\f$ , 32-bit integer or floating-point (32f or 64f).
2915
@param sqsum integral image for squared pixel values; it is \f$(W+1)\times (H+1)\f$, double-precision
2916
floating-point (64f) array.
2917
@param tilted integral for the image rotated by 45 degrees; it is \f$(W+1)\times (H+1)\f$ array with
2918
the same data type as sum.
2919
@param sdepth desired depth of the integral and the tilted integral images, CV_32S, CV_32F, or
2920
CV_64F.
2921
@param sqdepth desired depth of the integral image of squared pixel values, CV_32F or CV_64F.
2922
 */
2923
CV_EXPORTS_AS(integral3) void integral( InputArray src, OutputArray sum,
2924
                                        OutputArray sqsum, OutputArray tilted,
2925
                                        int sdepth = -1, int sqdepth = -1 );
2926
2927
/** @overload */
2928
CV_EXPORTS_W void integral( InputArray src, OutputArray sum, int sdepth = -1 );
2929
2930
/** @overload */
2931
CV_EXPORTS_AS(integral2) void integral( InputArray src, OutputArray sum,
2932
                                        OutputArray sqsum, int sdepth = -1, int sqdepth = -1 );
2933
2934
//! @} imgproc_misc
2935
2936
//! @addtogroup imgproc_motion
2937
//! @{
2938
2939
/** @brief Adds an image to the accumulator image.
2940
2941
The function adds src or some of its elements to dst :
2942
2943
\f[\texttt{dst} (x,y)  \leftarrow \texttt{dst} (x,y) +  \texttt{src} (x,y)  \quad \text{if} \quad \texttt{mask} (x,y)  \ne 0\f]
2944
2945
The function supports multi-channel images. Each channel is processed independently.
2946
2947
The function cv::accumulate can be used, for example, to collect statistics of a scene background
2948
viewed by a still camera and for the further foreground-background segmentation.
2949
2950
@param src Input image of type CV_8UC(n), CV_16UC(n), CV_32FC(n) or CV_64FC(n), where n is a positive integer.
2951
@param dst %Accumulator image with the same number of channels as input image, and a depth of CV_32F or CV_64F.
2952
@param mask Optional operation mask.
2953
2954
@sa  accumulateSquare, accumulateProduct, accumulateWeighted
2955
 */
2956
CV_EXPORTS_W void accumulate( InputArray src, InputOutputArray dst,
2957
                              InputArray mask = noArray() );
2958
2959
/** @brief Adds the square of a source image to the accumulator image.
2960
2961
The function adds the input image src or its selected region, raised to a power of 2, to the
2962
accumulator dst :
2963
2964
\f[\texttt{dst} (x,y)  \leftarrow \texttt{dst} (x,y) +  \texttt{src} (x,y)^2  \quad \text{if} \quad \texttt{mask} (x,y)  \ne 0\f]
2965
2966
The function supports multi-channel images. Each channel is processed independently.
2967
2968
@param src Input image as 1- or 3-channel, 8-bit or 32-bit floating point.
2969
@param dst %Accumulator image with the same number of channels as input image, 32-bit or 64-bit
2970
floating-point.
2971
@param mask Optional operation mask.
2972
2973
@sa  accumulateSquare, accumulateProduct, accumulateWeighted
2974
 */
2975
CV_EXPORTS_W void accumulateSquare( InputArray src, InputOutputArray dst,
2976
                                    InputArray mask = noArray() );
2977
2978
/** @brief Adds the per-element product of two input images to the accumulator image.
2979
2980
The function adds the product of two images or their selected regions to the accumulator dst :
2981
2982
\f[\texttt{dst} (x,y)  \leftarrow \texttt{dst} (x,y) +  \texttt{src1} (x,y)  \cdot \texttt{src2} (x,y)  \quad \text{if} \quad \texttt{mask} (x,y)  \ne 0\f]
2983
2984
The function supports multi-channel images. Each channel is processed independently.
2985
2986
@param src1 First input image, 1- or 3-channel, 8-bit or 32-bit floating point.
2987
@param src2 Second input image of the same type and the same size as src1 .
2988
@param dst %Accumulator image with the same number of channels as input images, 32-bit or 64-bit
2989
floating-point.
2990
@param mask Optional operation mask.
2991
2992
@sa  accumulate, accumulateSquare, accumulateWeighted
2993
 */
2994
CV_EXPORTS_W void accumulateProduct( InputArray src1, InputArray src2,
2995
                                     InputOutputArray dst, InputArray mask=noArray() );
2996
2997
/** @brief Updates a running average.
2998
2999
The function calculates the weighted sum of the input image src and the accumulator dst so that dst
3000
becomes a running average of a frame sequence:
3001
3002
\f[\texttt{dst} (x,y)  \leftarrow (1- \texttt{alpha} )  \cdot \texttt{dst} (x,y) +  \texttt{alpha} \cdot \texttt{src} (x,y)  \quad \text{if} \quad \texttt{mask} (x,y)  \ne 0\f]
3003
3004
That is, alpha regulates the update speed (how fast the accumulator "forgets" about earlier images).
3005
The function supports multi-channel images. Each channel is processed independently.
3006
3007
@param src Input image as 1- or 3-channel, 8-bit or 32-bit floating point.
3008
@param dst %Accumulator image with the same number of channels as input image, 32-bit or 64-bit
3009
floating-point.
3010
@param alpha Weight of the input image.
3011
@param mask Optional operation mask.
3012
3013
@sa  accumulate, accumulateSquare, accumulateProduct
3014
 */
3015
CV_EXPORTS_W void accumulateWeighted( InputArray src, InputOutputArray dst,
3016
                                      double alpha, InputArray mask = noArray() );
3017
3018
/** @brief The function is used to detect translational shifts that occur between two images.
3019
3020
The operation takes advantage of the Fourier shift theorem for detecting the translational shift in
3021
the frequency domain. It can be used for fast image registration as well as motion estimation. For
3022
more information please see <https://en.wikipedia.org/wiki/Phase_correlation>
3023
3024
Calculates the cross-power spectrum of two supplied source arrays. The arrays are padded if needed
3025
with getOptimalDFTSize.
3026
3027
The function performs the following equations:
3028
- First it applies a Hanning window to each image to remove possible edge effects, if it's provided
3029
by user. See @ref createHanningWindow and <https://en.wikipedia.org/wiki/Hann_function>. This window may
3030
be cached until the array size changes to speed up processing time.
3031
- Next it computes the forward DFTs of each source array:
3032
\f[\mathbf{G}_a = \mathcal{F}\{src_1\}, \; \mathbf{G}_b = \mathcal{F}\{src_2\}\f]
3033
where \f$\mathcal{F}\f$ is the forward DFT.
3034
- It then computes the cross-power spectrum of each frequency domain array:
3035
\f[R = \frac{ \mathbf{G}_a \mathbf{G}_b^*}{|\mathbf{G}_a \mathbf{G}_b^*|}\f]
3036
- Next the cross-correlation is converted back into the time domain via the inverse DFT:
3037
\f[r = \mathcal{F}^{-1}\{R\}\f]
3038
- Finally, it computes the peak location and computes a 5x5 weighted centroid around the peak to
3039
achieve sub-pixel accuracy.
3040
\f[(\Delta x, \Delta y) = \texttt{weightedCentroid} \{\arg \max_{(x, y)}\{r\}\}\f]
3041
- If non-zero, the response parameter is computed as the sum of the elements of r within the 5x5
3042
centroid around the peak location. It is normalized to a maximum of 1 (meaning there is a single
3043
peak) and will be smaller when there are multiple peaks.
3044
3045
@param src1 Source floating point array (CV_32FC1 or CV_64FC1)
3046
@param src2 Source floating point array (CV_32FC1 or CV_64FC1)
3047
@param window Floating point array with windowing coefficients to reduce edge effects (optional).
3048
@param response Signal power within the 5x5 centroid around the peak, between 0 and 1 (optional).
3049
@returns detected phase shift (sub-pixel) between the two arrays.
3050
3051
@sa dft, getOptimalDFTSize, idft, mulSpectrums createHanningWindow
3052
 */
3053
CV_EXPORTS_W Point2d phaseCorrelate(InputArray src1, InputArray src2,
3054
                                    InputArray window = noArray(), CV_OUT double* response = 0);
3055
3056
/** @brief Detects translational shifts between two images.
3057
3058
This function extends the standard @ref phaseCorrelate method by improving sub-pixel accuracy
3059
through iterative shift refinement in the phase-correlation space, as described in
3060
@cite hrazdira2020iterative.
3061
3062
@param src1 Source floating point array (CV_32FC1 or CV_64FC1)
3063
@param src2 Source floating point array (CV_32FC1 or CV_64FC1)
3064
@param L2size The size of the correlation neighborhood used by the iterative shift refinement algorithm.
3065
@param maxIters The maximum number of iterations the iterative refinement algorithm will run.
3066
@returns detected sub-pixel shift between the two arrays.
3067
3068
@sa phaseCorrelate, dft, idft, createHanningWindow
3069
 */
3070
CV_EXPORTS_W Point2d phaseCorrelateIterative(InputArray src1, InputArray src2, int L2size = 7, int maxIters = 10);
3071
3072
/** @brief This function computes a Hanning window coefficients in two dimensions.
3073
3074
See (https://en.wikipedia.org/wiki/Hann_function) and (https://en.wikipedia.org/wiki/Window_function)
3075
for more information.
3076
3077
An example is shown below:
3078
@code
3079
    // create hanning window of size 100x100 and type CV_32F
3080
    Mat hann;
3081
    createHanningWindow(hann, Size(100, 100), CV_32F);
3082
@endcode
3083
@param dst Destination array to place Hann coefficients in
3084
@param winSize The window size specifications (both width and height must be > 1)
3085
@param type Created array type
3086
 */
3087
CV_EXPORTS_W void createHanningWindow(OutputArray dst, Size winSize, int type);
3088
3089
/** @brief Performs the per-element division of the first Fourier spectrum by the second Fourier spectrum.
3090
3091
The function cv::divSpectrums performs the per-element division of the first array by the second array.
3092
The arrays are CCS-packed or complex matrices that are results of a real or complex Fourier transform.
3093
3094
@param a first input array.
3095
@param b second input array of the same size and type as src1 .
3096
@param c output array of the same size and type as src1 .
3097
@param flags operation flags; currently, the only supported flag is cv::DFT_ROWS, which indicates that
3098
each row of src1 and src2 is an independent 1D Fourier spectrum. If you do not want to use this flag, then simply add a `0` as value.
3099
@param conjB optional flag that conjugates the second input array before the multiplication (true)
3100
or not (false).
3101
*/
3102
CV_EXPORTS_W void divSpectrums(InputArray a, InputArray b, OutputArray c,
3103
                               int flags, bool conjB = false);
3104
3105
//! @} imgproc_motion
3106
3107
//! @addtogroup imgproc_misc
3108
//! @{
3109
3110
/** @brief Applies a fixed-level threshold to each array element.
3111
3112
The function applies fixed-level thresholding to a multiple-channel array. The function is typically
3113
used to get a bi-level (binary) image out of a grayscale image ( #compare could be also used for
3114
this purpose) or for removing a noise, that is, filtering out pixels with too small or too large
3115
values. There are several types of thresholding supported by the function. They are determined by
3116
type parameter.
3117
3118
Also, the special values #THRESH_OTSU or #THRESH_TRIANGLE may be combined with one of the
3119
above values. In these cases, the function determines the optimal threshold value using the Otsu's
3120
or Triangle algorithm and uses it instead of the specified thresh.
3121
3122
@note Currently, the Otsu's method is implemented only for CV_8UC1 and CV_16UC1 images,
3123
and the Triangle's method is implemented only for CV_8UC1 images.
3124
3125
@param src input array (multiple-channel, CV_8U, CV_16S, CV_16U, CV_32F or CV_64F).
3126
@param dst output array of the same size  and type and the same number of channels as src.
3127
@param thresh threshold value.
3128
@param maxval maximum value to use with the #THRESH_BINARY and #THRESH_BINARY_INV thresholding
3129
types.
3130
@param type thresholding type (see #ThresholdTypes).
3131
@return the computed threshold value if Otsu's or Triangle methods used.
3132
3133
@sa  thresholdWithMask, adaptiveThreshold, findContours, compare, min, max
3134
 */
3135
CV_EXPORTS_W double threshold( InputArray src, OutputArray dst,
3136
                               double thresh, double maxval, int type );
3137
3138
/** @brief Same as #threshold, but with an optional mask
3139
3140
@note If the mask is empty, #thresholdWithMask is equivalent to #threshold.
3141
If the mask is not empty, dst *must* be of the same size and type as src, so that
3142
outliers pixels are left as-is
3143
3144
@param src input array (multiple-channel, 8-bit or 32-bit floating point).
3145
@param dst output array of the same size  and type and the same number of channels as src.
3146
@param mask optional mask (same size as src, 8-bit).
3147
@param thresh threshold value.
3148
@param maxval maximum value to use with the #THRESH_BINARY and #THRESH_BINARY_INV thresholding
3149
types.
3150
@param type thresholding type (see #ThresholdTypes).
3151
@return the computed threshold value if Otsu's or Triangle methods used.
3152
3153
@sa  threshold, adaptiveThreshold, findContours, compare, min, max
3154
*/
3155
CV_EXPORTS_W double thresholdWithMask( InputArray src, InputOutputArray dst, InputArray mask,
3156
                                       double thresh, double maxval, int type );
3157
3158
/** @brief Applies an adaptive threshold to an array.
3159
3160
The function transforms a grayscale image to a binary image according to the formulae:
3161
-   **THRESH_BINARY**
3162
    \f[dst(x,y) =  \fork{\texttt{maxValue}}{if \(src(x,y) > T(x,y)\)}{0}{otherwise}\f]
3163
-   **THRESH_BINARY_INV**
3164
    \f[dst(x,y) =  \fork{0}{if \(src(x,y) > T(x,y)\)}{\texttt{maxValue}}{otherwise}\f]
3165
where \f$T(x,y)\f$ is a threshold calculated individually for each pixel (see adaptiveMethod parameter).
3166
3167
The function can process the image in-place.
3168
3169
@param src Source 8-bit single-channel image.
3170
@param dst Destination image of the same size and the same type as src.
3171
@param maxValue Non-zero value assigned to the pixels for which the condition is satisfied
3172
@param adaptiveMethod Adaptive thresholding algorithm to use, see #AdaptiveThresholdTypes.
3173
The #BORDER_REPLICATE | #BORDER_ISOLATED is used to process boundaries.
3174
@param thresholdType Thresholding type that must be either #THRESH_BINARY or #THRESH_BINARY_INV,
3175
see #ThresholdTypes.
3176
@param blockSize Size of a pixel neighborhood that is used to calculate a threshold value for the
3177
pixel: 3, 5, 7, and so on.
3178
@param C Constant subtracted from the mean or weighted mean (see the details below). Normally, it
3179
is positive but may be zero or negative as well.
3180
3181
@sa  threshold, blur, GaussianBlur
3182
 */
3183
CV_EXPORTS_W void adaptiveThreshold( InputArray src, OutputArray dst,
3184
                                     double maxValue, int adaptiveMethod,
3185
                                     int thresholdType, int blockSize, double C );
3186
3187
//! @} imgproc_misc
3188
3189
//! @addtogroup imgproc_filter
3190
//! @{
3191
3192
/** @example samples/cpp/tutorial_code/ImgProc/Pyramids/Pyramids.cpp
3193
An example using pyrDown and pyrUp functions
3194
*/
3195
3196
/** @brief Blurs an image and downsamples it.
3197
3198
By default, size of the output image is computed as `Size((src.cols+1)/2, (src.rows+1)/2)`, but in
3199
any case, the following conditions should be satisfied:
3200
3201
\f[\begin{array}{l} | \texttt{dstsize.width} *2-src.cols| \leq 2 \\ | \texttt{dstsize.height} *2-src.rows| \leq 2 \end{array}\f]
3202
3203
The function performs the downsampling step of the Gaussian pyramid construction. First, it
3204
convolves the source image with the kernel:
3205
3206
\f[\frac{1}{256} \begin{bmatrix} 1 & 4 & 6 & 4 & 1  \\ 4 & 16 & 24 & 16 & 4  \\ 6 & 24 & 36 & 24 & 6  \\ 4 & 16 & 24 & 16 & 4  \\ 1 & 4 & 6 & 4 & 1 \end{bmatrix}\f]
3207
3208
Then, it downsamples the image by rejecting even rows and columns.
3209
3210
@param src input image.
3211
@param dst output image; it has the specified size and the same type as src.
3212
@param dstsize size of the output image.
3213
@param borderType Pixel extrapolation method, see #BorderTypes (#BORDER_CONSTANT isn't supported)
3214
 */
3215
CV_EXPORTS_W void pyrDown( InputArray src, OutputArray dst,
3216
                           const Size& dstsize = Size(), int borderType = BORDER_DEFAULT );
3217
3218
/** @brief Upsamples an image and then blurs it.
3219
3220
By default, size of the output image is computed as `Size(src.cols\*2, (src.rows\*2)`, but in any
3221
case, the following conditions should be satisfied:
3222
3223
\f[\begin{array}{l} | \texttt{dstsize.width} -src.cols*2| \leq  ( \texttt{dstsize.width}   \mod  2)  \\ | \texttt{dstsize.height} -src.rows*2| \leq  ( \texttt{dstsize.height}   \mod  2) \end{array}\f]
3224
3225
The function performs the upsampling step of the Gaussian pyramid construction, though it can
3226
actually be used to construct the Laplacian pyramid. First, it upsamples the source image by
3227
injecting even zero rows and columns and then convolves the result with the same kernel as in
3228
pyrDown multiplied by 4.
3229
3230
@param src input image.
3231
@param dst output image. It has the specified size and the same type as src .
3232
@param dstsize size of the output image.
3233
@param borderType Pixel extrapolation method, see #BorderTypes (only #BORDER_DEFAULT is supported)
3234
 */
3235
CV_EXPORTS_W void pyrUp( InputArray src, OutputArray dst,
3236
                         const Size& dstsize = Size(), int borderType = BORDER_DEFAULT );
3237
3238
/** @brief Constructs the Gaussian pyramid for an image.
3239
3240
The function constructs a vector of images and builds the Gaussian pyramid by recursively applying
3241
pyrDown to the previously built pyramid layers, starting from `dst[0]==src`.
3242
3243
@param src Source image. Check pyrDown for the list of supported types.
3244
@param dst Destination vector of maxlevel+1 images of the same type as src. dst[0] will be the
3245
same as src. dst[1] is the next pyramid layer, a smoothed and down-sized src, and so on.
3246
@param maxlevel 0-based index of the last (the smallest) pyramid layer. It must be non-negative.
3247
@param borderType Pixel extrapolation method, see #BorderTypes (#BORDER_CONSTANT isn't supported)
3248
 */
3249
CV_EXPORTS void buildPyramid( InputArray src, OutputArrayOfArrays dst,
3250
                              int maxlevel, int borderType = BORDER_DEFAULT );
3251
3252
//! @} imgproc_filter
3253
3254
//! @addtogroup imgproc_hist
3255
//! @{
3256
3257
/** @example samples/cpp/demhist.cpp
3258
An example for creating histograms of an image
3259
*/
3260
3261
/** @brief Calculates a histogram of a set of arrays.
3262
3263
The function cv::calcHist calculates the histogram of one or more arrays. The elements of a tuple used
3264
to increment a histogram bin are taken from the corresponding input arrays at the same location. The
3265
sample below shows how to compute a 2D Hue-Saturation histogram for a color image. :
3266
@include snippets/imgproc_calcHist.cpp
3267
3268
@param images Source arrays. They all should have the same depth, CV_8U, CV_16U or CV_32F , and the same
3269
size. Each of them can have an arbitrary number of channels.
3270
@param nimages Number of source images.
3271
@param channels List of the dims channels used to compute the histogram. The first array channels
3272
are numerated from 0 to images[0].channels()-1 , the second array channels are counted from
3273
images[0].channels() to images[0].channels() + images[1].channels()-1, and so on.
3274
@param mask Optional mask. If the matrix is not empty, it must be an 8-bit array of the same size
3275
as images[i] . The non-zero mask elements mark the array elements counted in the histogram.
3276
@param hist Output histogram, which is a dense or sparse dims -dimensional array.
3277
@param dims Histogram dimensionality that must be positive and not greater than CV_MAX_DIMS
3278
(equal to 32 in the current OpenCV version).
3279
@param histSize Array of histogram sizes in each dimension.
3280
@param ranges Array of the dims arrays of the histogram bin boundaries in each dimension. When the
3281
histogram is uniform ( uniform =true), then for each dimension i it is enough to specify the lower
3282
(inclusive) boundary \f$L_0\f$ of the 0-th histogram bin and the upper (exclusive) boundary
3283
\f$U_{\texttt{histSize}[i]-1}\f$ for the last histogram bin histSize[i]-1 . That is, in case of a
3284
uniform histogram each of ranges[i] is an array of 2 elements. When the histogram is not uniform (
3285
uniform=false ), then each of ranges[i] contains histSize[i]+1 elements:
3286
\f$L_0, U_0=L_1, U_1=L_2, ..., U_{\texttt{histSize[i]}-2}=L_{\texttt{histSize[i]}-1}, U_{\texttt{histSize[i]}-1}\f$
3287
. The array elements, that are not between \f$L_0\f$ and \f$U_{\texttt{histSize[i]}-1}\f$ , are not
3288
counted in the histogram.
3289
@param uniform Flag indicating whether the histogram is uniform or not (see above).
3290
@param accumulate Accumulation flag. If it is set, the histogram is not cleared in the beginning
3291
when it is allocated. This feature enables you to compute a single histogram from several sets of
3292
arrays, or to update the histogram in time.
3293
*/
3294
CV_EXPORTS void calcHist( const Mat* images, int nimages,
3295
                          const int* channels, InputArray mask,
3296
                          OutputArray hist, int dims, const int* histSize,
3297
                          const float** ranges, bool uniform = true, bool accumulate = false );
3298
3299
/** @overload
3300
3301
this variant uses %SparseMat for output
3302
*/
3303
CV_EXPORTS void calcHist( const Mat* images, int nimages,
3304
                          const int* channels, InputArray mask,
3305
                          SparseMat& hist, int dims,
3306
                          const int* histSize, const float** ranges,
3307
                          bool uniform = true, bool accumulate = false );
3308
3309
/** @overload
3310
3311
this variant supports only uniform histograms.
3312
3313
ranges argument is either empty vector or a flattened vector of histSize.size()*2 elements
3314
(histSize.size() element pairs). The first and second elements of each pair specify the lower and
3315
upper boundaries.
3316
*/
3317
CV_EXPORTS_W void calcHist( InputArrayOfArrays images,
3318
                            const std::vector<int>& channels,
3319
                            InputArray mask, OutputArray hist,
3320
                            const std::vector<int>& histSize,
3321
                            const std::vector<float>& ranges,
3322
                            bool accumulate = false );
3323
3324
/** @brief Calculates the back projection of a histogram.
3325
3326
The function cv::calcBackProject calculates the back project of the histogram. That is, similarly to
3327
#calcHist , at each location (x, y) the function collects the values from the selected channels
3328
in the input images and finds the corresponding histogram bin. But instead of incrementing it, the
3329
function reads the bin value, scales it by scale , and stores in backProject(x,y) . In terms of
3330
statistics, the function computes probability of each element value in respect with the empirical
3331
probability distribution represented by the histogram. See how, for example, you can find and track
3332
a bright-colored object in a scene:
3333
3334
- Before tracking, show the object to the camera so that it covers almost the whole frame.
3335
Calculate a hue histogram. The histogram may have strong maximums, corresponding to the dominant
3336
colors in the object.
3337
3338
- When tracking, calculate a back projection of a hue plane of each input video frame using that
3339
pre-computed histogram. Threshold the back projection to suppress weak colors. It may also make
3340
sense to suppress pixels with non-sufficient color saturation and too dark or too bright pixels.
3341
3342
- Find connected components in the resulting picture and choose, for example, the largest
3343
component.
3344
3345
This is an approximate algorithm of the CamShift color object tracker.
3346
3347
@param images Source arrays. They all should have the same depth, CV_8U, CV_16U or CV_32F , and the same
3348
size. Each of them can have an arbitrary number of channels.
3349
@param nimages Number of source images.
3350
@param channels The list of channels used to compute the back projection. The number of channels
3351
must match the histogram dimensionality. The first array channels are numerated from 0 to
3352
images[0].channels()-1 , the second array channels are counted from images[0].channels() to
3353
images[0].channels() + images[1].channels()-1, and so on.
3354
@param hist Input histogram that can be dense or sparse.
3355
@param backProject Destination back projection array that is a single-channel array of the same
3356
size and depth as images[0] .
3357
@param ranges Array of arrays of the histogram bin boundaries in each dimension. See #calcHist .
3358
@param scale Optional scale factor for the output back projection.
3359
@param uniform Flag indicating whether the histogram is uniform or not (see #calcHist).
3360
3361
@sa calcHist, compareHist
3362
 */
3363
CV_EXPORTS void calcBackProject( const Mat* images, int nimages,
3364
                                 const int* channels, InputArray hist,
3365
                                 OutputArray backProject, const float** ranges,
3366
                                 double scale = 1, bool uniform = true );
3367
3368
/** @overload */
3369
CV_EXPORTS void calcBackProject( const Mat* images, int nimages,
3370
                                 const int* channels, const SparseMat& hist,
3371
                                 OutputArray backProject, const float** ranges,
3372
                                 double scale = 1, bool uniform = true );
3373
3374
/** @overload */
3375
CV_EXPORTS_W void calcBackProject( InputArrayOfArrays images, const std::vector<int>& channels,
3376
                                   InputArray hist, OutputArray dst,
3377
                                   const std::vector<float>& ranges,
3378
                                   double scale );
3379
3380
/** @brief Compares two histograms.
3381
3382
The function cv::compareHist compares two dense or two sparse histograms using the specified method.
3383
3384
The function returns \f$d(H_1, H_2)\f$ .
3385
3386
While the function works well with 1-, 2-, 3-dimensional dense histograms, it may not be suitable
3387
for high-dimensional sparse histograms. In such histograms, because of aliasing and sampling
3388
problems, the coordinates of non-zero histogram bins can slightly shift. To compare such histograms
3389
or more general sparse configurations of weighted points, consider using the #EMD function.
3390
3391
@param H1 First compared histogram.
3392
@param H2 Second compared histogram of the same size as H1 .
3393
@param method Comparison method, see #HistCompMethods
3394
 */
3395
CV_EXPORTS_W double compareHist( InputArray H1, InputArray H2, int method );
3396
3397
/** @overload */
3398
CV_EXPORTS double compareHist( const SparseMat& H1, const SparseMat& H2, int method );
3399
3400
/** @brief Equalizes the histogram of a grayscale image.
3401
3402
The function equalizes the histogram of the input image using the following algorithm:
3403
3404
- Calculate the histogram \f$H\f$ for src .
3405
- Normalize the histogram so that the sum of histogram bins is 255.
3406
- Compute the integral of the histogram:
3407
\f[H'_i =  \sum _{0  \le j < i} H(j)\f]
3408
- Transform the image using \f$H'\f$ as a look-up table: \f$\texttt{dst}(x,y) = H'(\texttt{src}(x,y))\f$
3409
3410
The algorithm normalizes the brightness and increases the contrast of the image.
3411
3412
@param src Source 8-bit single channel image.
3413
@param dst Destination image of the same size and type as src .
3414
 */
3415
CV_EXPORTS_W void equalizeHist( InputArray src, OutputArray dst );
3416
3417
/** @brief Creates a smart pointer to a cv::CLAHE class and initializes it.
3418
3419
@param clipLimit Threshold for contrast limiting.
3420
@param tileGridSize Size of grid for histogram equalization. Input image will be divided into
3421
equally sized rectangular tiles. tileGridSize defines the number of tiles in row and column.
3422
 */
3423
CV_EXPORTS_W Ptr<CLAHE> createCLAHE(double clipLimit = 40.0, Size tileGridSize = Size(8, 8));
3424
3425
/** @brief Computes the "minimal work" distance between two weighted point configurations.
3426
3427
The function computes the earth mover distance and/or a lower boundary of the distance between the
3428
two weighted point configurations. One of the applications described in @cite RubnerSept98,
3429
@cite Rubner2000 is multi-dimensional histogram comparison for image retrieval. EMD is a transportation
3430
problem that is solved using some modification of a simplex algorithm, thus the complexity is
3431
exponential in the worst case, though, on average it is much faster. In the case of a real metric
3432
the lower boundary can be calculated even faster (using linear-time algorithm) and it can be used
3433
to determine roughly whether the two signatures are far enough so that they cannot relate to the
3434
same object.
3435
3436
@param signature1 First signature, a \f$\texttt{size1}\times \texttt{dims}+1\f$ floating-point matrix.
3437
Each row stores the point weight followed by the point coordinates. The matrix is allowed to have
3438
a single column (weights only) if the user-defined cost matrix is used. The weights must be
3439
non-negative and have at least one non-zero value.
3440
@param signature2 Second signature of the same format as signature1 , though the number of rows
3441
may be different. The total weights may be different. In this case an extra "dummy" point is added
3442
to either signature1 or signature2. The weights must be non-negative and have at least one non-zero
3443
value.
3444
@param distType Used metric. See #DistanceTypes.
3445
@param cost User-defined \f$\texttt{size1}\times \texttt{size2}\f$ cost matrix. Also, if a cost matrix
3446
is used, lower boundary lowerBound cannot be calculated because it needs a metric function.
3447
@param lowerBound Optional input/output parameter: lower boundary of a distance between the two
3448
signatures that is a distance between mass centers. The lower boundary may not be calculated if
3449
the user-defined cost matrix is used, the total weights of point configurations are not equal, or
3450
if the signatures consist of weights only (the signature matrices have a single column). You
3451
**must** initialize \*lowerBound . If the calculated distance between mass centers is greater or
3452
equal to \*lowerBound (it means that the signatures are far enough), the function does not
3453
calculate EMD. In any case \*lowerBound is set to the calculated distance between mass centers on
3454
return. Thus, if you want to calculate both distance between mass centers and EMD, \*lowerBound
3455
should be set to 0.
3456
@param flow Resultant \f$\texttt{size1} \times \texttt{size2}\f$ flow matrix: \f$\texttt{flow}_{i,j}\f$ is
3457
a flow from \f$i\f$ -th point of signature1 to \f$j\f$ -th point of signature2 .
3458
 */
3459
CV_EXPORTS float EMD( InputArray signature1, InputArray signature2,
3460
                      int distType, InputArray cost=noArray(),
3461
                      float* lowerBound = 0, OutputArray flow = noArray() );
3462
3463
CV_EXPORTS_AS(EMD) float wrapperEMD( InputArray signature1, InputArray signature2,
3464
                      int distType, InputArray cost=noArray(),
3465
                      CV_IN_OUT Ptr<float> lowerBound = Ptr<float>(), OutputArray flow = noArray() );
3466
3467
//! @} imgproc_hist
3468
3469
//! @addtogroup imgproc_segmentation
3470
//! @{
3471
3472
/** @example samples/cpp/watershed.cpp
3473
An example using the watershed algorithm
3474
*/
3475
3476
/** @brief Performs a marker-based image segmentation using the watershed algorithm.
3477
3478
The function implements one of the variants of watershed, non-parametric marker-based segmentation
3479
algorithm, described in @cite Meyer92 .
3480
3481
Before passing the image to the function, you have to roughly outline the desired regions in the
3482
image markers with positive (\>0) indices. So, every region is represented as one or more connected
3483
components with the pixel values 1, 2, 3, and so on. Such markers can be retrieved from a binary
3484
mask using #findContours and #drawContours (see the watershed.cpp demo). The markers are "seeds" of
3485
the future image regions. All the other pixels in markers , whose relation to the outlined regions
3486
is not known and should be defined by the algorithm, should be set to 0's. In the function output,
3487
each pixel in markers is set to a value of the "seed" components or to -1 at boundaries between the
3488
regions.
3489
3490
@note Any two neighbor connected components are not necessarily separated by a watershed boundary
3491
(-1's pixels); for example, they can touch each other in the initial marker image passed to the
3492
function.
3493
3494
@param image Input 8-bit 3-channel image.
3495
@param markers Input/output 32-bit single-channel image (map) of markers. It should have the same
3496
size as image .
3497
3498
@sa findContours
3499
 */
3500
CV_EXPORTS_W void watershed( InputArray image, InputOutputArray markers );
3501
3502
//! @} imgproc_segmentation
3503
3504
//! @addtogroup imgproc_filter
3505
//! @{
3506
3507
/** @brief Performs initial step of meanshift segmentation of an image.
3508
3509
The function implements the filtering stage of meanshift segmentation, that is, the output of the
3510
function is the filtered "posterized" image with color gradients and fine-grain texture flattened.
3511
At every pixel (X,Y) of the input image (or down-sized input image, see below) the function executes
3512
meanshift iterations, that is, the pixel (X,Y) neighborhood in the joint space-color hyperspace is
3513
considered:
3514
3515
\f[(x,y): X- \texttt{sp} \le x  \le X+ \texttt{sp} , Y- \texttt{sp} \le y  \le Y+ \texttt{sp} , ||(R,G,B)-(r,g,b)||   \le \texttt{sr}\f]
3516
3517
where (R,G,B) and (r,g,b) are the vectors of color components at (X,Y) and (x,y), respectively
3518
(though, the algorithm does not depend on the color space used, so any 3-component color space can
3519
be used instead). Over the neighborhood the average spatial value (X',Y') and average color vector
3520
(R',G',B') are found and they act as the neighborhood center on the next iteration:
3521
3522
\f[(X,Y)~(X',Y'), (R,G,B)~(R',G',B').\f]
3523
3524
After the iterations over, the color components of the initial pixel (that is, the pixel from where
3525
the iterations started) are set to the final value (average color at the last iteration):
3526
3527
\f[I(X,Y) <- (R*,G*,B*)\f]
3528
3529
When maxLevel \> 0, the gaussian pyramid of maxLevel+1 levels is built, and the above procedure is
3530
run on the smallest layer first. After that, the results are propagated to the larger layer and the
3531
iterations are run again only on those pixels where the layer colors differ by more than sr from the
3532
lower-resolution layer of the pyramid. That makes boundaries of color regions sharper. Note that the
3533
results will be actually different from the ones obtained by running the meanshift procedure on the
3534
whole original image (i.e. when maxLevel==0).
3535
3536
@param src The source 8-bit, 3-channel image.
3537
@param dst The destination image of the same format and the same size as the source.
3538
@param sp The spatial window radius.
3539
@param sr The color window radius.
3540
@param maxLevel Maximum level of the pyramid for the segmentation.
3541
@param termcrit Termination criteria: when to stop meanshift iterations.
3542
 */
3543
CV_EXPORTS_W void pyrMeanShiftFiltering( InputArray src, OutputArray dst,
3544
                                         double sp, double sr, int maxLevel = 1,
3545
                                         TermCriteria termcrit=TermCriteria(TermCriteria::MAX_ITER+TermCriteria::EPS,5,1) );
3546
3547
//! @}
3548
3549
//! @addtogroup imgproc_segmentation
3550
//! @{
3551
3552
/** @example samples/cpp/grabcut.cpp
3553
An example using the GrabCut algorithm
3554
![Sample Screenshot](grabcut_output1.jpg)
3555
*/
3556
3557
/** @brief Runs the GrabCut algorithm.
3558
3559
The function implements the [GrabCut image segmentation algorithm](https://en.wikipedia.org/wiki/GrabCut).
3560
3561
@param img Input 8-bit 3-channel image.
3562
@param mask Input/output 8-bit single-channel mask. The mask is initialized by the function when
3563
mode is set to #GC_INIT_WITH_RECT. Its elements may have one of the #GrabCutClasses.
3564
@param rect ROI containing a segmented object. The pixels outside of the ROI are marked as
3565
"obvious background". The parameter is only used when mode==#GC_INIT_WITH_RECT .
3566
@param bgdModel Temporary array for the background model. Do not modify it while you are
3567
processing the same image.
3568
@param fgdModel Temporary arrays for the foreground model. Do not modify it while you are
3569
processing the same image.
3570
@param iterCount Number of iterations the algorithm should make before returning the result. Note
3571
that the result can be refined with further calls with mode==#GC_INIT_WITH_MASK or
3572
mode==GC_EVAL .
3573
@param mode Operation mode that could be one of the #GrabCutModes
3574
 */
3575
CV_EXPORTS_W void grabCut( InputArray img, InputOutputArray mask, Rect rect,
3576
                           InputOutputArray bgdModel, InputOutputArray fgdModel,
3577
                           int iterCount, int mode = GC_EVAL );
3578
3579
//! @} imgproc_segmentation
3580
3581
//! @addtogroup imgproc_misc
3582
//! @{
3583
3584
/** @example samples/cpp/distrans.cpp
3585
An example on using the distance transform
3586
*/
3587
3588
/** @brief Calculates the distance to the closest zero pixel for each pixel of the source image.
3589
3590
The function cv::distanceTransform calculates the approximate or precise distance from every binary
3591
image pixel to the nearest zero pixel. For zero image pixels, the distance will obviously be zero.
3592
3593
When maskSize == #DIST_MASK_PRECISE and distanceType == #DIST_L2 , the function runs the
3594
algorithm described in @cite Felzenszwalb04 . This algorithm is parallelized with the TBB library.
3595
3596
In other cases, the algorithm @cite Borgefors86 is used. This means that for a pixel the function
3597
finds the shortest path to the nearest zero pixel consisting of basic shifts: horizontal, vertical,
3598
diagonal, or knight's move (the latest is available for a \f$5\times 5\f$ mask). The overall
3599
distance is calculated as a sum of these basic distances. Since the distance function should be
3600
symmetric, all of the horizontal and vertical shifts must have the same cost (denoted as a ), all
3601
the diagonal shifts must have the same cost (denoted as `b`), and all knight's moves must have the
3602
same cost (denoted as `c`). For the #DIST_C and #DIST_L1 types, the distance is calculated
3603
precisely, whereas for #DIST_L2 (Euclidean distance) the distance can be calculated only with a
3604
relative error (a \f$5\times 5\f$ mask gives more accurate results). For `a`,`b`, and `c`, OpenCV
3605
uses the values suggested in the original paper:
3606
- DIST_L1: `a = 1, b = 2`
3607
- DIST_L2:
3608
    - `3 x 3`: `a=0.955, b=1.3693`
3609
    - `5 x 5`: `a=1, b=1.4, c=2.1969`
3610
- DIST_C: `a = 1, b = 1`
3611
3612
Typically, for a fast, coarse distance estimation #DIST_L2, a \f$3\times 3\f$ mask is used. For a
3613
more accurate distance estimation #DIST_L2, a \f$5\times 5\f$ mask or the precise algorithm is used.
3614
Note that both the precise and the approximate algorithms are linear on the number of pixels.
3615
3616
This variant of the function does not only compute the minimum distance for each pixel \f$(x, y)\f$
3617
but also identifies the nearest connected component consisting of zero pixels
3618
(labelType==#DIST_LABEL_CCOMP) or the nearest zero pixel (labelType==#DIST_LABEL_PIXEL). Index of the
3619
component/pixel is stored in `labels(x, y)`. When labelType==#DIST_LABEL_CCOMP, the function
3620
automatically finds connected components of zero pixels in the input image and marks them with
3621
distinct labels. When labelType==#DIST_LABEL_PIXEL, the function scans through the input image and
3622
marks all the zero pixels with distinct labels.
3623
3624
In this mode, the complexity is still linear. That is, the function provides a very fast way to
3625
compute the Voronoi diagram for a binary image. Currently, the second variant can use only the
3626
approximate distance transform algorithm, i.e. maskSize=#DIST_MASK_PRECISE is not supported
3627
yet.
3628
3629
@param src 8-bit, single-channel (binary) source image.
3630
@param dst Output image with calculated distances. It is a 8-bit or 32-bit floating-point,
3631
single-channel image of the same size as src.
3632
@param labels Output 2D array of labels (the discrete Voronoi diagram). It has the type
3633
CV_32SC1 and the same size as src.
3634
@param distanceType Type of distance, see #DistanceTypes
3635
@param maskSize Size of the distance transform mask, see #DistanceTransformMasks.
3636
#DIST_MASK_PRECISE is not supported by this variant. In case of the #DIST_L1 or #DIST_C distance type,
3637
the parameter is forced to 3 because a \f$3\times 3\f$ mask gives the same result as \f$5\times
3638
5\f$ or any larger aperture.
3639
@param labelType Type of the label array to build, see #DistanceTransformLabelTypes.
3640
 */
3641
CV_EXPORTS_AS(distanceTransformWithLabels) void distanceTransform( InputArray src, OutputArray dst,
3642
                                     OutputArray labels, int distanceType, int maskSize,
3643
                                     int labelType = DIST_LABEL_CCOMP );
3644
3645
/** @overload
3646
@param src 8-bit, single-channel (binary) source image.
3647
@param dst Output image with calculated distances. It is a 8-bit or 32-bit floating-point,
3648
single-channel image of the same size as src .
3649
@param distanceType Type of distance, see #DistanceTypes
3650
@param maskSize Size of the distance transform mask, see #DistanceTransformMasks. In case of the
3651
#DIST_L1 or #DIST_C distance type, the parameter is forced to 3 because a \f$3\times 3\f$ mask gives
3652
the same result as \f$5\times 5\f$ or any larger aperture.
3653
@param dstType Type of output image. It can be CV_8U or CV_32F. Type CV_8U can be used only for
3654
the first variant of the function and distanceType == #DIST_L1.
3655
*/
3656
CV_EXPORTS_W void distanceTransform( InputArray src, OutputArray dst,
3657
                                     int distanceType, int maskSize, int dstType=CV_32F);
3658
3659
/** @brief Fills a connected component with the given color.
3660
3661
The function cv::floodFill fills a connected component starting from the seed point with the specified
3662
color. The connectivity is determined by the color/brightness closeness of the neighbor pixels. The
3663
pixel at \f$(x,y)\f$ is considered to belong to the repainted domain if:
3664
3665
- in case of a grayscale image and floating range
3666
\f[\texttt{src} (x',y')- \texttt{loDiff} \leq \texttt{src} (x,y)  \leq \texttt{src} (x',y')+ \texttt{upDiff}\f]
3667
3668
3669
- in case of a grayscale image and fixed range
3670
\f[\texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)- \texttt{loDiff} \leq \texttt{src} (x,y)  \leq \texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)+ \texttt{upDiff}\f]
3671
3672
3673
- in case of a color image and floating range
3674
\f[\texttt{src} (x',y')_r- \texttt{loDiff} _r \leq \texttt{src} (x,y)_r \leq \texttt{src} (x',y')_r+ \texttt{upDiff} _r,\f]
3675
\f[\texttt{src} (x',y')_g- \texttt{loDiff} _g \leq \texttt{src} (x,y)_g \leq \texttt{src} (x',y')_g+ \texttt{upDiff} _g\f]
3676
and
3677
\f[\texttt{src} (x',y')_b- \texttt{loDiff} _b \leq \texttt{src} (x,y)_b \leq \texttt{src} (x',y')_b+ \texttt{upDiff} _b\f]
3678
3679
3680
- in case of a color image and fixed range
3681
\f[\texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_r- \texttt{loDiff} _r \leq \texttt{src} (x,y)_r \leq \texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_r+ \texttt{upDiff} _r,\f]
3682
\f[\texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_g- \texttt{loDiff} _g \leq \texttt{src} (x,y)_g \leq \texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_g+ \texttt{upDiff} _g\f]
3683
and
3684
\f[\texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_b- \texttt{loDiff} _b \leq \texttt{src} (x,y)_b \leq \texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_b+ \texttt{upDiff} _b\f]
3685
3686
3687
where \f$src(x',y')\f$ is the value of one of pixel neighbors that is already known to belong to the
3688
component. That is, to be added to the connected component, a color/brightness of the pixel should
3689
be close enough to:
3690
- Color/brightness of one of its neighbors that already belong to the connected component in case
3691
of a floating range.
3692
- Color/brightness of the seed point in case of a fixed range.
3693
3694
Use these functions to either mark a connected component with the specified color in-place, or build
3695
a mask and then extract the contour, or copy the region to another image, and so on.
3696
3697
@param image Input/output 1- or 3-channel, 8-bit, or floating-point image. It is modified by the
3698
function unless the #FLOODFILL_MASK_ONLY flag is set in the second variant of the function. See
3699
the details below.
3700
@param mask Operation mask that should be a single-channel 8-bit image, 2 pixels wider and 2 pixels
3701
taller than image. If an empty Mat is passed it will be created automatically. Since this is both an
3702
input and output parameter, you must take responsibility of initializing it.
3703
Flood-filling cannot go across non-zero pixels in the input mask. For example,
3704
an edge detector output can be used as a mask to stop filling at edges. On output, pixels in the
3705
mask corresponding to filled pixels in the image are set to 1 or to the specified value in flags
3706
as described below. Additionally, the function fills the border of the mask with ones to simplify
3707
internal processing. It is therefore possible to use the same mask in multiple calls to the function
3708
to make sure the filled areas do not overlap.
3709
@param seedPoint Starting point.
3710
@param newVal New value of the repainted domain pixels.
3711
@param loDiff Maximal lower brightness/color difference between the currently observed pixel and
3712
one of its neighbors belonging to the component, or a seed pixel being added to the component.
3713
@param upDiff Maximal upper brightness/color difference between the currently observed pixel and
3714
one of its neighbors belonging to the component, or a seed pixel being added to the component.
3715
@param rect Optional output parameter set by the function to the minimum bounding rectangle of the
3716
repainted domain.
3717
@param flags Operation flags. The first 8 bits contain a connectivity value. The default value of
3718
4 means that only the four nearest neighbor pixels (those that share an edge) are considered. A
3719
connectivity value of 8 means that the eight nearest neighbor pixels (those that share a corner)
3720
will be considered. The next 8 bits (8-16) contain a value between 1 and 255 with which to fill
3721
the mask (the default value is 1). For example, 4 | ( 255 \<\< 8 ) will consider 4 nearest
3722
neighbours and fill the mask with a value of 255. The following additional options occupy higher
3723
bits and therefore may be further combined with the connectivity and mask fill values using
3724
bit-wise or (|), see #FloodFillFlags.
3725
3726
@note Since the mask is larger than the filled image, a pixel \f$(x, y)\f$ in image corresponds to the
3727
pixel \f$(x+1, y+1)\f$ in the mask .
3728
3729
@sa findContours
3730
 */
3731
CV_EXPORTS_W int floodFill( InputOutputArray image, InputOutputArray mask,
3732
                            Point seedPoint, Scalar newVal, CV_OUT Rect* rect=0,
3733
                            Scalar loDiff = Scalar(), Scalar upDiff = Scalar(),
3734
                            int flags = 4 );
3735
3736
/** @example samples/cpp/ffilldemo.cpp
3737
An example using the FloodFill technique
3738
*/
3739
3740
/** @overload
3741
3742
variant without `mask` parameter
3743
*/
3744
CV_EXPORTS int floodFill( InputOutputArray image,
3745
                          Point seedPoint, Scalar newVal, CV_OUT Rect* rect = 0,
3746
                          Scalar loDiff = Scalar(), Scalar upDiff = Scalar(),
3747
                          int flags = 4 );
3748
3749
//! Performs linear blending of two images:
3750
//! \f[ \texttt{dst}(i,j) = \texttt{weights1}(i,j)*\texttt{src1}(i,j) + \texttt{weights2}(i,j)*\texttt{src2}(i,j) \f]
3751
//! @param src1 It has a type of CV_8UC(n) or CV_32FC(n), where n is a positive integer.
3752
//! @param src2 It has the same type and size as src1.
3753
//! @param weights1 It has a type of CV_32FC1 and the same size with src1.
3754
//! @param weights2 It has a type of CV_32FC1 and the same size with src1.
3755
//! @param dst It is created if it does not have the same size and type with src1.
3756
CV_EXPORTS_W void blendLinear(InputArray src1, InputArray src2, InputArray weights1, InputArray weights2, OutputArray dst);
3757
3758
//! @} imgproc_misc
3759
3760
//! @addtogroup imgproc_color_conversions
3761
//! @{
3762
3763
/** @brief Converts an image from one color space to another.
3764
3765
The function converts an input image from one color space to another. In case of a transformation
3766
to-from RGB color space, the order of the channels should be specified explicitly (RGB or BGR). Note
3767
that the default color format in OpenCV is often referred to as RGB but it is actually BGR (the
3768
bytes are reversed). So the first byte in a standard (24-bit) color image will be an 8-bit Blue
3769
component, the second byte will be Green, and the third byte will be Red. The fourth, fifth, and
3770
sixth bytes would then be the second pixel (Blue, then Green, then Red), and so on.
3771
3772
The conventional ranges for R, G, and B channel values are:
3773
-   0 to 255 for CV_8U images
3774
-   0 to 65535 for CV_16U images
3775
-   0 to 1 for CV_32F images
3776
3777
In case of linear transformations, the range does not matter. But in case of a non-linear
3778
transformation, an input RGB image should be normalized to the proper value range to get the correct
3779
results, for example, for RGB \f$\rightarrow\f$ L\*u\*v\* transformation. For example, if you have a
3780
32-bit floating-point image directly converted from an 8-bit image without any scaling, then it will
3781
have the 0..255 value range instead of 0..1 assumed by the function. So, before calling #cvtColor ,
3782
you need first to scale the image down:
3783
@code
3784
    img *= 1./255;
3785
    cvtColor(img, img, COLOR_BGR2Luv);
3786
@endcode
3787
If you use #cvtColor with 8-bit images, the conversion will have some information lost. For many
3788
applications, this will not be noticeable but it is recommended to use 32-bit images in applications
3789
that need the full range of colors or that convert an image before an operation and then convert
3790
back.
3791
3792
If conversion adds the alpha channel, its value will set to the maximum of corresponding channel
3793
range: 255 for CV_8U, 65535 for CV_16U, 1 for CV_32F.
3794
3795
@param src input image: 8-bit unsigned, 16-bit unsigned ( CV_16UC... ), or single-precision
3796
floating-point. The accepted depths differ between conversions and are listed with each code in
3797
#ColorConversionCodes: for example #COLOR_BGR2GRAY is marked `[8U/16U/32F]`, while
3798
#COLOR_BGR2HSV is marked `[8U/32F]` and rejects `CV_16U`.
3799
@param dst output image of the same size and depth as src.
3800
@param code color space conversion code (see #ColorConversionCodes).
3801
@param dstCn number of channels in the destination image; if the parameter is 0, the number of the
3802
channels is derived automatically from src and code.
3803
@param hint Implementation modfication flags. See #AlgorithmHint
3804
3805
@see @ref imgproc_color_conversions
3806
 */
3807
CV_EXPORTS_W void cvtColor( InputArray src, OutputArray dst, int code, int dstCn = 0, AlgorithmHint hint = cv::ALGO_HINT_DEFAULT );
3808
3809
/** @brief Converts an image from one color space to another where the source image is
3810
stored in two planes.
3811
3812
This function only supports YUV420 to RGB conversion as of now.
3813
3814
@param src1 8-bit image (#CV_8U) of the Y plane.
3815
@param src2 image containing interleaved U/V plane.
3816
@param dst output image.
3817
@param code Specifies the type of conversion. It can take any of the following values:
3818
- #COLOR_YUV2BGR_NV12
3819
- #COLOR_YUV2RGB_NV12
3820
- #COLOR_YUV2BGRA_NV12
3821
- #COLOR_YUV2RGBA_NV12
3822
- #COLOR_YUV2BGR_NV21
3823
- #COLOR_YUV2RGB_NV21
3824
- #COLOR_YUV2BGRA_NV21
3825
- #COLOR_YUV2RGBA_NV21
3826
@param hint Implementation modfication flags. See #AlgorithmHint
3827
*/
3828
CV_EXPORTS_W void cvtColorTwoPlane( InputArray src1, InputArray src2, OutputArray dst, int code, AlgorithmHint hint = cv::ALGO_HINT_DEFAULT );
3829
3830
/** @brief main function for all demosaicing processes
3831
3832
@param src input image: 8-bit unsigned or 16-bit unsigned. The accepted depths differ between
3833
codes and are listed with each code in #ColorConversionCodes: the Variable Number of Gradients
3834
codes such as #COLOR_BayerBG2BGR_VNG are marked `[8U]` and reject `CV_16U`, while for example
3835
#COLOR_BayerBG2BGR is marked `[8U/16U]`.
3836
@param dst output image of the same size and depth as src.
3837
@param code Color space conversion code (see the description below).
3838
@param dstCn number of channels in the destination image; if the parameter is 0, the number of the
3839
channels is derived automatically from src and code.
3840
3841
The function can do the following transformations:
3842
3843
-   Demosaicing using bilinear interpolation
3844
3845
    #COLOR_BayerBG2BGR , #COLOR_BayerGB2BGR , #COLOR_BayerRG2BGR , #COLOR_BayerGR2BGR
3846
3847
    #COLOR_BayerBG2GRAY , #COLOR_BayerGB2GRAY , #COLOR_BayerRG2GRAY , #COLOR_BayerGR2GRAY
3848
3849
-   Demosaicing using Variable Number of Gradients.
3850
3851
    #COLOR_BayerBG2BGR_VNG , #COLOR_BayerGB2BGR_VNG , #COLOR_BayerRG2BGR_VNG , #COLOR_BayerGR2BGR_VNG
3852
3853
-   Edge-Aware Demosaicing.
3854
3855
    #COLOR_BayerBG2BGR_EA , #COLOR_BayerGB2BGR_EA , #COLOR_BayerRG2BGR_EA , #COLOR_BayerGR2BGR_EA
3856
3857
-   Demosaicing with alpha channel
3858
3859
    #COLOR_BayerBG2BGRA , #COLOR_BayerGB2BGRA , #COLOR_BayerRG2BGRA , #COLOR_BayerGR2BGRA
3860
3861
@sa cvtColor
3862
*/
3863
CV_EXPORTS_W void demosaicing(InputArray src, OutputArray dst, int code, int dstCn = 0);
3864
3865
//! @} imgproc_color_conversions
3866
3867
//! @addtogroup imgproc_shape
3868
//! @{
3869
3870
/** @brief Calculates all of the moments up to the third order of a polygon or rasterized shape.
3871
3872
The function computes moments, up to the 3rd order, of a vector shape or a rasterized shape. The
3873
results are returned in the structure cv::Moments.
3874
3875
@param array Single channel raster image (CV_8U, CV_16U, CV_16S, CV_32F, CV_64F) or an array (
3876
\f$1 \times N\f$ or \f$N \times 1\f$ ) of 2D points (Point or Point2f).
3877
@param binaryImage If it is true, all non-zero image pixels are treated as 1's. The parameter is
3878
used for images only.
3879
@returns moments.
3880
3881
@note Only applicable to contour moments calculations from Python bindings: Note that the numpy
3882
type for the input array should be either np.int32 or np.float32.
3883
3884
@note For contour-based moments, the zeroth-order moment \c m00 represents
3885
the contour area.
3886
3887
If the input contour is degenerate (for example, a single point or all points
3888
are collinear), the area is zero and therefore \c m00 == 0.
3889
3890
In this case, the centroid coordinates (\c m10/m00, \c m01/m00) are undefined
3891
and must be handled explicitly by the caller.
3892
3893
A common workaround is to compute the center using cv::boundingRect() or by
3894
averaging the input points.
3895
3896
@sa  contourArea, arcLength
3897
 */
3898
CV_EXPORTS_W Moments moments( InputArray array, bool binaryImage = false );
3899
3900
/** @brief Calculates seven Hu invariants.
3901
3902
The function calculates seven Hu invariants (introduced in @cite Hu62; see also
3903
<https://en.wikipedia.org/wiki/Image_moment>) defined as:
3904
3905
\f[\begin{array}{l} hu[0]= \eta _{20}+ \eta _{02} \\ hu[1]=( \eta _{20}- \eta _{02})^{2}+4 \eta _{11}^{2} \\ hu[2]=( \eta _{30}-3 \eta _{12})^{2}+ (3 \eta _{21}- \eta _{03})^{2} \\ hu[3]=( \eta _{30}+ \eta _{12})^{2}+ ( \eta _{21}+ \eta _{03})^{2} \\ hu[4]=( \eta _{30}-3 \eta _{12})( \eta _{30}+ \eta _{12})[( \eta _{30}+ \eta _{12})^{2}-3( \eta _{21}+ \eta _{03})^{2}]+(3 \eta _{21}- \eta _{03})( \eta _{21}+ \eta _{03})[3( \eta _{30}+ \eta _{12})^{2}-( \eta _{21}+ \eta _{03})^{2}] \\ hu[5]=( \eta _{20}- \eta _{02})[( \eta _{30}+ \eta _{12})^{2}- ( \eta _{21}+ \eta _{03})^{2}]+4 \eta _{11}( \eta _{30}+ \eta _{12})( \eta _{21}+ \eta _{03}) \\ hu[6]=(3 \eta _{21}- \eta _{03})( \eta _{21}+ \eta _{03})[3( \eta _{30}+ \eta _{12})^{2}-( \eta _{21}+ \eta _{03})^{2}]-( \eta _{30}-3 \eta _{12})( \eta _{21}+ \eta _{03})[3( \eta _{30}+ \eta _{12})^{2}-( \eta _{21}+ \eta _{03})^{2}] \\ \end{array}\f]
3906
3907
where \f$\eta_{ji}\f$ stands for \f$\texttt{Moments::nu}_{ji}\f$ .
3908
3909
These values are proved to be invariants to the image scale, rotation, and reflection except the
3910
seventh one, whose sign is changed by reflection. This invariance is proved with the assumption of
3911
infinite image resolution. In case of raster images, the computed Hu invariants for the original and
3912
transformed images are a bit different.
3913
3914
@param moments Input moments computed with moments .
3915
@param hu Output Hu invariants.
3916
3917
@sa matchShapes
3918
 */
3919
CV_EXPORTS void HuMoments( const Moments& moments, double hu[7] );
3920
3921
/** @overload */
3922
CV_EXPORTS_W void HuMoments( const Moments& m, OutputArray hu );
3923
3924
//! @} imgproc_shape
3925
3926
//! @addtogroup imgproc_object
3927
//! @{
3928
3929
//! type of the template matching operation
3930
enum TemplateMatchModes {
3931
    TM_SQDIFF        = 0, /*!< \f[R(x,y)= \sum _{x',y'} (T(x',y')-I(x+x',y+y'))^2\f]
3932
                               with mask:
3933
                               \f[R(x,y)= \sum _{x',y'} \left( (T(x',y')-I(x+x',y+y')) \cdot
3934
                                  M(x',y') \right)^2\f] */
3935
    TM_SQDIFF_NORMED = 1, /*!< \f[R(x,y)= \frac{\sum_{x',y'} (T(x',y')-I(x+x',y+y'))^2}{\sqrt{\sum_{
3936
                                  x',y'}T(x',y')^2 \cdot \sum_{x',y'} I(x+x',y+y')^2}}\f]
3937
                               with mask:
3938
                               \f[R(x,y)= \frac{\sum _{x',y'} \left( (T(x',y')-I(x+x',y+y')) \cdot
3939
                                  M(x',y') \right)^2}{\sqrt{\sum_{x',y'} \left( T(x',y') \cdot
3940
                                  M(x',y') \right)^2 \cdot \sum_{x',y'} \left( I(x+x',y+y') \cdot
3941
                                  M(x',y') \right)^2}}\f] */
3942
    TM_CCORR         = 2, /*!< \f[R(x,y)= \sum _{x',y'} (T(x',y') \cdot I(x+x',y+y'))\f]
3943
                               with mask:
3944
                               \f[R(x,y)= \sum _{x',y'} (T(x',y') \cdot I(x+x',y+y') \cdot M(x',y')
3945
                                  ^2)\f] */
3946
    TM_CCORR_NORMED  = 3, /*!< \f[R(x,y)= \frac{\sum_{x',y'} (T(x',y') \cdot I(x+x',y+y'))}{\sqrt{
3947
                                  \sum_{x',y'}T(x',y')^2 \cdot \sum_{x',y'} I(x+x',y+y')^2}}\f]
3948
                               with mask:
3949
                               \f[R(x,y)= \frac{\sum_{x',y'} (T(x',y') \cdot I(x+x',y+y') \cdot
3950
                                  M(x',y')^2)}{\sqrt{\sum_{x',y'} \left( T(x',y') \cdot M(x',y')
3951
                                  \right)^2 \cdot \sum_{x',y'} \left( I(x+x',y+y') \cdot M(x',y')
3952
                                  \right)^2}}\f] */
3953
    TM_CCOEFF        = 4, /*!< \f[R(x,y)= \sum _{x',y'} (T'(x',y') \cdot I'(x+x',y+y'))\f]
3954
                               where
3955
                               \f[\begin{array}{l} T'(x',y')=T(x',y') - 1/(w \cdot h) \cdot \sum _{
3956
                                  x'',y''} T(x'',y'') \\ I'(x+x',y+y')=I(x+x',y+y') - 1/(w \cdot h)
3957
                                  \cdot \sum _{x'',y''} I(x+x'',y+y'') \end{array}\f]
3958
                               with mask:
3959
                               \f[\begin{array}{l} T'(x',y')=M(x',y') \cdot \left( T(x',y') -
3960
                                  \frac{1}{\sum _{x'',y''} M(x'',y'')} \cdot \sum _{x'',y''}
3961
                                  (T(x'',y'') \cdot M(x'',y'')) \right) \\ I'(x+x',y+y')=M(x',y')
3962
                                  \cdot \left( I(x+x',y+y') - \frac{1}{\sum _{x'',y''} M(x'',y'')}
3963
                                  \cdot \sum _{x'',y''} (I(x+x'',y+y'') \cdot M(x'',y'')) \right)
3964
                                  \end{array} \f] */
3965
    TM_CCOEFF_NORMED = 5  /*!< \f[R(x,y)= \frac{ \sum_{x',y'} (T'(x',y') \cdot I'(x+x',y+y')) }{
3966
                                  \sqrt{\sum_{x',y'}T'(x',y')^2 \cdot \sum_{x',y'} I'(x+x',y+y')^2}
3967
                                  }\f] */
3968
};
3969
3970
/** @example samples/cpp/tutorial_code/Histograms_Matching/MatchTemplate_Demo.cpp
3971
An example using Template Matching algorithm
3972
*/
3973
3974
/** @brief Compares a template against overlapped image regions.
3975
3976
The function slides through image , compares the overlapped patches of size \f$w \times h\f$ against
3977
templ using the specified method and stores the comparison results in result . #TemplateMatchModes
3978
describes the formulae for the available comparison methods ( \f$I\f$ denotes image, \f$T\f$
3979
template, \f$R\f$ result, \f$M\f$ the optional mask ). The summation is done over template and/or
3980
the image patch: \f$x' = 0...w-1, y' = 0...h-1\f$
3981
3982
After the function finishes the comparison, the best matches can be found as global minimums (when
3983
#TM_SQDIFF was used) or maximums (when #TM_CCORR or #TM_CCOEFF was used) using the
3984
#minMaxLoc function. In case of a color image, template summation in the numerator and each sum in
3985
the denominator is done over all of the channels and separate mean values are used for each channel.
3986
That is, the function can take a color template and a color image. The result will still be a
3987
single-channel image, which is easier to analyze.
3988
3989
@param image Image where the search is running. It must be 8-bit or 32-bit floating-point.
3990
@param templ Searched template. It must be not greater than the source image and have the same
3991
data type.
3992
@param result Map of comparison results. It must be single-channel 32-bit floating-point. If image
3993
is \f$W \times H\f$ and templ is \f$w \times h\f$ , then result is \f$(W-w+1) \times (H-h+1)\f$ .
3994
@param method Parameter specifying the comparison method, see #TemplateMatchModes
3995
@param mask Optional mask. It must have the same size as templ. It must either have the same number
3996
            of channels as template or only one channel, which is then used for all template and
3997
            image channels. If the data type is #CV_8U, the mask is interpreted as a binary mask,
3998
            meaning only elements where mask is nonzero are used and are kept unchanged independent
3999
            of the actual mask value (weight equals 1). For data type #CV_32F, the mask values are
4000
            used as weights. The exact formulas are documented in #TemplateMatchModes.
4001
 */
4002
CV_EXPORTS_W void matchTemplate( InputArray image, InputArray templ,
4003
                                 OutputArray result, int method, InputArray mask = noArray() );
4004
4005
//! @}
4006
4007
//! @addtogroup imgproc_shape
4008
//! @{
4009
4010
/** @example samples/cpp/connected_components.cpp
4011
This program demonstrates connected components and use of the trackbar
4012
*/
4013
4014
/** @brief computes the connected components labeled image of boolean image
4015
4016
image with 4 or 8 way connectivity - returns N, the total number of labels [0, N-1] where 0
4017
represents the background label. ltype specifies the output label image type, an important
4018
consideration based on the total number of labels or alternatively the total number of pixels in
4019
the source image. ccltype specifies the connected components labeling algorithm to use, currently
4020
Bolelli (Spaghetti) @cite Bolelli2019, Grana (BBDT) @cite Grana2010 and Wu's (SAUF) @cite Wu2009 algorithms
4021
are supported, see the #ConnectedComponentsAlgorithmsTypes for details. Note that SAUF algorithm forces
4022
a row major ordering of labels while Spaghetti and BBDT do not.
4023
This function uses parallel version of the algorithms if at least one allowed
4024
parallel framework is enabled and if the rows of the image are at least twice the number returned by #getNumberOfCPUs.
4025
4026
@param image the 8-bit single-channel image to be labeled
4027
@param labels destination labeled image
4028
@param connectivity 8 or 4 for 8-way or 4-way connectivity respectively
4029
@param ltype output image label type. Currently CV_32S and CV_16U are supported.
4030
@param ccltype connected components algorithm type (see the #ConnectedComponentsAlgorithmsTypes).
4031
*/
4032
CV_EXPORTS_AS(connectedComponentsWithAlgorithm) int connectedComponents(InputArray image, OutputArray labels,
4033
                                                                        int connectivity, int ltype, int ccltype);
4034
4035
4036
/** @overload
4037
4038
@param image the 8-bit single-channel image to be labeled
4039
@param labels destination labeled image
4040
@param connectivity 8 or 4 for 8-way or 4-way connectivity respectively
4041
@param ltype output image label type. Currently CV_32S and CV_16U are supported.
4042
*/
4043
CV_EXPORTS_W int connectedComponents(InputArray image, OutputArray labels,
4044
                                     int connectivity = 8, int ltype = CV_32S);
4045
4046
4047
/** @brief computes the connected components labeled image of boolean image and also produces a statistics output for each label
4048
4049
image with 4 or 8 way connectivity - returns N, the total number of labels [0, N-1] where 0
4050
represents the background label. ltype specifies the output label image type, an important
4051
consideration based on the total number of labels or alternatively the total number of pixels in
4052
the source image. ccltype specifies the connected components labeling algorithm to use, currently
4053
Bolelli (Spaghetti) @cite Bolelli2019, Grana (BBDT) @cite Grana2010 and Wu's (SAUF) @cite Wu2009 algorithms
4054
are supported, see the #ConnectedComponentsAlgorithmsTypes for details. Note that SAUF algorithm forces
4055
a row major ordering of labels while Spaghetti and BBDT do not.
4056
This function uses parallel version of the algorithms (statistics included) if at least one allowed
4057
parallel framework is enabled and if the rows of the image are at least twice the number returned by #getNumberOfCPUs.
4058
4059
@param image the 8-bit single-channel image to be labeled
4060
@param labels destination labeled image
4061
@param stats statistics output for each label, including the background label.
4062
Statistics are accessed via stats(label, COLUMN) where COLUMN is one of
4063
#ConnectedComponentsTypes, selecting the statistic. The data type is CV_32S.
4064
@param centroids centroid output for each label, including the background label. Centroids are
4065
accessed via centroids(label, 0) for x and centroids(label, 1) for y. The data type CV_64F.
4066
@param connectivity 8 or 4 for 8-way or 4-way connectivity respectively
4067
@param ltype output image label type. Currently CV_32S and CV_16U are supported.
4068
@param ccltype connected components algorithm type (see #ConnectedComponentsAlgorithmsTypes).
4069
*/
4070
CV_EXPORTS_AS(connectedComponentsWithStatsWithAlgorithm) int connectedComponentsWithStats(InputArray image, OutputArray labels,
4071
                                                                                          OutputArray stats, OutputArray centroids,
4072
                                                                                          int connectivity, int ltype, int ccltype);
4073
4074
/** @overload
4075
@param image the 8-bit single-channel image to be labeled
4076
@param labels destination labeled image
4077
@param stats statistics output for each label, including the background label.
4078
Statistics are accessed via stats(label, COLUMN) where COLUMN is one of
4079
#ConnectedComponentsTypes, selecting the statistic. The data type is CV_32S.
4080
@param centroids centroid output for each label, including the background label. Centroids are
4081
accessed via centroids(label, 0) for x and centroids(label, 1) for y. The data type CV_64F.
4082
@param connectivity 8 or 4 for 8-way or 4-way connectivity respectively
4083
@param ltype output image label type. Currently CV_32S and CV_16U are supported.
4084
*/
4085
CV_EXPORTS_W int connectedComponentsWithStats(InputArray image, OutputArray labels,
4086
                                              OutputArray stats, OutputArray centroids,
4087
                                              int connectivity = 8, int ltype = CV_32S);
4088
4089
4090
/** @brief Finds contours in a binary image.
4091
4092
The function retrieves contours from the binary image. The contours
4093
are a useful tool for shape analysis and object detection and recognition. See squares.cpp in the
4094
OpenCV sample directory.
4095
4096
@note Since OpenCV 4.14, when mode is #RETR_LIST and no hierarchy is requested, this function
4097
automatically uses the TRUCO parallel algorithm @cite TRUCO2026, a scalable lock-free method for
4098
contour extraction. In all other cases, the sequential @cite Suzuki85 algorithm is used.
4099
4100
@note Since opencv 3.2 source image is not modified by this function.
4101
4102
@param image Source, an 8-bit single-channel image. Non-zero pixels are treated as 1's. Zero
4103
pixels remain 0's, so the image is treated as binary . You can use #compare, #inRange, #threshold ,
4104
#adaptiveThreshold, #Canny, and others to create a binary image out of a grayscale or color one.
4105
If mode equals to #RETR_CCOMP or #RETR_FLOODFILL, the input can also be a 32-bit integer image of labels (CV_32SC1).
4106
@param contours Detected contours. Each contour is stored as a vector of points (e.g.
4107
std::vector<std::vector<cv::Point> >).
4108
@param hierarchy Optional output vector (e.g. std::vector<cv::Vec4i>), containing information about the image topology. It has
4109
as many elements as the number of contours. For each i-th contour contours[i], the elements
4110
hierarchy[i][0] , hierarchy[i][1] , hierarchy[i][2] , and hierarchy[i][3] are set to 0-based indices
4111
in contours of the next and previous contours at the same hierarchical level, the first child
4112
contour and the parent contour, respectively. If for the contour i there are no next, previous,
4113
parent, or nested contours, the corresponding elements of hierarchy[i] will be negative.
4114
@note In Python, hierarchy is nested inside a top level array. Use hierarchy[0][i] to access hierarchical elements of i-th contour.
4115
@param mode Contour retrieval mode, see #RetrievalModes
4116
@param method Contour approximation method, see #ContourApproximationModes
4117
@param offset Optional offset by which every contour point is shifted. This is useful if the
4118
contours are extracted from the image ROI and then they should be analyzed in the whole image
4119
context.
4120
 */
4121
CV_EXPORTS_W void findContours( InputArray image, OutputArrayOfArrays contours,
4122
                              OutputArray hierarchy, int mode,
4123
                              int method, Point offset = Point());
4124
4125
/** @overload */
4126
CV_EXPORTS void findContours( InputArray image, OutputArrayOfArrays contours,
4127
                              int mode, int method, Point offset = Point());
4128
4129
4130
//! @brief Find contours using link runs algorithm
4131
//!
4132
//! This function implements an algorithm different from cv::findContours:
4133
//! - doesn't allocate temporary image internally, thus it has reduced memory consumption
4134
//! - supports CV_8UC1 images only
4135
//! - outputs 2-level hierarhy only (RETR_CCOMP mode)
4136
//! - doesn't support approximation change other than CHAIN_APPROX_SIMPLE
4137
//! In all other aspects this function is compatible with cv::findContours.
4138
CV_EXPORTS_W void findContoursLinkRuns(InputArray image, OutputArrayOfArrays contours, OutputArray hierarchy);
4139
4140
//! @overload
4141
CV_EXPORTS_W void findContoursLinkRuns(InputArray image, OutputArrayOfArrays contours);
4142
4143
4144
/** @brief Approximates a polygonal curve(s) with the specified precision.
4145
4146
The function cv::approxPolyDP approximates a curve or a polygon with another curve/polygon with less
4147
vertices so that the distance between them is less or equal to the specified precision. It uses the
4148
Douglas-Peucker algorithm <https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm>
4149
4150
@param curve Input vector of a 2D point stored in std::vector or Mat
4151
@param approxCurve Result of the approximation. The type should match the type of the input curve.
4152
@param epsilon Parameter specifying the approximation accuracy. This is the maximum distance
4153
between the original curve and its approximation.
4154
@param closed If true, the approximated curve is closed (its first and last vertices are
4155
connected). Otherwise, it is not closed.
4156
 */
4157
CV_EXPORTS_W void approxPolyDP( InputArray curve,
4158
                                OutputArray approxCurve,
4159
                                double epsilon, bool closed );
4160
4161
/** @brief Approximates a polygon with a convex hull with a specified accuracy and number of sides.
4162
4163
The cv::approxPolyN function approximates a polygon with a convex hull
4164
so that the difference between the contour area of the original contour and the new polygon is minimal.
4165
It uses a greedy algorithm for contracting two vertices into one in such a way that the additional area is minimal.
4166
Straight lines formed by each edge of the convex contour are drawn and the areas of the resulting triangles are considered.
4167
Each vertex will lie either on the original contour or outside it.
4168
4169
The algorithm based on the paper @cite LowIlie2003 .
4170
4171
@param curve Input vector of a 2D points stored in std::vector or Mat, points must be float or integer.
4172
@param approxCurve Result of the approximation. The type is vector of a 2D point (Point2f or Point) in std::vector or Mat.
4173
@param nsides The parameter defines the number of sides of the result polygon.
4174
@param epsilon_percentage defines the percentage of the maximum of additional area.
4175
If it equals -1, it is not used. Otherwise algorithm stops if additional area is greater than contourArea(_curve) * percentage.
4176
If additional area exceeds the limit, algorithm returns as many vertices as there were at the moment the limit was exceeded.
4177
@param ensure_convex If it is true, algorithm creates a convex hull of input contour. Otherwise input vector should be convex.
4178
 */
4179
CV_EXPORTS_W void approxPolyN(InputArray curve, OutputArray approxCurve,
4180
                              int nsides, float epsilon_percentage = -1.0,
4181
                              bool ensure_convex = true);
4182
4183
/** @brief Calculates a contour perimeter or a curve length.
4184
4185
The function computes a curve length or a closed contour perimeter.
4186
4187
@param curve Input vector of 2D points, stored in std::vector or Mat.
4188
@param closed Flag indicating whether the curve is closed or not.
4189
 */
4190
CV_EXPORTS_W double arcLength( InputArray curve, bool closed );
4191
4192
/** @brief Calculates the up-right bounding rectangle of a point set or non-zero pixels of gray-scale image.
4193
4194
The function calculates and returns the minimal up-right bounding rectangle for the specified point set or
4195
non-zero pixels of gray-scale image.
4196
4197
@param array Input gray-scale image or 2D point set, stored in std::vector or Mat.
4198
 */
4199
CV_EXPORTS_W Rect boundingRect( InputArray array );
4200
4201
/** @brief Calculates a contour area.
4202
4203
The function computes a contour area. Similarly to moments , the area is computed using the Green
4204
formula. Thus, the returned area and the number of non-zero pixels, if you draw the contour using
4205
#drawContours or #fillPoly , can be different. Also, the function will most certainly give a wrong
4206
results for contours with self-intersections.
4207
4208
Example:
4209
@code
4210
    vector<Point> contour;
4211
    contour.push_back(Point2f(0, 0));
4212
    contour.push_back(Point2f(10, 0));
4213
    contour.push_back(Point2f(10, 10));
4214
    contour.push_back(Point2f(5, 4));
4215
4216
    double area0 = contourArea(contour);
4217
    vector<Point> approx;
4218
    approxPolyDP(contour, approx, 5, true);
4219
    double area1 = contourArea(approx);
4220
4221
    cout << "area0 =" << area0 << endl <<
4222
            "area1 =" << area1 << endl <<
4223
            "approx poly vertices" << approx.size() << endl;
4224
@endcode
4225
@param contour Input vector of 2D points (contour vertices), stored in std::vector or Mat.
4226
@param oriented Oriented area flag. If it is true, the function returns a signed area value,
4227
depending on the contour orientation (clockwise or counter-clockwise). Using this feature you can
4228
determine orientation of a contour by taking the sign of an area. By default, the parameter is
4229
false, which means that the absolute value is returned.
4230
 */
4231
CV_EXPORTS_W double contourArea( InputArray contour, bool oriented = false );
4232
4233
/** @brief Finds a rotated rectangle of the minimum area enclosing the input 2D point set.
4234
4235
The function calculates and returns the minimum-area bounding rectangle (possibly rotated) for a
4236
specified point set. The angle of rotation represents the angle between the line connecting the starting
4237
and ending points (based on the clockwise order with greatest index for the corner with greatest \f$y\f$)
4238
and the horizontal axis. This angle always falls between \f$[-90, 0)\f$ because, if the object
4239
rotates more than a rect angle, the next edge is used to measure the angle. The starting and ending points change
4240
as the object rotates.Developer should keep in mind that the returned RotatedRect can contain negative
4241
indices when data is close to the containing Mat element boundary.
4242
4243
@param points Input vector of 2D points, stored in std::vector\<\> or Mat
4244
 */
4245
CV_EXPORTS_W RotatedRect minAreaRect( InputArray points );
4246
4247
/** @brief Finds the four vertices of a rotated rect. Useful to draw the rotated rectangle.
4248
4249
The function finds the four vertices of a rotated rectangle. The four vertices are returned
4250
in clockwise order starting from the point with greatest \f$y\f$. If two points have the
4251
same \f$y\f$ coordinate the rightmost is the starting point. This function is useful to draw the
4252
rectangle. In C++, instead of using this function, you can directly use RotatedRect::points method. Please
4253
visit the @ref tutorial_bounding_rotated_ellipses "tutorial on Creating Bounding rotated boxes and ellipses
4254
for contours" for more information.
4255
4256
@param box The input rotated rectangle. It may be the output of @ref minAreaRect.
4257
@param points The output array of four vertices of rectangles.
4258
 */
4259
CV_EXPORTS_W void boxPoints(RotatedRect box, OutputArray points);
4260
4261
/** @brief Finds a circle of the minimum area enclosing a 2D point set.
4262
4263
The function finds the minimal enclosing circle of a 2D point set using an iterative algorithm.
4264
4265
@param points Input vector of 2D points, stored in std::vector\<\> or Mat
4266
@param center Output center of the circle.
4267
@param radius Output radius of the circle.
4268
 */
4269
CV_EXPORTS_W void minEnclosingCircle( InputArray points,
4270
                                      CV_OUT Point2f& center, CV_OUT float& radius );
4271
4272
/** @example samples/cpp/minarea.cpp
4273
*/
4274
4275
/** @brief Finds a triangle of minimum area enclosing a 2D point set and returns its area.
4276
4277
The function finds a triangle of minimum area enclosing the given set of 2D points and returns its
4278
area. The output for a given 2D point set is shown in the image below. 2D points are depicted in
4279
*red* and the enclosing triangle in *yellow*.
4280
4281
![Sample output of the minimum enclosing triangle function](pics/minenclosingtriangle.png)
4282
4283
The implementation of the algorithm is based on O'Rourke's @cite ORourke86 and Klee and Laskowski's
4284
@cite KleeLaskowski85 papers. O'Rourke provides a \f$\theta(n)\f$ algorithm for finding the minimal
4285
enclosing triangle of a 2D convex polygon with n vertices. Since the #minEnclosingTriangle function
4286
takes a 2D point set as input an additional preprocessing step of computing the convex hull of the
4287
2D point set is required. The complexity of the #convexHull function is \f$O(n log(n))\f$ which is higher
4288
than \f$\theta(n)\f$. Thus the overall complexity of the function is \f$O(n log(n))\f$.
4289
4290
@param points Input vector of 2D points with depth CV_32S or CV_32F, stored in std::vector\<\> or Mat
4291
@param triangle Output vector of three 2D points defining the vertices of the triangle. The depth
4292
of the OutputArray must be CV_32F.
4293
 */
4294
CV_EXPORTS_W double minEnclosingTriangle( InputArray points, CV_OUT OutputArray triangle );
4295
4296
4297
/**
4298
@brief Finds a convex polygon of minimum area enclosing a 2D point set and returns its area.
4299
4300
This function takes a given set of 2D points and finds the enclosing polygon with k vertices and minimal
4301
area. It takes the set of points and the parameter k as input and returns the area of the minimal
4302
enclosing polygon.
4303
4304
The Implementation is based on a paper by Aggarwal, Chang and Yap @cite Aggarwal1985. They
4305
provide a \f$\theta(n²log(n)log(k))\f$ algorithm for finding the minimal convex polygon with k
4306
vertices enclosing a 2D convex polygon with n vertices (k < n). Since the #minEnclosingConvexPolygon
4307
function takes a 2D point set as input, an additional preprocessing step of computing the convex hull
4308
of the 2D point set is required. The complexity of the #convexHull function is \f$O(n log(n))\f$ which
4309
is lower than \f$\theta(n²log(n)log(k))\f$. Thus the overall complexity of the function is
4310
\f$O(n²log(n)log(k))\f$.
4311
4312
@param points   Input vector of 2D points, stored in std::vector\<\> or Mat
4313
@param polygon  Output vector of 2D points defining the vertices of the enclosing polygon
4314
@param k        Number of vertices of the output polygon
4315
 */
4316
4317
CV_EXPORTS_W double minEnclosingConvexPolygon ( InputArray points, OutputArray polygon, int k );
4318
4319
4320
/** @brief Compares two shapes.
4321
4322
The function compares two shapes. All three implemented methods use the Hu invariants (see #HuMoments)
4323
4324
@param contour1 First contour or grayscale image.
4325
@param contour2 Second contour or grayscale image.
4326
@param method Comparison method, see #ShapeMatchModes
4327
@param parameter Method-specific parameter (not supported now).
4328
 */
4329
CV_EXPORTS_W double matchShapes( InputArray contour1, InputArray contour2,
4330
                                 int method, double parameter );
4331
4332
/** @example samples/cpp/convexhull.cpp
4333
An example using the convexHull functionality
4334
*/
4335
4336
/** @brief Finds the convex hull of a point set.
4337
4338
The function cv::convexHull finds the convex hull of a 2D point set using the Sklansky's algorithm @cite Sklansky82
4339
that has *O(N logN)* complexity in the current implementation.
4340
4341
@param points Input 2D point set, stored in std::vector or Mat.
4342
@param hull Output convex hull. It is either an integer vector of indices or vector of points. In
4343
the first case, the hull elements are 0-based indices of the convex hull points in the original
4344
array (since the set of convex hull points is a subset of the original point set). In the second
4345
case, hull elements are the convex hull points themselves.
4346
@param clockwise Orientation flag. If it is true, the output convex hull is oriented clockwise.
4347
Otherwise, it is oriented counter-clockwise. The assumed coordinate system has its X axis pointing
4348
to the right, and its Y axis pointing upwards.
4349
@param returnPoints Operation flag. In case of a matrix, when the flag is true, the function
4350
returns convex hull points. Otherwise, it returns indices of the convex hull points. When the
4351
output array is std::vector, the flag is ignored, and the output depends on the type of the
4352
vector: std::vector\<int\> implies returnPoints=false, std::vector\<Point\> implies
4353
returnPoints=true.
4354
4355
@note `points` and `hull` should be different arrays, inplace processing isn't supported.
4356
4357
Check @ref tutorial_hull "the corresponding tutorial" for more details.
4358
4359
useful links:
4360
4361
https://www.learnopencv.com/convex-hull-using-opencv-in-python-and-c/
4362
 */
4363
CV_EXPORTS_W void convexHull( InputArray points, OutputArray hull,
4364
                              bool clockwise = false, bool returnPoints = true );
4365
4366
/** @brief Finds the convexity defects of a contour.
4367
4368
The figure below displays convexity defects of a hand contour:
4369
4370
![image](pics/defects.png)
4371
4372
@param contour Input contour.
4373
@param convexhull Convex hull obtained using convexHull that should contain indices of the contour
4374
points that make the hull.
4375
@param convexityDefects The output vector of convexity defects. In C++ and the new Python/Java
4376
interface each convexity defect is represented as 4-element integer vector (a.k.a. #Vec4i):
4377
(start_index, end_index, farthest_pt_index, fixpt_depth), where indices are 0-based indices
4378
in the original contour of the convexity defect beginning, end and the farthest point, and
4379
fixpt_depth is fixed-point approximation (with 8 fractional bits) of the distance between the
4380
farthest contour point and the hull. That is, to get the floating-point value of the depth will be
4381
fixpt_depth/256.0.
4382
 */
4383
CV_EXPORTS_W void convexityDefects( InputArray contour, InputArray convexhull, OutputArray convexityDefects );
4384
4385
/** @brief Tests a contour convexity.
4386
4387
The function tests whether the input contour is convex or not. The contour must be simple, that is,
4388
without self-intersections. Otherwise, the function output is undefined.
4389
4390
@param contour Input vector of 2D points, stored in std::vector\<\> or Mat
4391
 */
4392
CV_EXPORTS_W bool isContourConvex( InputArray contour );
4393
4394
/** @example samples/cpp/intersectExample.cpp
4395
Examples of how intersectConvexConvex works
4396
*/
4397
4398
/** @brief Finds intersection of two convex polygons
4399
4400
@param p1 First polygon
4401
@param p2 Second polygon
4402
@param p12 Output polygon describing the intersecting area
4403
@param handleNested When true, an intersection is found if one of the polygons is fully enclosed in the other.
4404
When false, no intersection is found. If the polygons share a side or the vertex of one polygon lies on an edge
4405
of the other, they are not considered nested and an intersection will be found regardless of the value of handleNested.
4406
4407
@returns Area of intersecting polygon. May be negative, if algorithm has not converged, e.g. non-convex input.
4408
4409
@note intersectConvexConvex doesn't confirm that both polygons are convex and will return invalid results if they aren't.
4410
 */
4411
CV_EXPORTS_W float intersectConvexConvex( InputArray p1, InputArray p2,
4412
                                          OutputArray p12, bool handleNested = true );
4413
4414
/** @example samples/cpp/fitellipse.cpp
4415
An example using the fitEllipse technique
4416
*/
4417
4418
/** @brief Fits an ellipse around a set of 2D points.
4419
4420
The function calculates the ellipse that fits (in a least-squares sense) a set of 2D points best of
4421
all. It returns the rotated rectangle in which the ellipse is inscribed. The first algorithm described by @cite Fitzgibbon95
4422
is used. Developer should keep in mind that it is possible that the returned
4423
ellipse/rotatedRect data contains negative indices, due to the data points being close to the
4424
border of the containing Mat element.
4425
4426
@param points Input 2D point set, stored in std::vector\<\> or Mat
4427
4428
@note Input point types are @ref Point2i or @ref Point2f and at least 5 points are required.
4429
@note @ref getClosestEllipsePoints function can be used to compute the ellipse fitting error.
4430
 */
4431
CV_EXPORTS_W RotatedRect fitEllipse( InputArray points );
4432
4433
/** @brief Fits an ellipse around a set of 2D points.
4434
4435
 The function calculates the ellipse that fits a set of 2D points.
4436
 It returns the rotated rectangle in which the ellipse is inscribed.
4437
 The Approximate Mean Square (AMS) proposed by @cite Taubin1991 is used.
4438
4439
 For an ellipse, this basis set is \f$ \chi= \left(x^2, x y, y^2, x, y, 1\right) \f$,
4440
 which is a set of six free coefficients \f$ A^T=\left\{A_{\text{xx}},A_{\text{xy}},A_{\text{yy}},A_x,A_y,A_0\right\} \f$.
4441
 However, to specify an ellipse, all that is needed is five numbers; the major and minor axes lengths \f$ (a,b) \f$,
4442
 the position \f$ (x_0,y_0) \f$, and the orientation \f$ \theta \f$. This is because the basis set includes lines,
4443
 quadratics, parabolic and hyperbolic functions as well as elliptical functions as possible fits.
4444
 If the fit is found to be a parabolic or hyperbolic function then the standard #fitEllipse method is used.
4445
 The AMS method restricts the fit to parabolic, hyperbolic and elliptical curves
4446
 by imposing the condition that \f$ A^T ( D_x^T D_x  +   D_y^T D_y) A = 1 \f$ where
4447
 the matrices \f$ Dx \f$ and \f$ Dy \f$ are the partial derivatives of the design matrix \f$ D \f$ with
4448
 respect to x and y. The matrices are formed row by row applying the following to
4449
 each of the points in the set:
4450
 \f{align*}{
4451
 D(i,:)&=\left\{x_i^2, x_i y_i, y_i^2, x_i, y_i, 1\right\} &
4452
 D_x(i,:)&=\left\{2 x_i,y_i,0,1,0,0\right\} &
4453
 D_y(i,:)&=\left\{0,x_i,2 y_i,0,1,0\right\}
4454
 \f}
4455
 The AMS method minimizes the cost function
4456
 \f{equation*}{
4457
 \epsilon ^2=\frac{ A^T D^T D A }{ A^T (D_x^T D_x +  D_y^T D_y) A^T }
4458
 \f}
4459
4460
 The minimum cost is found by solving the generalized eigenvalue problem.
4461
4462
 \f{equation*}{
4463
 D^T D A = \lambda  \left( D_x^T D_x +  D_y^T D_y\right) A
4464
 \f}
4465
4466
 @param points Input 2D point set, stored in std::vector\<\> or Mat
4467
4468
 @note Input point types are @ref Point2i or @ref Point2f and at least 5 points are required.
4469
 @note @ref getClosestEllipsePoints function can be used to compute the ellipse fitting error.
4470
 */
4471
CV_EXPORTS_W RotatedRect fitEllipseAMS( InputArray points );
4472
4473
4474
/** @brief Fits an ellipse around a set of 2D points.
4475
4476
 The function calculates the ellipse that fits a set of 2D points.
4477
 It returns the rotated rectangle in which the ellipse is inscribed.
4478
 The Direct least square (Direct) method by @cite oy1998NumericallySD is used.
4479
4480
 For an ellipse, this basis set is \f$ \chi= \left(x^2, x y, y^2, x, y, 1\right) \f$,
4481
 which is a set of six free coefficients \f$ A^T=\left\{A_{\text{xx}},A_{\text{xy}},A_{\text{yy}},A_x,A_y,A_0\right\} \f$.
4482
 However, to specify an ellipse, all that is needed is five numbers; the major and minor axes lengths \f$ (a,b) \f$,
4483
 the position \f$ (x_0,y_0) \f$, and the orientation \f$ \theta \f$. This is because the basis set includes lines,
4484
 quadratics, parabolic and hyperbolic functions as well as elliptical functions as possible fits.
4485
 The Direct method confines the fit to ellipses by ensuring that \f$ 4 A_{xx} A_{yy}- A_{xy}^2 > 0 \f$.
4486
 The condition imposed is that \f$ 4 A_{xx} A_{yy}- A_{xy}^2=1 \f$ which satisfies the inequality
4487
 and as the coefficients can be arbitrarily scaled is not overly restrictive.
4488
4489
 \f{equation*}{
4490
 \epsilon ^2= A^T D^T D A \quad \text{with} \quad A^T C A =1 \quad \text{and} \quad C=\left(\begin{matrix}
4491
 0 & 0  & 2  & 0  & 0  &  0  \\
4492
 0 & -1  & 0  & 0  & 0  &  0 \\
4493
 2 & 0  & 0  & 0  & 0  &  0 \\
4494
 0 & 0  & 0  & 0  & 0  &  0 \\
4495
 0 & 0  & 0  & 0  & 0  &  0 \\
4496
 0 & 0  & 0  & 0  & 0  &  0
4497
 \end{matrix} \right)
4498
 \f}
4499
4500
 The minimum cost is found by solving the generalized eigenvalue problem.
4501
4502
 \f{equation*}{
4503
 D^T D A = \lambda  \left( C\right) A
4504
 \f}
4505
4506
 The system produces only one positive eigenvalue \f$ \lambda\f$ which is chosen as the solution
4507
 with its eigenvector \f$\mathbf{u}\f$. These are used to find the coefficients
4508
4509
 \f{equation*}{
4510
 A = \sqrt{\frac{1}{\mathbf{u}^T C \mathbf{u}}}  \mathbf{u}
4511
 \f}
4512
 The scaling factor guarantees that  \f$A^T C A =1\f$.
4513
4514
 @param points Input 2D point set, stored in std::vector\<\> or Mat
4515
4516
 @note Input point types are @ref Point2i or @ref Point2f and at least 5 points are required.
4517
 @note @ref getClosestEllipsePoints function can be used to compute the ellipse fitting error.
4518
 */
4519
CV_EXPORTS_W RotatedRect fitEllipseDirect( InputArray points );
4520
4521
/** @brief Compute for each 2d point the nearest 2d point located on a given ellipse.
4522
4523
 The function computes the nearest 2d location on a given ellipse for a vector of 2d points and is based on @cite Chatfield2017 code.
4524
 This function can be used to compute for instance the ellipse fitting error.
4525
4526
 @param ellipse_params Ellipse parameters
4527
 @param points Input 2d points
4528
 @param closest_pts For each 2d point, their corresponding closest 2d point located on a given ellipse
4529
4530
 @note Input point types are @ref Point2i or @ref Point2f
4531
 @see fitEllipse, fitEllipseAMS, fitEllipseDirect
4532
 */
4533
CV_EXPORTS_W void getClosestEllipsePoints( const RotatedRect& ellipse_params, InputArray points, OutputArray closest_pts );
4534
4535
/** @brief Fits a line to a 2D or 3D point set.
4536
4537
The function fitLine fits a line to a 2D or 3D point set by minimizing \f$\sum_i \rho(r_i)\f$ where
4538
\f$r_i\f$ is a distance between the \f$i^{th}\f$ point, the line and \f$\rho(r)\f$ is a distance function, one
4539
of the following:
4540
-  DIST_L2
4541
\f[\rho (r) = r^2/2  \quad \text{(the simplest and the fastest least-squares method)}\f]
4542
- DIST_L1
4543
\f[\rho (r) = r\f]
4544
- DIST_L12
4545
\f[\rho (r) = 2  \cdot ( \sqrt{1 + \frac{r^2}{2}} - 1)\f]
4546
- DIST_FAIR
4547
\f[\rho \left (r \right ) = C^2  \cdot \left (  \frac{r}{C} -  \log{\left(1 + \frac{r}{C}\right)} \right )  \quad \text{where} \quad C=1.3998\f]
4548
- DIST_WELSCH
4549
\f[\rho \left (r \right ) =  \frac{C^2}{2} \cdot \left ( 1 -  \exp{\left(-\left(\frac{r}{C}\right)^2\right)} \right )  \quad \text{where} \quad C=2.9846\f]
4550
- DIST_HUBER
4551
\f[\rho (r) =  \fork{r^2/2}{if \(r < C\)}{C \cdot (r-C/2)}{otherwise} \quad \text{where} \quad C=1.345\f]
4552
4553
The algorithm is based on the M-estimator ( <https://en.wikipedia.org/wiki/M-estimator> ) technique
4554
that iteratively fits the line using the weighted least-squares algorithm. After each iteration the
4555
weights \f$w_i\f$ are adjusted to be inversely proportional to \f$\rho(r_i)\f$ .
4556
4557
@param points Input vector of 2D or 3D points, stored in std::vector\<\> or Mat.
4558
@param line Output line parameters. In case of 2D fitting, it should be a vector of 4 elements
4559
(like Vec4f) - (vx, vy, x0, y0), where (vx, vy) is a normalized vector collinear to the line and
4560
(x0, y0) is a point on the line. In case of 3D fitting, it should be a vector of 6 elements (like
4561
Vec6f) - (vx, vy, vz, x0, y0, z0), where (vx, vy, vz) is a normalized vector collinear to the line
4562
and (x0, y0, z0) is a point on the line.
4563
@param distType Distance used by the M-estimator, see #DistanceTypes
4564
@param param Numerical parameter ( C ) for some types of distances. If it is 0, an optimal value
4565
is chosen.
4566
@param reps Sufficient accuracy for the radius (distance between the coordinate origin and the line).
4567
@param aeps Sufficient accuracy for the angle. 0.01 would be a good default value for reps and aeps.
4568
 */
4569
CV_EXPORTS_W void fitLine( InputArray points, OutputArray line, int distType,
4570
                           double param, double reps, double aeps );
4571
4572
/** @brief Performs a point-in-contour test.
4573
4574
The function determines whether the point is inside a contour, outside, or lies on an edge (or
4575
coincides with a vertex). It returns positive (inside), negative (outside), or zero (on an edge)
4576
value, correspondingly. When measureDist=false , the return value is +1, -1, and 0, respectively.
4577
Otherwise, the return value is a signed distance between the point and the nearest contour edge.
4578
4579
See below a sample output of the function where each image pixel is tested against the contour:
4580
4581
![sample output](pics/pointpolygon.png)
4582
4583
@param contour Input contour.
4584
@param pt Point tested against the contour.
4585
@param measureDist If true, the function estimates the signed distance from the point to the
4586
nearest contour edge. Otherwise, the function only checks if the point is inside a contour or not.
4587
 */
4588
CV_EXPORTS_W double pointPolygonTest( InputArray contour, Point2f pt, bool measureDist );
4589
4590
/** @brief Finds out if there is any intersection between two rotated rectangles.
4591
4592
If there is then the vertices of the intersecting region are returned as well.
4593
4594
Below are some examples of intersection configurations. The hatched pattern indicates the
4595
intersecting region and the red vertices are returned by the function.
4596
4597
![intersection examples](pics/intersection.png)
4598
4599
@param rect1 First rectangle
4600
@param rect2 Second rectangle
4601
@param intersectingRegion The output array of the vertices of the intersecting region. It returns
4602
at most 8 vertices. Stored as std::vector\<cv::Point2f\> or cv::Mat as Mx1 of type CV_32FC2.
4603
@returns One of #RectanglesIntersectTypes
4604
 */
4605
CV_EXPORTS_W int rotatedRectangleIntersection( const RotatedRect& rect1, const RotatedRect& rect2, OutputArray intersectingRegion  );
4606
4607
/** @brief Creates a smart pointer to a cv::GeneralizedHoughBallard class and initializes it.
4608
*/
4609
CV_EXPORTS_W Ptr<GeneralizedHoughBallard> createGeneralizedHoughBallard();
4610
4611
/** @brief Creates a smart pointer to a cv::GeneralizedHoughGuil class and initializes it.
4612
*/
4613
CV_EXPORTS_W Ptr<GeneralizedHoughGuil> createGeneralizedHoughGuil();
4614
4615
//! @} imgproc_shape
4616
4617
//! @addtogroup imgproc_colormap
4618
//! @{
4619
4620
//! GNU Octave/MATLAB equivalent colormaps
4621
enum ColormapTypes
4622
{
4623
    COLORMAP_AUTUMN = 0, //!< ![autumn](pics/colormaps/colorscale_autumn.jpg)
4624
    COLORMAP_BONE = 1, //!< ![bone](pics/colormaps/colorscale_bone.jpg)
4625
    COLORMAP_JET = 2, //!< ![jet](pics/colormaps/colorscale_jet.jpg)
4626
    COLORMAP_WINTER = 3, //!< ![winter](pics/colormaps/colorscale_winter.jpg)
4627
    COLORMAP_RAINBOW = 4, //!< ![rainbow](pics/colormaps/colorscale_rainbow.jpg)
4628
    COLORMAP_OCEAN = 5, //!< ![ocean](pics/colormaps/colorscale_ocean.jpg)
4629
    COLORMAP_SUMMER = 6, //!< ![summer](pics/colormaps/colorscale_summer.jpg)
4630
    COLORMAP_SPRING = 7, //!< ![spring](pics/colormaps/colorscale_spring.jpg)
4631
    COLORMAP_COOL = 8, //!< ![cool](pics/colormaps/colorscale_cool.jpg)
4632
    COLORMAP_HSV = 9, //!< ![HSV](pics/colormaps/colorscale_hsv.jpg)
4633
    COLORMAP_PINK = 10, //!< ![pink](pics/colormaps/colorscale_pink.jpg)
4634
    COLORMAP_HOT = 11, //!< ![hot](pics/colormaps/colorscale_hot.jpg)
4635
    COLORMAP_PARULA = 12, //!< ![parula](pics/colormaps/colorscale_parula.jpg)
4636
    COLORMAP_MAGMA = 13, //!< ![magma](pics/colormaps/colorscale_magma.jpg)
4637
    COLORMAP_INFERNO = 14, //!< ![inferno](pics/colormaps/colorscale_inferno.jpg)
4638
    COLORMAP_PLASMA = 15, //!< ![plasma](pics/colormaps/colorscale_plasma.jpg)
4639
    COLORMAP_VIRIDIS = 16, //!< ![viridis](pics/colormaps/colorscale_viridis.jpg)
4640
    COLORMAP_CIVIDIS = 17, //!< ![cividis](pics/colormaps/colorscale_cividis.jpg)
4641
    COLORMAP_TWILIGHT = 18, //!< ![twilight](pics/colormaps/colorscale_twilight.jpg)
4642
    COLORMAP_TWILIGHT_SHIFTED = 19, //!< ![twilight shifted](pics/colormaps/colorscale_twilight_shifted.jpg)
4643
    COLORMAP_TURBO = 20, //!< ![turbo](pics/colormaps/colorscale_turbo.jpg)
4644
    COLORMAP_DEEPGREEN = 21  //!< ![deepgreen](pics/colormaps/colorscale_deepgreen.jpg)
4645
};
4646
4647
/** @example samples/cpp/falsecolor.cpp
4648
An example using applyColorMap function
4649
*/
4650
4651
/** @brief Applies a GNU Octave/MATLAB equivalent colormap on a given image.
4652
4653
@param src The source image, grayscale or colored of type CV_8UC1 or CV_8UC3. If CV_8UC3, then the CV_8UC1 image is generated internally using cv::COLOR_BGR2GRAY.
4654
@param dst The result is the colormapped source image. Note: Mat::create is called on dst.
4655
@param colormap The colormap to apply, see #ColormapTypes
4656
*/
4657
CV_EXPORTS_W void applyColorMap(InputArray src, OutputArray dst, int colormap);
4658
4659
/** @brief Applies a user colormap on a given image.
4660
4661
@param src The source image, grayscale or colored of type CV_8UC1 or CV_8UC3. If CV_8UC3, then the CV_8UC1 image is generated internally using cv::COLOR_BGR2GRAY.
4662
@param dst The result is the colormapped source image of the same number of channels as userColor. Note: Mat::create is called on dst.
4663
@param userColor The colormap to apply of type CV_8UC1 or CV_8UC3 and size 256
4664
*/
4665
CV_EXPORTS_W void applyColorMap(InputArray src, OutputArray dst, InputArray userColor);
4666
4667
//! @} imgproc_colormap
4668
4669
//! @addtogroup imgproc_draw
4670
//! @{
4671
4672
4673
/** OpenCV color channel order is BGR[A] */
4674
#define CV_RGB(r, g, b)  cv::Scalar((b), (g), (r), 0)
4675
4676
/** @brief Draws a line segment connecting two points.
4677
4678
The function line draws the line segment between pt1 and pt2 points in the image. The line is
4679
clipped by the image boundaries. For non-antialiased lines with integer coordinates, the 8-connected
4680
or 4-connected Bresenham algorithm is used. Thick lines are drawn with rounding endings. Antialiased
4681
lines are drawn using Gaussian filtering.
4682
4683
@param img Image.
4684
@param pt1 First point of the line segment.
4685
@param pt2 Second point of the line segment.
4686
@param color Line color.
4687
@param thickness Line thickness.
4688
@param lineType Type of the line. See #LineTypes.
4689
@param shift Number of fractional bits in the point coordinates.
4690
 */
4691
CV_EXPORTS_W void line(InputOutputArray img, Point pt1, Point pt2, const Scalar& color,
4692
                     int thickness = 1, int lineType = LINE_8, int shift = 0);
4693
4694
/** @brief Draws an arrow segment pointing from the first point to the second one.
4695
4696
The function cv::arrowedLine draws an arrow between pt1 and pt2 points in the image. See also #line.
4697
4698
@param img Image.
4699
@param pt1 The point the arrow starts from.
4700
@param pt2 The point the arrow points to.
4701
@param color Line color.
4702
@param thickness Line thickness.
4703
@param line_type Type of the line. See #LineTypes
4704
@param shift Number of fractional bits in the point coordinates.
4705
@param tipLength The length of the arrow tip in relation to the arrow length
4706
 */
4707
CV_EXPORTS_W void arrowedLine(InputOutputArray img, Point pt1, Point pt2, const Scalar& color,
4708
                     int thickness=1, int line_type=8, int shift=0, double tipLength=0.1);
4709
4710
/** @brief Draws a simple, thick, or filled up-right rectangle.
4711
4712
The function cv::rectangle draws a rectangle outline or a filled rectangle whose two opposite corners
4713
are pt1 and pt2.
4714
4715
@param img Image.
4716
@param pt1 Vertex of the rectangle.
4717
@param pt2 Vertex of the rectangle opposite to pt1 .
4718
@param color Rectangle color or brightness (grayscale image).
4719
@param thickness Thickness of lines that make up the rectangle. Negative values, like #FILLED,
4720
mean that the function has to draw a filled rectangle.
4721
@param lineType Type of the line. See #LineTypes
4722
@param shift Number of fractional bits in the point coordinates.
4723
 */
4724
CV_EXPORTS_W void rectangle(InputOutputArray img, Point pt1, Point pt2,
4725
                          const Scalar& color, int thickness = 1,
4726
                          int lineType = LINE_8, int shift = 0);
4727
4728
/** @overload
4729
4730
use `rec` parameter as alternative specification of the drawn rectangle: `r.tl() and
4731
r.br()-Point(1,1)` are opposite corners
4732
*/
4733
CV_EXPORTS_W void rectangle(InputOutputArray img, Rect rec,
4734
                          const Scalar& color, int thickness = 1,
4735
                          int lineType = LINE_8, int shift = 0);
4736
4737
/** @example samples/cpp/tutorial_code/ImgProc/basic_drawing/Drawing_2.cpp
4738
An example using drawing functions
4739
*/
4740
4741
/** @brief Draws a circle.
4742
4743
The function cv::circle draws a simple or filled circle with a given center and radius.
4744
@param img Image where the circle is drawn.
4745
@param center Center of the circle.
4746
@param radius Radius of the circle.
4747
@param color Circle color.
4748
@param thickness Thickness of the circle outline, if positive. Negative values, like #FILLED,
4749
mean that a filled circle is to be drawn.
4750
@param lineType Type of the circle boundary. See #LineTypes
4751
@param shift Number of fractional bits in the coordinates of the center and in the radius value.
4752
 */
4753
CV_EXPORTS_W void circle(InputOutputArray img, Point center, int radius,
4754
                       const Scalar& color, int thickness = 1,
4755
                       int lineType = LINE_8, int shift = 0);
4756
4757
/** @brief Draws a simple or thick elliptic arc or fills an ellipse sector.
4758
4759
The function cv::ellipse with more parameters draws an ellipse outline, a filled ellipse, an elliptic
4760
arc, or a filled ellipse sector. The drawing code uses general parametric form.
4761
A piecewise-linear curve is used to approximate the elliptic arc
4762
boundary. If you need more control of the ellipse rendering, you can retrieve the curve using
4763
#ellipse2Poly and then render it with #polylines or fill it with #fillPoly. If you use the first
4764
variant of the function and want to draw the whole ellipse, not an arc, pass `startAngle=0` and
4765
`endAngle=360`. If `startAngle` is greater than `endAngle`, they are swapped. The figure below explains
4766
the meaning of the parameters to draw the blue arc.
4767
4768
![Parameters of Elliptic Arc](pics/ellipse.svg)
4769
4770
@param img Image.
4771
@param center Center of the ellipse.
4772
@param axes Half of the size of the ellipse main axes.
4773
@param angle Ellipse rotation angle in degrees.
4774
@param startAngle Starting angle of the elliptic arc in degrees.
4775
@param endAngle Ending angle of the elliptic arc in degrees.
4776
@param color Ellipse color.
4777
@param thickness Thickness of the ellipse arc outline, if positive. Otherwise, this indicates that
4778
a filled ellipse sector is to be drawn.
4779
@param lineType Type of the ellipse boundary. See #LineTypes
4780
@param shift Number of fractional bits in the coordinates of the center and values of axes.
4781
 */
4782
CV_EXPORTS_W void ellipse(InputOutputArray img, Point center, Size axes,
4783
                        double angle, double startAngle, double endAngle,
4784
                        const Scalar& color, int thickness = 1,
4785
                        int lineType = LINE_8, int shift = 0);
4786
4787
/** @overload
4788
@param img Image.
4789
@param box Alternative ellipse representation via RotatedRect. This means that the function draws
4790
an ellipse inscribed in the rotated rectangle.
4791
@param color Ellipse color.
4792
@param thickness Thickness of the ellipse arc outline, if positive. Otherwise, this indicates that
4793
a filled ellipse sector is to be drawn.
4794
@param lineType Type of the ellipse boundary. See #LineTypes
4795
*/
4796
CV_EXPORTS_W void ellipse(InputOutputArray img, const RotatedRect& box, const Scalar& color,
4797
                        int thickness = 1, int lineType = LINE_8);
4798
4799
/* ----------------------------------------------------------------------------------------- */
4800
/* ADDING A SET OF PREDEFINED MARKERS WHICH COULD BE USED TO HIGHLIGHT POSITIONS IN AN IMAGE */
4801
/* ----------------------------------------------------------------------------------------- */
4802
4803
/** @brief Draws a marker on a predefined position in an image.
4804
4805
The function cv::drawMarker draws a marker on a given position in the image. For the moment several
4806
marker types are supported, see #MarkerTypes for more information.
4807
4808
@param img Image.
4809
@param position The point where the crosshair is positioned.
4810
@param color Line color.
4811
@param markerType The specific type of marker you want to use, see #MarkerTypes
4812
@param thickness Line thickness.
4813
@param line_type Type of the line, See #LineTypes
4814
@param markerSize The length of the marker axis [default = 20 pixels]
4815
 */
4816
CV_EXPORTS_W void drawMarker(InputOutputArray img, Point position, const Scalar& color,
4817
                             int markerType = MARKER_CROSS, int markerSize=20, int thickness=1,
4818
                             int line_type=8);
4819
4820
/* ----------------------------------------------------------------------------------------- */
4821
/* END OF MARKER SECTION */
4822
/* ----------------------------------------------------------------------------------------- */
4823
4824
/** @brief Fills a convex polygon.
4825
4826
The function cv::fillConvexPoly draws a filled convex polygon. This function is much faster than the
4827
function #fillPoly . It can fill not only convex polygons but any monotonic polygon without
4828
self-intersections, that is, a polygon whose contour intersects every horizontal line (scan line)
4829
twice at the most (though, its top-most and/or the bottom edge could be horizontal).
4830
4831
@param img Image.
4832
@param points Polygon vertices.
4833
@param color Polygon color.
4834
@param lineType Type of the polygon boundaries. See #LineTypes
4835
@param shift Number of fractional bits in the vertex coordinates.
4836
 */
4837
CV_EXPORTS_W void fillConvexPoly(InputOutputArray img, InputArray points,
4838
                                 const Scalar& color, int lineType = LINE_8,
4839
                                 int shift = 0);
4840
4841
/** @overload */
4842
CV_EXPORTS void fillConvexPoly(InputOutputArray img, const Point* pts, int npts,
4843
                               const Scalar& color, int lineType = LINE_8,
4844
                               int shift = 0);
4845
4846
/** @example samples/cpp/tutorial_code/ImgProc/basic_drawing/Drawing_1.cpp
4847
An example using drawing functions
4848
Check @ref tutorial_random_generator_and_text "the corresponding tutorial" for more details
4849
*/
4850
4851
/** @brief Fills the area bounded by one or more polygons.
4852
4853
The function cv::fillPoly fills an area bounded by several polygonal contours. The function can fill
4854
complex areas, for example, areas with holes, contours with self-intersections (some of their
4855
parts), and so forth.
4856
4857
@param img Image.
4858
@param pts Array of polygons where each polygon is represented as an array of points.
4859
@param color Polygon color.
4860
@param lineType Type of the polygon boundaries. See #LineTypes
4861
@param shift Number of fractional bits in the vertex coordinates.
4862
@param offset Optional offset of all points of the contours.
4863
 */
4864
CV_EXPORTS_W void fillPoly(InputOutputArray img, InputArrayOfArrays pts,
4865
                           const Scalar& color, int lineType = LINE_8, int shift = 0,
4866
                           Point offset = Point() );
4867
4868
/** @overload */
4869
CV_EXPORTS void fillPoly(InputOutputArray img, const Point** pts,
4870
                         const int* npts, int ncontours,
4871
                         const Scalar& color, int lineType = LINE_8, int shift = 0,
4872
                         Point offset = Point() );
4873
4874
/** @brief Draws several polygonal curves.
4875
4876
@param img Image.
4877
@param pts Array of polygonal curves.
4878
@param isClosed Flag indicating whether the drawn polylines are closed or not. If they are closed,
4879
the function draws a line from the last vertex of each curve to its first vertex.
4880
@param color Polyline color.
4881
@param thickness Thickness of the polyline edges.
4882
@param lineType Type of the line segments. See #LineTypes
4883
@param shift Number of fractional bits in the vertex coordinates.
4884
4885
The function cv::polylines draws one or more polygonal curves.
4886
 */
4887
CV_EXPORTS_W void polylines(InputOutputArray img, InputArrayOfArrays pts,
4888
                            bool isClosed, const Scalar& color,
4889
                            int thickness = 1, int lineType = LINE_8, int shift = 0 );
4890
4891
/** @overload */
4892
CV_EXPORTS void polylines(InputOutputArray img, const Point* const* pts, const int* npts,
4893
                          int ncontours, bool isClosed, const Scalar& color,
4894
                          int thickness = 1, int lineType = LINE_8, int shift = 0 );
4895
4896
/** @example samples/cpp/contours2.cpp
4897
An example program illustrates the use of cv::findContours and cv::drawContours
4898
\image html WindowsQtContoursOutput.png "Screenshot of the program"
4899
*/
4900
4901
/** @example samples/cpp/segment_objects.cpp
4902
An example using drawContours to clean up a background segmentation result
4903
*/
4904
4905
/** @brief Draws contours outlines or filled contours.
4906
4907
The function draws contour outlines in the image if \f$\texttt{thickness} \ge 0\f$ or fills the area
4908
bounded by the contours if \f$\texttt{thickness}<0\f$ . The example below shows how to retrieve
4909
connected components from the binary image and label them: :
4910
@include snippets/imgproc_drawContours.cpp
4911
4912
@param image Destination image.
4913
@param contours All the input contours. Each contour is stored as a point vector.
4914
@param contourIdx Parameter indicating a contour to draw. If it is negative, all the contours are drawn.
4915
@param color Color of the contours.
4916
@param thickness Thickness of lines the contours are drawn with. If it is negative (for example,
4917
thickness=#FILLED ), the contour interiors are drawn.
4918
@param lineType Line connectivity. See #LineTypes
4919
@param hierarchy Optional information about hierarchy. It is only needed if you want to draw only
4920
some of the contours (see maxLevel ).
4921
@param maxLevel Maximal level for drawn contours. If it is 0, only the specified contour is drawn.
4922
If it is 1, the function draws the contour(s) and all the nested contours. If it is 2, the function
4923
draws the contours, all the nested contours, all the nested-to-nested contours, and so on. This
4924
parameter is only taken into account when there is hierarchy available.
4925
@param offset Optional contour shift parameter. Shift all the drawn contours by the specified
4926
\f$\texttt{offset}=(dx,dy)\f$ .
4927
@note When thickness=#FILLED, the function is designed to handle connected components with holes correctly
4928
even when no hierarchy data is provided. This is done by analyzing all the outlines together
4929
using even-odd rule. This may give incorrect results if you have a joint collection of separately retrieved
4930
contours. In order to solve this problem, you need to call #drawContours separately for each sub-group
4931
of contours, or iterate over the collection using contourIdx parameter.
4932
 */
4933
CV_EXPORTS_W void drawContours( InputOutputArray image, InputArrayOfArrays contours,
4934
                              int contourIdx, const Scalar& color,
4935
                              int thickness = 1, int lineType = LINE_8,
4936
                              InputArray hierarchy = noArray(),
4937
                              int maxLevel = INT_MAX, Point offset = Point() );
4938
4939
/** @brief Clips the line against the image rectangle.
4940
4941
The function cv::clipLine calculates a part of the line segment that is entirely within the specified
4942
rectangle. It returns false if the line segment is completely outside the rectangle. Otherwise,
4943
it returns true .
4944
@param imgSize Image size. The image rectangle is Rect(0, 0, imgSize.width, imgSize.height) .
4945
@param pt1 First line point.
4946
@param pt2 Second line point.
4947
 */
4948
CV_EXPORTS bool clipLine(Size imgSize, CV_IN_OUT Point& pt1, CV_IN_OUT Point& pt2);
4949
4950
/** @overload
4951
@param imgSize Image size. The image rectangle is Rect(0, 0, imgSize.width, imgSize.height) .
4952
@param pt1 First line point.
4953
@param pt2 Second line point.
4954
*/
4955
CV_EXPORTS bool clipLine(Size2l imgSize, CV_IN_OUT Point2l& pt1, CV_IN_OUT Point2l& pt2);
4956
4957
/** @overload
4958
@param imgRect Image rectangle.
4959
@param pt1 First line point.
4960
@param pt2 Second line point.
4961
*/
4962
CV_EXPORTS_W bool clipLine(Rect imgRect, CV_OUT CV_IN_OUT Point& pt1, CV_OUT CV_IN_OUT Point& pt2);
4963
4964
/** @brief Approximates an elliptic arc with a polyline.
4965
4966
The function ellipse2Poly computes the vertices of a polyline that approximates the specified
4967
elliptic arc. It is used by #ellipse. If `arcStart` is greater than `arcEnd`, they are swapped.
4968
4969
@param center Center of the arc.
4970
@param axes Half of the size of the ellipse main axes. See #ellipse for details.
4971
@param angle Rotation angle of the ellipse in degrees. See #ellipse for details.
4972
@param arcStart Starting angle of the elliptic arc in degrees.
4973
@param arcEnd Ending angle of the elliptic arc in degrees.
4974
@param delta Angle between the subsequent polyline vertices. It defines the approximation
4975
accuracy.
4976
@param pts Output vector of polyline vertices.
4977
 */
4978
CV_EXPORTS_W void ellipse2Poly( Point center, Size axes, int angle,
4979
                                int arcStart, int arcEnd, int delta,
4980
                                CV_OUT std::vector<Point>& pts );
4981
4982
/** @overload
4983
@param center Center of the arc.
4984
@param axes Half of the size of the ellipse main axes. See #ellipse for details.
4985
@param angle Rotation angle of the ellipse in degrees. See #ellipse for details.
4986
@param arcStart Starting angle of the elliptic arc in degrees.
4987
@param arcEnd Ending angle of the elliptic arc in degrees.
4988
@param delta Angle between the subsequent polyline vertices. It defines the approximation accuracy.
4989
@param pts Output vector of polyline vertices.
4990
*/
4991
CV_EXPORTS void ellipse2Poly(Point2d center, Size2d axes, int angle,
4992
                             int arcStart, int arcEnd, int delta,
4993
                             CV_OUT std::vector<Point2d>& pts);
4994
4995
/** @brief Draws a text string.
4996
4997
The function cv::putText renders the specified text string in the image. Symbols that cannot be rendered
4998
using the specified font are replaced by question marks. See #getTextSize for a text rendering code
4999
example.
5000
5001
The `fontScale` parameter is a scale factor that is multiplied by the base font size:
5002
- When scale > 1, the text is magnified.
5003
- When 0 < scale < 1, the text is minimized.
5004
- When scale < 0, the text is mirrored or reversed.
5005
5006
@param img Image.
5007
@param text Text string to be drawn.
5008
@param org Bottom-left corner of the text string in the image.
5009
@param fontFace Font type, see #HersheyFonts.
5010
@param fontScale Font scale factor that is multiplied by the font-specific base size.
5011
@param color Text color.
5012
@param thickness Thickness of the lines used to draw a text.
5013
@param lineType Line type. See #LineTypes
5014
@param bottomLeftOrigin When true, the image data origin is at the bottom-left corner. Otherwise,
5015
it is at the top-left corner.
5016
 */
5017
CV_EXPORTS_W void putText( InputOutputArray img, const String& text, Point org,
5018
                         int fontFace, double fontScale, Scalar color,
5019
                         int thickness = 1, int lineType = LINE_8,
5020
                         bool bottomLeftOrigin = false );
5021
5022
/** @brief Calculates the width and height of a text string.
5023
5024
The function cv::getTextSize calculates and returns the size of a box that contains the specified text.
5025
That is, the following code renders some text, the tight box surrounding it, and the baseline: :
5026
@code
5027
    String text = "Funny text inside the box";
5028
    int fontFace = FONT_HERSHEY_SCRIPT_SIMPLEX;
5029
    double fontScale = 2;
5030
    int thickness = 3;
5031
5032
    Mat img(600, 800, CV_8UC3, Scalar::all(0));
5033
5034
    int baseline=0;
5035
    Size textSize = getTextSize(text, fontFace,
5036
                                fontScale, thickness, &baseline);
5037
    baseline += thickness;
5038
5039
    // center the text
5040
    Point textOrg((img.cols - textSize.width)/2,
5041
                  (img.rows + textSize.height)/2);
5042
5043
    // draw the box
5044
    rectangle(img, textOrg + Point(0, baseline),
5045
              textOrg + Point(textSize.width, -textSize.height),
5046
              Scalar(0,0,255));
5047
    // ... and the baseline first
5048
    line(img, textOrg + Point(0, thickness),
5049
         textOrg + Point(textSize.width, thickness),
5050
         Scalar(0, 0, 255));
5051
5052
    // then put the text itself
5053
    putText(img, text, textOrg, fontFace, fontScale,
5054
            Scalar::all(255), thickness, 8);
5055
@endcode
5056
5057
@param text Input text string.
5058
@param fontFace Font to use, see #HersheyFonts.
5059
@param fontScale Font scale factor that is multiplied by the font-specific base size.
5060
@param thickness Thickness of lines used to render the text. See #putText for details.
5061
@param[out] baseLine y-coordinate of the baseline relative to the bottom-most text
5062
point.
5063
@return The size of a box that contains the specified text.
5064
5065
@see putText
5066
 */
5067
CV_EXPORTS_W Size getTextSize(const String& text, int fontFace,
5068
                            double fontScale, int thickness,
5069
                            CV_OUT int* baseLine);
5070
5071
5072
/** @brief Calculates the font-specific size to use to achieve a given height in pixels.
5073
5074
@param fontFace Font to use, see cv::HersheyFonts.
5075
@param pixelHeight Pixel height to compute the fontScale for
5076
@param thickness Thickness of lines used to render the text.See putText for details.
5077
@return The fontSize to use for cv::putText
5078
5079
@see cv::putText
5080
*/
5081
CV_EXPORTS_W double getFontScaleFromHeight(const int fontFace,
5082
                                           const int pixelHeight,
5083
                                           const int thickness = 1);
5084
5085
/** @brief Class for iterating over all pixels on a raster line segment.
5086
5087
The class LineIterator is used to get each pixel of a raster line connecting
5088
two specified points.
5089
It can be treated as a versatile implementation of the Bresenham algorithm
5090
where you can stop at each pixel and do some extra processing, for
5091
example, grab pixel values along the line or draw a line with an effect
5092
(for example, with XOR operation).
5093
5094
The number of pixels along the line is stored in LineIterator::count.
5095
The method LineIterator::pos returns the current position in the image:
5096
5097
@code{.cpp}
5098
// grabs pixels along the line (pt1, pt2)
5099
// from 8-bit 3-channel image to the buffer
5100
LineIterator it(img, pt1, pt2, 8);
5101
LineIterator it2 = it;
5102
vector<Vec3b> buf(it.count);
5103
5104
for(int i = 0; i < it.count; i++, ++it)
5105
    buf[i] = *(const Vec3b*)*it;
5106
5107
// alternative way of iterating through the line
5108
for(int i = 0; i < it2.count; i++, ++it2)
5109
{
5110
    Vec3b val = img.at<Vec3b>(it2.pos());
5111
    CV_Assert(buf[i] == val);
5112
}
5113
@endcode
5114
*/
5115
class CV_EXPORTS LineIterator
5116
{
5117
public:
5118
    /** @brief Initializes iterator object for the given line and image.
5119
5120
    The returned iterator can be used to traverse all pixels on a line that
5121
    connects the given two points.
5122
    The line will be clipped on the image boundaries.
5123
5124
    @param img Underlying image.
5125
    @param pt1 First endpoint of the line.
5126
    @param pt2 The other endpoint of the line.
5127
    @param connectivity Pixel connectivity of the iterator. Valid values are 4 (iterator can move
5128
    up, down, left and right) and 8 (iterator can also move diagonally).
5129
    @param leftToRight If true, the line is traversed from the leftmost endpoint to the rightmost
5130
    endpoint. Otherwise, the line is traversed from \p pt1 to \p pt2.
5131
    */
5132
    LineIterator( const Mat& img, Point pt1, Point pt2,
5133
                  int connectivity = 8, bool leftToRight = false )
5134
0
    {
5135
0
        init(&img, Rect(0, 0, img.cols, img.rows), pt1, pt2, connectivity, leftToRight);
5136
0
        ptmode = false;
5137
0
    }
5138
    LineIterator( Point pt1, Point pt2,
5139
                  int connectivity = 8, bool leftToRight = false )
5140
0
    {
5141
0
        init(0, Rect(std::min(pt1.x, pt2.x),
5142
0
                     std::min(pt1.y, pt2.y),
5143
0
                     std::max(pt1.x, pt2.x) - std::min(pt1.x, pt2.x) + 1,
5144
0
                     std::max(pt1.y, pt2.y) - std::min(pt1.y, pt2.y) + 1),
5145
0
             pt1, pt2, connectivity, leftToRight);
5146
0
        ptmode = true;
5147
0
    }
5148
    LineIterator( Size boundingAreaSize, Point pt1, Point pt2,
5149
                  int connectivity = 8, bool leftToRight = false )
5150
0
    {
5151
0
        init(0, Rect(0, 0, boundingAreaSize.width, boundingAreaSize.height),
5152
0
             pt1, pt2, connectivity, leftToRight);
5153
0
        ptmode = true;
5154
0
    }
5155
    LineIterator( Rect boundingAreaRect, Point pt1, Point pt2,
5156
                  int connectivity = 8, bool leftToRight = false )
5157
0
    {
5158
0
        init(0, boundingAreaRect, pt1, pt2, connectivity, leftToRight);
5159
0
        ptmode = true;
5160
0
    }
5161
    void init(const Mat* img, Rect boundingAreaRect, Point pt1, Point pt2, int connectivity, bool leftToRight);
5162
5163
    /** @brief Returns pointer to the current pixel.
5164
    */
5165
    uchar* operator *();
5166
5167
    /** @brief Moves iterator to the next pixel on the line.
5168
5169
    This is the prefix version (++it).
5170
    */
5171
    LineIterator& operator ++();
5172
5173
    /** @brief Moves iterator to the next pixel on the line.
5174
5175
    This is the postfix version (it++).
5176
    */
5177
    LineIterator operator ++(int);
5178
5179
    /** @brief Returns coordinates of the current pixel.
5180
    */
5181
    Point pos() const;
5182
5183
    uchar* ptr;
5184
    const uchar* ptr0;
5185
    int step, elemSize;
5186
    int err, count;
5187
    int minusDelta, plusDelta;
5188
    int minusStep, plusStep;
5189
    int minusShift, plusShift;
5190
    Point p;
5191
    bool ptmode;
5192
};
5193
5194
//! @cond IGNORED
5195
5196
// === LineIterator implementation ===
5197
5198
inline
5199
uchar* LineIterator::operator *()
5200
0
{
5201
0
    return ptmode ? 0 : ptr;
5202
0
}
5203
5204
inline
5205
LineIterator& LineIterator::operator ++()
5206
0
{
5207
0
    int mask = err < 0 ? -1 : 0;
5208
0
    err += minusDelta + (plusDelta & mask);
5209
0
    if(!ptmode)
5210
0
    {
5211
0
        ptr += minusStep + (plusStep & mask);
5212
0
    }
5213
0
    else
5214
0
    {
5215
0
        p.x += minusShift + (plusShift & mask);
5216
0
        p.y += minusStep + (plusStep & mask);
5217
0
    }
5218
0
    return *this;
5219
0
}
5220
5221
inline
5222
LineIterator LineIterator::operator ++(int)
5223
0
{
5224
0
    LineIterator it = *this;
5225
0
    ++(*this);
5226
0
    return it;
5227
0
}
5228
5229
inline
5230
Point LineIterator::pos() const
5231
0
{
5232
0
    if(!ptmode)
5233
0
    {
5234
0
        size_t offset = (size_t)(ptr - ptr0);
5235
0
        int y = (int)(offset/step);
5236
0
        int x = (int)((offset - (size_t)y*step)/elemSize);
5237
0
        return Point(x, y);
5238
0
    }
5239
0
    return p;
5240
0
}
5241
5242
//! @endcond
5243
5244
//! @} imgproc_draw
5245
5246
//! @} imgproc
5247
5248
} // cv
5249
5250
5251
#include "./imgproc/segmentation.hpp"
5252
5253
5254
#endif