2612 : @param sum integral image as \f$(W+1)\times (H+1)\f$ , 32-bit integer or floating-point (32f or 64f).
2613 : @param sqsum integral image for squared pixel values; it is \f$(W+1)\times (H+1)\f$, double-precision
2614 : floating-point (64f) array.
2615 : @param tilted integral for the image rotated by 45 degrees; it is \f$(W+1)\times (H+1)\f$ array with
2616 : the same data type as sum.
2617 : @param sdepth desired depth of the integral and the tilted integral images, CV_32S, CV_32F, or
2618 : CV_64F.
2619 : @param sqdepth desired depth of the integral image of squared pixel values, CV_32F or CV_64F.
2620 : */
2621 : CV_EXPORTS_AS(integral3) void integral( InputArray src, OutputArray sum,
2622 : OutputArray sqsum, OutputArray tilted,
2623 : int sdepth = -1, int sqdepth = -1 );
2624 :
2625 : //! @} imgproc_misc
2626 :
2627 : //! @addtogroup imgproc_motion
2628 : //! @{
2629 :
2630 : /** @brief Adds an image to the accumulator image.
2631 :
2632 : The function adds src or some of its elements to dst :
2633 :
2634 : \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]
2635 :
2636 : The function supports multi-channel images. Each channel is processed independently.
2637 :
2638 : The function cv::accumulate can be used, for example, to collect statistics of a scene background
2639 : viewed by a still camera and for the further foreground-background segmentation.
2640 :
2641 : @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.
2642 : @param dst %Accumulator image with the same number of channels as input image, and a depth of CV_32F or CV_64F.
2643 : @param mask Optional operation mask.
2644 :
2645 : @sa accumulateSquare, accumulateProduct, accumulateWeighted
2646 : */
2647 : CV_EXPORTS_W void accumulate( InputArray src, InputOutputArray dst,
2648 : InputArray mask = noArray() );
2649 :
2650 : /** @brief Adds the square of a source image to the accumulator image.
2651 :
2652 : The function adds the input image src or its selected region, raised to a power of 2, to the
2653 : accumulator dst :
2654 :
2655 : \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]
2656 :
2657 : The function supports multi-channel images. Each channel is processed independently.
2658 :
2659 : @param src Input image as 1- or 3-channel, 8-bit or 32-bit floating point.
2660 : @param dst %Accumulator image with the same number of channels as input image, 32-bit or 64-bit
2661 : floating-point.
2662 : @param mask Optional operation mask.
2663 :
2664 : @sa accumulateSquare, accumulateProduct, accumulateWeighted
2665 : */
2666 : CV_EXPORTS_W void accumulateSquare( InputArray src, InputOutputArray dst,
2667 : InputArray mask = noArray() );
2668 :
2669 : /** @brief Adds the per-element product of two input images to the accumulator image.
2670 :
2671 : The function adds the product of two images or their selected regions to the accumulator dst :
2672 :
2673 : \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]
2674 :
2675 : The function supports multi-channel images. Each channel is processed independently.
2676 :
2677 : @param src1 First input image, 1- or 3-channel, 8-bit or 32-bit floating point.
2678 : @param src2 Second input image of the same type and the same size as src1 .
2679 : @param dst %Accumulator image with the same number of channels as input images, 32-bit or 64-bit
2680 : floating-point.
2681 : @param mask Optional operation mask.
2682 :
2683 : @sa accumulate, accumulateSquare, accumulateWeighted
2684 : */
2685 : CV_EXPORTS_W void accumulateProduct( InputArray src1, InputArray src2,
2686 : InputOutputArray dst, InputArray mask=noArray() );
2687 :
2688 : /** @brief Updates a running average.
2689 :
2690 : The function calculates the weighted sum of the input image src and the accumulator dst so that dst
2691 : becomes a running average of a frame sequence:
2692 :
2693 : \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]
2694 :
2695 : That is, alpha regulates the update speed (how fast the accumulator "forgets" about earlier images).
2696 : The function supports multi-channel images. Each channel is processed independently.
2697 :
2698 : @param src Input image as 1- or 3-channel, 8-bit or 32-bit floating point.
2699 : @param dst %Accumulator image with the same number of channels as input image, 32-bit or 64-bit
2700 : floating-point.
2701 : @param alpha Weight of the input image.
2702 : @param mask Optional operation mask.
2703 :
2704 : @sa accumulate, accumulateSquare, accumulateProduct
2705 : */
2706 : CV_EXPORTS_W void accumulateWeighted( InputArray src, InputOutputArray dst,
2707 : double alpha, InputArray mask = noArray() );
2708 :
2709 : /** @brief The function is used to detect translational shifts that occur between two images.
2710 :
2711 : The operation takes advantage of the Fourier shift theorem for detecting the translational shift in
2712 : the frequency domain. It can be used for fast image registration as well as motion estimation. For
2713 : more information please see <http://en.wikipedia.org/wiki/Phase_correlation>
2714 :
2715 : Calculates the cross-power spectrum of two supplied source arrays. The arrays are padded if needed
2716 : with getOptimalDFTSize.
2717 :
2718 : The function performs the following equations:
2719 : - First it applies a Hanning window (see <http://en.wikipedia.org/wiki/Hann_function>) to each
2720 : image to remove possible edge effects. This window is cached until the array size changes to speed
2721 : up processing time.
2722 : - Next it computes the forward DFTs of each source array:
2723 : \f[\mathbf{G}_a = \mathcal{F}\{src_1\}, \; \mathbf{G}_b = \mathcal{F}\{src_2\}\f]
2724 : where \f$\mathcal{F}\f$ is the forward DFT.
2725 : - It then computes the cross-power spectrum of each frequency domain array:
2726 : \f[R = \frac{ \mathbf{G}_a \mathbf{G}_b^*}{|\mathbf{G}_a \mathbf{G}_b^*|}\f]
2727 : - Next the cross-correlation is converted back into the time domain via the inverse DFT:
2728 : \f[r = \mathcal{F}^{-1}\{R\}\f]
2729 : - Finally, it computes the peak location and computes a 5x5 weighted centroid around the peak to
2730 : achieve sub-pixel accuracy.
2731 : \f[(\Delta x, \Delta y) = \texttt{weightedCentroid} \{\arg \max_{(x, y)}\{r\}\}\f]
2732 : - If non-zero, the response parameter is computed as the sum of the elements of r within the 5x5
2733 : centroid around the peak location. It is normalized to a maximum of 1 (meaning there is a single
2734 : peak) and will be smaller when there are multiple peaks.
2735 :
2736 : @param src1 Source floating point array (CV_32FC1 or CV_64FC1)
2737 : @param src2 Source floating point array (CV_32FC1 or CV_64FC1)
2738 : @param window Floating point array with windowing coefficients to reduce edge effects (optional).
2739 : @param response Signal power within the 5x5 centroid around the peak, between 0 and 1 (optional).
2740 : @returns detected phase shift (sub-pixel) between the two arrays.
2741 :
2742 : @sa dft, getOptimalDFTSize, idft, mulSpectrums createHanningWindow
2743 : */
2744 : CV_EXPORTS_W Point2d phaseCorrelate(InputArray src1, InputArray src2,
2745 : InputArray window = noArray(), CV_OUT double* response = 0);
2746 :
2747 : /** @brief This function computes a Hanning window coefficients in two dimensions.
2748 :
2749 : See (http://en.wikipedia.org/wiki/Hann_function) and (http://en.wikipedia.org/wiki/Window_function)
2750 : for more information.
2751 :
2752 : An example is shown below:
2753 : @code
2754 : // create hanning window of size 100x100 and type CV_32F
2755 : Mat hann;
2756 : createHanningWindow(hann, Size(100, 100), CV_32F);
2757 : @endcode
2758 : @param dst Destination array to place Hann coefficients in
2759 : @param winSize The window size specifications (both width and height must be > 1)
2760 : @param type Created array type
2761 : */
2762 : CV_EXPORTS_W void createHanningWindow(OutputArray dst, Size winSize, int type);
2763 :
2764 : //! @} imgproc_motion
2765 :
2766 : //! @addtogroup imgproc_misc
2767 : //! @{
2768 :
2769 : /** @brief Applies a fixed-level threshold to each array element.
2770 :
2771 : The function applies fixed-level thresholding to a multiple-channel array. The function is typically
2772 : used to get a bi-level (binary) image out of a grayscale image ( cv::compare could be also used for
2773 : this purpose) or for removing a noise, that is, filtering out pixels with too small or too large
2774 : values. There are several types of thresholding supported by the function. They are determined by
2775 : type parameter.
2776 :
2777 : Also, the special values cv::THRESH_OTSU or cv::THRESH_TRIANGLE may be combined with one of the
2778 : above values. In these cases, the function determines the optimal threshold value using the Otsu's
2779 : or Triangle algorithm and uses it instead of the specified thresh . The function returns the
2780 : computed threshold value. Currently, the Otsu's and Triangle methods are implemented only for 8-bit
2781 : images.
2782 :
2783 : @note Input image should be single channel only in case of CV_THRESH_OTSU or CV_THRESH_TRIANGLE flags
2784 :
2785 : @param src input array (multiple-channel, 8-bit or 32-bit floating point).
2786 : @param dst output array of the same size and type and the same number of channels as src.
2787 : @param thresh threshold value.
2788 : @param maxval maximum value to use with the THRESH_BINARY and THRESH_BINARY_INV thresholding
2789 : types.
2790 : @param type thresholding type (see the cv::ThresholdTypes).
2791 :
2792 : @sa adaptiveThreshold, findContours, compare, min, max
2793 : */
2794 : CV_EXPORTS_W double threshold( InputArray src, OutputArray dst,
2795 : double thresh, double maxval, int type );
2796 :
2797 :
2798 : /** @brief Applies an adaptive threshold to an array.
2799 :
2800 : The function transforms a grayscale image to a binary image according to the formulae:
2801 : - **THRESH_BINARY**
2802 : \f[dst(x,y) = \fork{\texttt{maxValue}}{if \(src(x,y) > T(x,y)\)}{0}{otherwise}\f]
2803 : - **THRESH_BINARY_INV**
2804 : \f[dst(x,y) = \fork{0}{if \(src(x,y) > T(x,y)\)}{\texttt{maxValue}}{otherwise}\f]
2805 : where \f$T(x,y)\f$ is a threshold calculated individually for each pixel (see adaptiveMethod parameter).
2806 :
2807 : The function can process the image in-place.
2808 :
2809 : @param src Source 8-bit single-channel image.
2810 : @param dst Destination image of the same size and the same type as src.
2811 : @param maxValue Non-zero value assigned to the pixels for which the condition is satisfied
2812 : @param adaptiveMethod Adaptive thresholding algorithm to use, see cv::AdaptiveThresholdTypes.
2813 : The BORDER_REPLICATE | BORDER_ISOLATED is used to process boundaries.
2814 : @param thresholdType Thresholding type that must be either THRESH_BINARY or THRESH_BINARY_INV,
2815 : see cv::ThresholdTypes.
2816 : @param blockSize Size of a pixel neighborhood that is used to calculate a threshold value for the
2817 : pixel: 3, 5, 7, and so on.
2818 : @param C Constant subtracted from the mean or weighted mean (see the details below). Normally, it
2819 : is positive but may be zero or negative as well.
2820 :
2821 : @sa threshold, blur, GaussianBlur
2822 : */
2823 : CV_EXPORTS_W void adaptiveThreshold( InputArray src, OutputArray dst,
2824 : double maxValue, int adaptiveMethod,
2825 : int thresholdType, int blockSize, double C );
2826 :
2827 : //! @} imgproc_misc
2828 :
2829 : //! @addtogroup imgproc_filter
2830 : //! @{
2831 :
2832 : /** @example Pyramids.cpp
2833 : An example using pyrDown and pyrUp functions
2834 : */
2835 : /** @brief Blurs an image and downsamples it.
2836 :
2837 : By default, size of the output image is computed as `Size((src.cols+1)/2, (src.rows+1)/2)`, but in
2838 : any case, the following conditions should be satisfied:
2839 :
2840 : \f[\begin{array}{l} | \texttt{dstsize.width} *2-src.cols| \leq 2 \\ | \texttt{dstsize.height} *2-src.rows| \leq 2 \end{array}\f]
2841 :
2842 : The function performs the downsampling step of the Gaussian pyramid construction. First, it
2843 : convolves the source image with the kernel:
2844 :
2845 : \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]
2846 :
2847 : Then, it downsamples the image by rejecting even rows and columns.
2848 :
2849 : @param src input image.
2850 : @param dst output image; it has the specified size and the same type as src.
2851 : @param dstsize size of the output image.
2852 : @param borderType Pixel extrapolation method, see cv::BorderTypes (BORDER_CONSTANT isn't supported)
2853 : */
2854 : CV_EXPORTS_W void pyrDown( InputArray src, OutputArray dst,
2855 : const Size& dstsize = Size(), int borderType = BORDER_DEFAULT );
2856 :
2857 : /** @brief Upsamples an image and then blurs it.
2858 :
2859 : By default, size of the output image is computed as `Size(src.cols\*2, (src.rows\*2)`, but in any
2860 : case, the following conditions should be satisfied:
2861 :
2862 : \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]
2863 :
2864 : The function performs the upsampling step of the Gaussian pyramid construction, though it can
2865 : actually be used to construct the Laplacian pyramid. First, it upsamples the source image by
2866 : injecting even zero rows and columns and then convolves the result with the same kernel as in
2867 : pyrDown multiplied by 4.
2868 :
2869 : @param src input image.
2870 : @param dst output image. It has the specified size and the same type as src .
2871 : @param dstsize size of the output image.
2872 : @param borderType Pixel extrapolation method, see cv::BorderTypes (only BORDER_DEFAULT is supported)
2873 : */
2874 : CV_EXPORTS_W void pyrUp( InputArray src, OutputArray dst,
2875 : const Size& dstsize = Size(), int borderType = BORDER_DEFAULT );
2876 :
2877 : /** @brief Constructs the Gaussian pyramid for an image.
2878 :
2879 : The function constructs a vector of images and builds the Gaussian pyramid by recursively applying
2880 : pyrDown to the previously built pyramid layers, starting from `dst[0]==src`.
2881 :
2882 : @param src Source image. Check pyrDown for the list of supported types.
2883 : @param dst Destination vector of maxlevel+1 images of the same type as src. dst[0] will be the
2884 : same as src. dst[1] is the next pyramid layer, a smoothed and down-sized src, and so on.
2885 : @param maxlevel 0-based index of the last (the smallest) pyramid layer. It must be non-negative.
2886 : @param borderType Pixel extrapolation method, see cv::BorderTypes (BORDER_CONSTANT isn't supported)
2887 : */
2888 : CV_EXPORTS void buildPyramid( InputArray src, OutputArrayOfArrays dst,
2889 : int maxlevel, int borderType = BORDER_DEFAULT );
2890 :
2891 : //! @} imgproc_filter
2892 :
2893 : //! @addtogroup imgproc_transform
2894 : //! @{
2895 :
2896 : /** @brief Transforms an image to compensate for lens distortion.
2897 :
2898 : The function transforms an image to compensate radial and tangential lens distortion.
2899 :
2900 : The function is simply a combination of cv::initUndistortRectifyMap (with unity R ) and cv::remap
2901 : (with bilinear interpolation). See the former function for details of the transformation being
2902 : performed.
2903 :
2904 : Those pixels in the destination image, for which there is no correspondent pixels in the source
2905 : image, are filled with zeros (black color).
2906 :
2907 : A particular subset of the source image that will be visible in the corrected image can be regulated
2908 : by newCameraMatrix. You can use cv::getOptimalNewCameraMatrix to compute the appropriate
2909 : newCameraMatrix depending on your requirements.
2910 :
2911 : The camera matrix and the distortion parameters can be determined using cv::calibrateCamera. If
2912 : the resolution of images is different from the resolution used at the calibration stage, \f$f_x,
2913 : f_y, c_x\f$ and \f$c_y\f$ need to be scaled accordingly, while the distortion coefficients remain
2914 : the same.
2915 :
2916 : @param src Input (distorted) image.
2917 : @param dst Output (corrected) image that has the same size and type as src .
2918 : @param cameraMatrix Input camera matrix \f$A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ .
2919 : @param distCoeffs Input vector of distortion coefficients
2920 : \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$
2921 : of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed.
2922 : @param newCameraMatrix Camera matrix of the distorted image. By default, it is the same as
2923 : cameraMatrix but you may additionally scale and shift the result by using a different matrix.
2924 : */
2925 : CV_EXPORTS_W void undistort( InputArray src, OutputArray dst,
2926 : InputArray cameraMatrix,
2927 : InputArray distCoeffs,
2928 : InputArray newCameraMatrix = noArray() );
2929 :
2930 : /** @brief Computes the undistortion and rectification transformation map.
2931 :
2932 : The function computes the joint undistortion and rectification transformation and represents the
2933 : result in the form of maps for remap. The undistorted image looks like original, as if it is
2934 : captured with a camera using the camera matrix =newCameraMatrix and zero distortion. In case of a
2935 : monocular camera, newCameraMatrix is usually equal to cameraMatrix, or it can be computed by
2936 : cv::getOptimalNewCameraMatrix for a better control over scaling. In case of a stereo camera,
2937 : newCameraMatrix is normally set to P1 or P2 computed by cv::stereoRectify .
2938 :
2939 : Also, this new camera is oriented differently in the coordinate space, according to R. That, for
2940 : example, helps to align two heads of a stereo camera so that the epipolar lines on both images
2941 : become horizontal and have the same y- coordinate (in case of a horizontally aligned stereo camera).
2942 :
2943 : The function actually builds the maps for the inverse mapping algorithm that is used by remap. That
2944 : is, for each pixel \f$(u, v)\f$ in the destination (corrected and rectified) image, the function
2945 : computes the corresponding coordinates in the source image (that is, in the original image from
2946 : camera). The following process is applied:
2947 : \f[
2948 : \begin{array}{l}
2949 : x \leftarrow (u - {c'}_x)/{f'}_x \\
2950 : y \leftarrow (v - {c'}_y)/{f'}_y \\
2951 : {[X\,Y\,W]} ^T \leftarrow R^{-1}*[x \, y \, 1]^T \\
2952 : x' \leftarrow X/W \\
2953 : y' \leftarrow Y/W \\
2954 : r^2 \leftarrow x'^2 + y'^2 \\
2955 : x'' \leftarrow x' \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6}
2956 : + 2p_1 x' y' + p_2(r^2 + 2 x'^2) + s_1 r^2 + s_2 r^4\\
2957 : y'' \leftarrow y' \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6}
2958 : + p_1 (r^2 + 2 y'^2) + 2 p_2 x' y' + s_3 r^2 + s_4 r^4 \\
2959 : s\vecthree{x'''}{y'''}{1} =
2960 : \vecthreethree{R_{33}(\tau_x, \tau_y)}{0}{-R_{13}((\tau_x, \tau_y)}
2961 : {0}{R_{33}(\tau_x, \tau_y)}{-R_{23}(\tau_x, \tau_y)}
2962 : {0}{0}{1} R(\tau_x, \tau_y) \vecthree{x''}{y''}{1}\\
2963 : map_x(u,v) \leftarrow x''' f_x + c_x \\
2964 : map_y(u,v) \leftarrow y''' f_y + c_y
2965 : \end{array}
2966 : \f]
2967 : where \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$
2968 : are the distortion coefficients.
2969 :
2970 : In case of a stereo camera, this function is called twice: once for each camera head, after
2971 : stereoRectify, which in its turn is called after cv::stereoCalibrate. But if the stereo camera
2972 : was not calibrated, it is still possible to compute the rectification transformations directly from
2973 : the fundamental matrix using cv::stereoRectifyUncalibrated. For each camera, the function computes
2974 : homography H as the rectification transformation in a pixel domain, not a rotation matrix R in 3D
2975 : space. R can be computed from H as
2976 : \f[\texttt{R} = \texttt{cameraMatrix} ^{-1} \cdot \texttt{H} \cdot \texttt{cameraMatrix}\f]
2977 : where cameraMatrix can be chosen arbitrarily.
2978 :
2979 : @param cameraMatrix Input camera matrix \f$A=\vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ .
2980 : @param distCoeffs Input vector of distortion coefficients
2981 : \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$
2982 : of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed.
2983 : @param R Optional rectification transformation in the object space (3x3 matrix). R1 or R2 ,
2984 : computed by stereoRectify can be passed here. If the matrix is empty, the identity transformation
2985 : is assumed. In cvInitUndistortMap R assumed to be an identity matrix.
2986 : @param newCameraMatrix New camera matrix \f$A'=\vecthreethree{f_x'}{0}{c_x'}{0}{f_y'}{c_y'}{0}{0}{1}\f$.
2987 : @param size Undistorted image size.
2988 : @param m1type Type of the first output map that can be CV_32FC1, CV_32FC2 or CV_16SC2, see cv::convertMaps
2989 : @param map1 The first output map.
2990 : @param map2 The second output map.
2991 : */
2992 : CV_EXPORTS_W void initUndistortRectifyMap( InputArray cameraMatrix, InputArray distCoeffs,
2993 : InputArray R, InputArray newCameraMatrix,
2994 : Size size, int m1type, OutputArray map1, OutputArray map2 );
2995 :
2996 : //! initializes maps for cv::remap() for wide-angle
2997 : CV_EXPORTS_W float initWideAngleProjMap( InputArray cameraMatrix, InputArray distCoeffs,
2998 : Size imageSize, int destImageWidth,
2999 : int m1type, OutputArray map1, OutputArray map2,
3000 : int projType = PROJ_SPHERICAL_EQRECT, double alpha = 0);
3001 :
3002 : /** @brief Returns the default new camera matrix.
3003 :
3004 : The function returns the camera matrix that is either an exact copy of the input cameraMatrix (when
3005 : centerPrinicipalPoint=false ), or the modified one (when centerPrincipalPoint=true).
3006 :
3007 : In the latter case, the new camera matrix will be:
3008 :
3009 : \f[\begin{bmatrix} f_x && 0 && ( \texttt{imgSize.width} -1)*0.5 \\ 0 && f_y && ( \texttt{imgSize.height} -1)*0.5 \\ 0 && 0 && 1 \end{bmatrix} ,\f]
3010 :
3011 : where \f$f_x\f$ and \f$f_y\f$ are \f$(0,0)\f$ and \f$(1,1)\f$ elements of cameraMatrix, respectively.
3012 :
3013 : By default, the undistortion functions in OpenCV (see initUndistortRectifyMap, undistort) do not
3014 : move the principal point. However, when you work with stereo, it is important to move the principal
3015 : points in both views to the same y-coordinate (which is required by most of stereo correspondence
3016 : algorithms), and may be to the same x-coordinate too. So, you can form the new camera matrix for
3017 : each view where the principal points are located at the center.
3018 :
3019 : @param cameraMatrix Input camera matrix.
3020 : @param imgsize Camera view image size in pixels.
3021 : @param centerPrincipalPoint Location of the principal point in the new camera matrix. The
3022 : parameter indicates whether this location should be at the image center or not.
3023 : */
3024 : CV_EXPORTS_W Mat getDefaultNewCameraMatrix( InputArray cameraMatrix, Size imgsize = Size(),
3025 : bool centerPrincipalPoint = false );
3026 :
3027 : /** @brief Computes the ideal point coordinates from the observed point coordinates.
3028 :
3029 : The function is similar to cv::undistort and cv::initUndistortRectifyMap but it operates on a
3030 : sparse set of points instead of a raster image. Also the function performs a reverse transformation
3031 : to projectPoints. In case of a 3D object, it does not reconstruct its 3D coordinates, but for a
3032 : planar object, it does, up to a translation vector, if the proper R is specified.
3033 :
3034 : For each observed point coordinate \f$(u, v)\f$ the function computes:
3035 : \f[
3036 : \begin{array}{l}
3037 : x^{"} \leftarrow (u - c_x)/f_x \\
3038 : y^{"} \leftarrow (v - c_y)/f_y \\
3039 : (x',y') = undistort(x^{"},y^{"}, \texttt{distCoeffs}) \\
3040 : {[X\,Y\,W]} ^T \leftarrow R*[x' \, y' \, 1]^T \\
3041 : x \leftarrow X/W \\
3042 : y \leftarrow Y/W \\
3043 : \text{only performed if P is specified:} \\
3044 : u' \leftarrow x {f'}_x + {c'}_x \\
3045 : v' \leftarrow y {f'}_y + {c'}_y
3046 : \end{array}
3047 : \f]
3048 :
3049 : where *undistort* is an approximate iterative algorithm that estimates the normalized original
3050 : point coordinates out of the normalized distorted point coordinates ("normalized" means that the
3051 : coordinates do not depend on the camera matrix).
3052 :
3053 : The function can be used for both a stereo camera head or a monocular camera (when R is empty).
3054 :
3055 : @param src Observed point coordinates, 1xN or Nx1 2-channel (CV_32FC2 or CV_64FC2).
3056 : @param dst Output ideal point coordinates after undistortion and reverse perspective
3057 : transformation. If matrix P is identity or omitted, dst will contain normalized point coordinates.
3058 : @param cameraMatrix Camera matrix \f$\vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ .
3059 : @param distCoeffs Input vector of distortion coefficients
3060 : \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$
3061 : of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed.
3062 : @param R Rectification transformation in the object space (3x3 matrix). R1 or R2 computed by
3063 : cv::stereoRectify can be passed here. If the matrix is empty, the identity transformation is used.
3064 : @param P New camera matrix (3x3) or new projection matrix (3x4) \f$\begin{bmatrix} {f'}_x & 0 & {c'}_x & t_x \\ 0 & {f'}_y & {c'}_y & t_y \\ 0 & 0 & 1 & t_z \end{bmatrix}\f$. P1 or P2 computed by
3065 : cv::stereoRectify can be passed here. If the matrix is empty, the identity new camera matrix is used.
3066 : */
3067 : CV_EXPORTS_W void undistortPoints( InputArray src, OutputArray dst,
3068 : InputArray cameraMatrix, InputArray distCoeffs,
3069 : InputArray R = noArray(), InputArray P = noArray());
3070 : /** @overload
3071 : @note Default version of cv::undistortPoints does 5 iterations to compute undistorted points.
3072 :
3073 : */
3074 : CV_EXPORTS_AS(undistortPointsIter) void undistortPoints( InputArray src, OutputArray dst,
3075 : InputArray cameraMatrix, InputArray distCoeffs,
3076 : InputArray R, InputArray P, TermCriteria criteria);
3077 :
3078 : //! @} imgproc_transform
3079 :
3080 : //! @addtogroup imgproc_hist
3081 : //! @{
3082 :
3083 : /** @example demhist.cpp
3084 : An example for creating histograms of an image
3085 : */
3086 :
3087 : /** @brief Calculates a histogram of a set of arrays.
3088 :
3089 : The function cv::calcHist calculates the histogram of one or more arrays. The elements of a tuple used
3090 : to increment a histogram bin are taken from the corresponding input arrays at the same location. The
3091 : sample below shows how to compute a 2D Hue-Saturation histogram for a color image. :
3092 : @code
3093 : #include <opencv2/imgproc.hpp>
3094 : #include <opencv2/highgui.hpp>
3095 :
3096 : using namespace cv;
3097 :
3098 : int main( int argc, char** argv )
3099 : {
3100 : Mat src, hsv;
3101 : if( argc != 2 || !(src=imread(argv[1], 1)).data )
3102 : return -1;
3103 :
3104 : cvtColor(src, hsv, COLOR_BGR2HSV);
3105 :
3106 : // Quantize the hue to 30 levels
3107 : // and the saturation to 32 levels
3108 : int hbins = 30, sbins = 32;
3109 : int histSize[] = {hbins, sbins};
3110 : // hue varies from 0 to 179, see cvtColor
3111 : float hranges[] = { 0, 180 };
3112 : // saturation varies from 0 (black-gray-white) to
3113 : // 255 (pure spectrum color)
3114 : float sranges[] = { 0, 256 };
3115 : const float* ranges[] = { hranges, sranges };
3116 : MatND hist;
3117 : // we compute the histogram from the 0-th and 1-st channels
3118 : int channels[] = {0, 1};
3119 :
3120 : calcHist( &hsv, 1, channels, Mat(), // do not use mask
3121 : hist, 2, histSize, ranges,
3122 : true, // the histogram is uniform
3123 : false );
3124 : double maxVal=0;
3125 : minMaxLoc(hist, 0, &maxVal, 0, 0);
3126 :
3127 : int scale = 10;
3128 : Mat histImg = Mat::zeros(sbins*scale, hbins*10, CV_8UC3);
3129 :
3130 : for( int h = 0; h < hbins; h++ )
3131 : for( int s = 0; s < sbins; s++ )
3132 : {
3133 : float binVal = hist.at<float>(h, s);
3134 : int intensity = cvRound(binVal*255/maxVal);
3135 : rectangle( histImg, Point(h*scale, s*scale),
3136 : Point( (h+1)*scale - 1, (s+1)*scale - 1),
3137 : Scalar::all(intensity),
3138 : CV_FILLED );
3139 : }
3140 :
3141 : namedWindow( "Source", 1 );
3142 : imshow( "Source", src );
3143 :
3144 : namedWindow( "H-S Histogram", 1 );
3145 : imshow( "H-S Histogram", histImg );
3146 : waitKey();
3147 : }
3148 : @endcode
3149 :
3150 : @param images Source arrays. They all should have the same depth, CV_8U, CV_16U or CV_32F , and the same
3151 : size. Each of them can have an arbitrary number of channels.
3152 : @param nimages Number of source images.
3153 : @param channels List of the dims channels used to compute the histogram. The first array channels
3154 : are numerated from 0 to images[0].channels()-1 , the second array channels are counted from
3155 : images[0].channels() to images[0].channels() + images[1].channels()-1, and so on.
3156 : @param mask Optional mask. If the matrix is not empty, it must be an 8-bit array of the same size
3157 : as images[i] . The non-zero mask elements mark the array elements counted in the histogram.
3158 : @param hist Output histogram, which is a dense or sparse dims -dimensional array.
3159 : @param dims Histogram dimensionality that must be positive and not greater than CV_MAX_DIMS
3160 : (equal to 32 in the current OpenCV version).
3161 : @param histSize Array of histogram sizes in each dimension.
3162 : @param ranges Array of the dims arrays of the histogram bin boundaries in each dimension. When the
3163 : histogram is uniform ( uniform =true), then for each dimension i it is enough to specify the lower
3164 : (inclusive) boundary \f$L_0\f$ of the 0-th histogram bin and the upper (exclusive) boundary
3165 : \f$U_{\texttt{histSize}[i]-1}\f$ for the last histogram bin histSize[i]-1 . That is, in case of a
3166 : uniform histogram each of ranges[i] is an array of 2 elements. When the histogram is not uniform (
3167 : uniform=false ), then each of ranges[i] contains histSize[i]+1 elements:
3168 : \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$
3169 : . The array elements, that are not between \f$L_0\f$ and \f$U_{\texttt{histSize[i]}-1}\f$ , are not
3170 : counted in the histogram.
3171 : @param uniform Flag indicating whether the histogram is uniform or not (see above).
3172 : @param accumulate Accumulation flag. If it is set, the histogram is not cleared in the beginning
3173 : when it is allocated. This feature enables you to compute a single histogram from several sets of
3174 : arrays, or to update the histogram in time.
3175 : */
3176 : CV_EXPORTS void calcHist( const Mat* images, int nimages,
3177 : const int* channels, InputArray mask,
3178 : OutputArray hist, int dims, const int* histSize,
3179 : const float** ranges, bool uniform = true, bool accumulate = false );
3180 :
3181 : /** @overload
3182 :
3183 : this variant uses cv::SparseMat for output
3184 : */
3185 : CV_EXPORTS void calcHist( const Mat* images, int nimages,
3186 : const int* channels, InputArray mask,
3187 : SparseMat& hist, int dims,
3188 : const int* histSize, const float** ranges,
3189 : bool uniform = true, bool accumulate = false );
3190 :
3191 : /** @overload */
3192 : CV_EXPORTS_W void calcHist( InputArrayOfArrays images,
3193 : const std::vector<int>& channels,
3194 : InputArray mask, OutputArray hist,
3195 : const std::vector<int>& histSize,
3196 : const std::vector<float>& ranges,
3197 : bool accumulate = false );
3198 :
3199 : /** @brief Calculates the back projection of a histogram.
3200 :
3201 : The function cv::calcBackProject calculates the back project of the histogram. That is, similarly to
3202 : cv::calcHist , at each location (x, y) the function collects the values from the selected channels
3203 : in the input images and finds the corresponding histogram bin. But instead of incrementing it, the
3204 : function reads the bin value, scales it by scale , and stores in backProject(x,y) . In terms of
3205 : statistics, the function computes probability of each element value in respect with the empirical
3206 : probability distribution represented by the histogram. See how, for example, you can find and track
3207 : a bright-colored object in a scene:
3208 :
3209 : - Before tracking, show the object to the camera so that it covers almost the whole frame.
3210 : Calculate a hue histogram. The histogram may have strong maximums, corresponding to the dominant
3211 : colors in the object.
3212 :
3213 : - When tracking, calculate a back projection of a hue plane of each input video frame using that
3214 : pre-computed histogram. Threshold the back projection to suppress weak colors. It may also make
3215 : sense to suppress pixels with non-sufficient color saturation and too dark or too bright pixels.
3216 :
3217 : - Find connected components in the resulting picture and choose, for example, the largest
3218 : component.
3219 :
3220 : This is an approximate algorithm of the CamShift color object tracker.
3221 :
3222 : @param images Source arrays. They all should have the same depth, CV_8U, CV_16U or CV_32F , and the same
3223 : size. Each of them can have an arbitrary number of channels.
3224 : @param nimages Number of source images.
3225 : @param channels The list of channels used to compute the back projection. The number of channels
3226 : must match the histogram dimensionality. The first array channels are numerated from 0 to
3227 : images[0].channels()-1 , the second array channels are counted from images[0].channels() to
3228 : images[0].channels() + images[1].channels()-1, and so on.
3229 : @param hist Input histogram that can be dense or sparse.
3230 : @param backProject Destination back projection array that is a single-channel array of the same
3231 : size and depth as images[0] .
3232 : @param ranges Array of arrays of the histogram bin boundaries in each dimension. See cv::calcHist .
3233 : @param scale Optional scale factor for the output back projection.
3234 : @param uniform Flag indicating whether the histogram is uniform or not (see above).
3235 :
3236 : @sa cv::calcHist, cv::compareHist
3237 : */
3238 : CV_EXPORTS void calcBackProject( const Mat* images, int nimages,
3239 : const int* channels, InputArray hist,
3240 : OutputArray backProject, const float** ranges,
3241 : double scale = 1, bool uniform = true );
3242 :
3243 : /** @overload */
3244 : CV_EXPORTS void calcBackProject( const Mat* images, int nimages,
3245 : const int* channels, const SparseMat& hist,
3246 : OutputArray backProject, const float** ranges,
3247 : double scale = 1, bool uniform = true );
3248 :
3249 : /** @overload */
3250 : CV_EXPORTS_W void calcBackProject( InputArrayOfArrays images, const std::vector<int>& channels,
3251 : InputArray hist, OutputArray dst,
3252 : const std::vector<float>& ranges,
3253 : double scale );
3254 :
3255 : /** @brief Compares two histograms.
3256 :
3257 : The function cv::compareHist compares two dense or two sparse histograms using the specified method.
3258 :
3259 : The function returns \f$d(H_1, H_2)\f$ .
3260 :
3261 : While the function works well with 1-, 2-, 3-dimensional dense histograms, it may not be suitable
3262 : for high-dimensional sparse histograms. In such histograms, because of aliasing and sampling
3263 : problems, the coordinates of non-zero histogram bins can slightly shift. To compare such histograms
3264 : or more general sparse configurations of weighted points, consider using the cv::EMD function.
3265 :
3266 : @param H1 First compared histogram.
3267 : @param H2 Second compared histogram of the same size as H1 .
3268 : @param method Comparison method, see cv::HistCompMethods
3269 : */
3270 : CV_EXPORTS_W double compareHist( InputArray H1, InputArray H2, int method );
3271 :
3272 : /** @overload */
3273 : CV_EXPORTS double compareHist( const SparseMat& H1, const SparseMat& H2, int method );
3274 :
3275 : /** @brief Equalizes the histogram of a grayscale image.
3276 :
3277 : The function equalizes the histogram of the input image using the following algorithm:
3278 :
3279 : - Calculate the histogram \f$H\f$ for src .
3280 : - Normalize the histogram so that the sum of histogram bins is 255.
3281 : - Compute the integral of the histogram:
3282 : \f[H'_i = \sum _{0 \le j < i} H(j)\f]
3283 : - Transform the image using \f$H'\f$ as a look-up table: \f$\texttt{dst}(x,y) = H'(\texttt{src}(x,y))\f$
3284 :
3285 : The algorithm normalizes the brightness and increases the contrast of the image.
3286 :
3287 : @param src Source 8-bit single channel image.
3288 : @param dst Destination image of the same size and type as src .
3289 : */
3290 : CV_EXPORTS_W void equalizeHist( InputArray src, OutputArray dst );
3291 :
3292 : /** @brief Computes the "minimal work" distance between two weighted point configurations.
3293 :
3294 : The function computes the earth mover distance and/or a lower boundary of the distance between the
3295 : two weighted point configurations. One of the applications described in @cite RubnerSept98,
3296 : @cite Rubner2000 is multi-dimensional histogram comparison for image retrieval. EMD is a transportation
3297 : problem that is solved using some modification of a simplex algorithm, thus the complexity is
3298 : exponential in the worst case, though, on average it is much faster. In the case of a real metric
3299 : the lower boundary can be calculated even faster (using linear-time algorithm) and it can be used
3300 : to determine roughly whether the two signatures are far enough so that they cannot relate to the
3301 : same object.
3302 :
3303 : @param signature1 First signature, a \f$\texttt{size1}\times \texttt{dims}+1\f$ floating-point matrix.
3304 : Each row stores the point weight followed by the point coordinates. The matrix is allowed to have
3305 : a single column (weights only) if the user-defined cost matrix is used. The weights must be
3306 : non-negative and have at least one non-zero value.
3307 : @param signature2 Second signature of the same format as signature1 , though the number of rows
3308 : may be different. The total weights may be different. In this case an extra "dummy" point is added
3309 : to either signature1 or signature2. The weights must be non-negative and have at least one non-zero
3310 : value.
3311 : @param distType Used metric. See cv::DistanceTypes.
3312 : @param cost User-defined \f$\texttt{size1}\times \texttt{size2}\f$ cost matrix. Also, if a cost matrix
3313 : is used, lower boundary lowerBound cannot be calculated because it needs a metric function.
3314 : @param lowerBound Optional input/output parameter: lower boundary of a distance between the two
3315 : signatures that is a distance between mass centers. The lower boundary may not be calculated if
3316 : the user-defined cost matrix is used, the total weights of point configurations are not equal, or
3317 : if the signatures consist of weights only (the signature matrices have a single column). You
3318 : **must** initialize \*lowerBound . If the calculated distance between mass centers is greater or
3319 : equal to \*lowerBound (it means that the signatures are far enough), the function does not
3320 : calculate EMD. In any case \*lowerBound is set to the calculated distance between mass centers on
3321 : return. Thus, if you want to calculate both distance between mass centers and EMD, \*lowerBound
3322 : should be set to 0.
3323 : @param flow Resultant \f$\texttt{size1} \times \texttt{size2}\f$ flow matrix: \f$\texttt{flow}_{i,j}\f$ is
3324 : a flow from \f$i\f$ -th point of signature1 to \f$j\f$ -th point of signature2 .
3325 : */
3326 : CV_EXPORTS float EMD( InputArray signature1, InputArray signature2,
3327 : int distType, InputArray cost=noArray(),
3328 : float* lowerBound = 0, OutputArray flow = noArray() );
3329 :
3330 : CV_EXPORTS_AS(EMD) float wrapperEMD( InputArray signature1, InputArray signature2,
3331 : int distType, InputArray cost=noArray(),
3332 : CV_IN_OUT Ptr<float> lowerBound = Ptr<float>(), OutputArray flow = noArray() );
3333 :
3334 : //! @} imgproc_hist
3335 :
3336 : /** @example watershed.cpp
3337 : An example using the watershed algorithm
3338 : */
3339 :
3340 : /** @brief Performs a marker-based image segmentation using the watershed algorithm.
3341 :
3342 : The function implements one of the variants of watershed, non-parametric marker-based segmentation
3343 : algorithm, described in @cite Meyer92 .
3344 :
3345 : Before passing the image to the function, you have to roughly outline the desired regions in the
3346 : image markers with positive (\>0) indices. So, every region is represented as one or more connected
3347 : components with the pixel values 1, 2, 3, and so on. Such markers can be retrieved from a binary
3348 : mask using findContours and drawContours (see the watershed.cpp demo). The markers are "seeds" of
3349 : the future image regions. All the other pixels in markers , whose relation to the outlined regions
3350 : is not known and should be defined by the algorithm, should be set to 0's. In the function output,
3351 : each pixel in markers is set to a value of the "seed" components or to -1 at boundaries between the
3352 : regions.
3353 :
3354 : @note Any two neighbor connected components are not necessarily separated by a watershed boundary
3355 : (-1's pixels); for example, they can touch each other in the initial marker image passed to the
3356 : function.
3357 :
3358 : @param image Input 8-bit 3-channel image.
3359 : @param markers Input/output 32-bit single-channel image (map) of markers. It should have the same
3360 : size as image .
3361 :
3362 : @sa findContours
3363 :
3364 : @ingroup imgproc_misc
3365 : */
3366 : CV_EXPORTS_W void watershed( InputArray image, InputOutputArray markers );
3367 :
3368 : //! @addtogroup imgproc_filter
3369 : //! @{
3370 :
3371 : /** @brief Performs initial step of meanshift segmentation of an image.
3372 :
3373 : The function implements the filtering stage of meanshift segmentation, that is, the output of the
3374 : function is the filtered "posterized" image with color gradients and fine-grain texture flattened.
3375 : At every pixel (X,Y) of the input image (or down-sized input image, see below) the function executes
3376 : meanshift iterations, that is, the pixel (X,Y) neighborhood in the joint space-color hyperspace is
3377 : considered:
3378 :
3379 : \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]
3380 :
3381 : where (R,G,B) and (r,g,b) are the vectors of color components at (X,Y) and (x,y), respectively
3382 : (though, the algorithm does not depend on the color space used, so any 3-component color space can
3383 : be used instead). Over the neighborhood the average spatial value (X',Y') and average color vector
3384 : (R',G',B') are found and they act as the neighborhood center on the next iteration:
3385 :
3386 : \f[(X,Y)~(X',Y'), (R,G,B)~(R',G',B').\f]
3387 :
3388 : After the iterations over, the color components of the initial pixel (that is, the pixel from where
3389 : the iterations started) are set to the final value (average color at the last iteration):
3390 :
3391 : \f[I(X,Y) <- (R*,G*,B*)\f]
3392 :
3393 : When maxLevel \> 0, the gaussian pyramid of maxLevel+1 levels is built, and the above procedure is
3394 : run on the smallest layer first. After that, the results are propagated to the larger layer and the
3395 : iterations are run again only on those pixels where the layer colors differ by more than sr from the
3396 : lower-resolution layer of the pyramid. That makes boundaries of color regions sharper. Note that the
3397 : results will be actually different from the ones obtained by running the meanshift procedure on the
3398 : whole original image (i.e. when maxLevel==0).
3399 :
3400 : @param src The source 8-bit, 3-channel image.
3401 : @param dst The destination image of the same format and the same size as the source.
3402 : @param sp The spatial window radius.
3403 : @param sr The color window radius.
3404 : @param maxLevel Maximum level of the pyramid for the segmentation.
3405 : @param termcrit Termination criteria: when to stop meanshift iterations.
3406 : */
3407 : CV_EXPORTS_W void pyrMeanShiftFiltering( InputArray src, OutputArray dst,
3408 : double sp, double sr, int maxLevel = 1,
3409 : TermCriteria termcrit=TermCriteria(TermCriteria::MAX_ITER+TermCriteria::EPS,5,1) );
3410 :
3411 : //! @}
3412 :
3413 : //! @addtogroup imgproc_misc
3414 : //! @{
3415 :
3416 : /** @example grabcut.cpp
3417 : An example using the GrabCut algorithm
3418 : ![Sample Screenshot](grabcut_output1.jpg)
3419 : */
3420 :
3421 : /** @brief Runs the GrabCut algorithm.
3422 :
3423 : The function implements the [GrabCut image segmentation algorithm](http://en.wikipedia.org/wiki/GrabCut).
3424 :
3425 : @param img Input 8-bit 3-channel image.
3426 : @param mask Input/output 8-bit single-channel mask. The mask is initialized by the function when
3427 : mode is set to GC_INIT_WITH_RECT. Its elements may have one of the cv::GrabCutClasses.
3428 : @param rect ROI containing a segmented object. The pixels outside of the ROI are marked as
3429 : "obvious background". The parameter is only used when mode==GC_INIT_WITH_RECT .
3430 : @param bgdModel Temporary array for the background model. Do not modify it while you are
3431 : processing the same image.
3432 : @param fgdModel Temporary arrays for the foreground model. Do not modify it while you are
3433 : processing the same image.
3434 : @param iterCount Number of iterations the algorithm should make before returning the result. Note
3435 : that the result can be refined with further calls with mode==GC_INIT_WITH_MASK or
3436 : mode==GC_EVAL .
3437 : @param mode Operation mode that could be one of the cv::GrabCutModes
3438 : */
3439 : CV_EXPORTS_W void grabCut( InputArray img, InputOutputArray mask, Rect rect,
3440 : InputOutputArray bgdModel, InputOutputArray fgdModel,
3441 : int iterCount, int mode = GC_EVAL );
3442 :
3443 : /** @example distrans.cpp
3444 : An example on using the distance transform\
3445 : */
3446 :
3447 :
3448 : /** @brief Calculates the distance to the closest zero pixel for each pixel of the source image.
3449 :
3450 : The function cv::distanceTransform calculates the approximate or precise distance from every binary
3451 : image pixel to the nearest zero pixel. For zero image pixels, the distance will obviously be zero.
3452 :
3453 : When maskSize == DIST_MASK_PRECISE and distanceType == DIST_L2 , the function runs the
3454 : algorithm described in @cite Felzenszwalb04 . This algorithm is parallelized with the TBB library.
3455 :
3456 : In other cases, the algorithm @cite Borgefors86 is used. This means that for a pixel the function
3457 : finds the shortest path to the nearest zero pixel consisting of basic shifts: horizontal, vertical,
3458 : diagonal, or knight's move (the latest is available for a \f$5\times 5\f$ mask). The overall
3459 : distance is calculated as a sum of these basic distances. Since the distance function should be
3460 : symmetric, all of the horizontal and vertical shifts must have the same cost (denoted as a ), all
3461 : the diagonal shifts must have the same cost (denoted as `b`), and all knight's moves must have the
3462 : same cost (denoted as `c`). For the cv::DIST_C and cv::DIST_L1 types, the distance is calculated
3463 : precisely, whereas for cv::DIST_L2 (Euclidean distance) the distance can be calculated only with a
3464 : relative error (a \f$5\times 5\f$ mask gives more accurate results). For `a`,`b`, and `c`, OpenCV
3465 : uses the values suggested in the original paper:
3466 : - DIST_L1: `a = 1, b = 2`
3467 : - DIST_L2:
3468 : - `3 x 3`: `a=0.955, b=1.3693`
3469 : - `5 x 5`: `a=1, b=1.4, c=2.1969`
3470 : - DIST_C: `a = 1, b = 1`
3471 :
3472 : Typically, for a fast, coarse distance estimation DIST_L2, a \f$3\times 3\f$ mask is used. For a
3473 : more accurate distance estimation DIST_L2, a \f$5\times 5\f$ mask or the precise algorithm is used.
3474 : Note that both the precise and the approximate algorithms are linear on the number of pixels.
3475 :
3476 : This variant of the function does not only compute the minimum distance for each pixel \f$(x, y)\f$
3477 : but also identifies the nearest connected component consisting of zero pixels
3478 : (labelType==DIST_LABEL_CCOMP) or the nearest zero pixel (labelType==DIST_LABEL_PIXEL). Index of the
3479 : component/pixel is stored in `labels(x, y)`. When labelType==DIST_LABEL_CCOMP, the function
3480 : automatically finds connected components of zero pixels in the input image and marks them with
3481 : distinct labels. When labelType==DIST_LABEL_CCOMP, the function scans through the input image and
3482 : marks all the zero pixels with distinct labels.
3483 :
3484 : In this mode, the complexity is still linear. That is, the function provides a very fast way to
3485 : compute the Voronoi diagram for a binary image. Currently, the second variant can use only the
3486 : approximate distance transform algorithm, i.e. maskSize=DIST_MASK_PRECISE is not supported
3487 : yet.
3488 :
3489 : @param src 8-bit, single-channel (binary) source image.
3490 : @param dst Output image with calculated distances. It is a 8-bit or 32-bit floating-point,
3491 : single-channel image of the same size as src.
3492 : @param labels Output 2D array of labels (the discrete Voronoi diagram). It has the type
3493 : CV_32SC1 and the same size as src.
3494 : @param distanceType Type of distance, see cv::DistanceTypes
3495 : @param maskSize Size of the distance transform mask, see cv::DistanceTransformMasks.
3496 : DIST_MASK_PRECISE is not supported by this variant. In case of the DIST_L1 or DIST_C distance type,
3497 : the parameter is forced to 3 because a \f$3\times 3\f$ mask gives the same result as \f$5\times
3498 : 5\f$ or any larger aperture.
3499 : @param labelType Type of the label array to build, see cv::DistanceTransformLabelTypes.
3500 : */
3501 : CV_EXPORTS_AS(distanceTransformWithLabels) void distanceTransform( InputArray src, OutputArray dst,
3502 : OutputArray labels, int distanceType, int maskSize,
3503 : int labelType = DIST_LABEL_CCOMP );
3504 :
3505 : /** @overload
3506 : @param src 8-bit, single-channel (binary) source image.
3507 : @param dst Output image with calculated distances. It is a 8-bit or 32-bit floating-point,
3508 : single-channel image of the same size as src .
3509 : @param distanceType Type of distance, see cv::DistanceTypes
3510 : @param maskSize Size of the distance transform mask, see cv::DistanceTransformMasks. In case of the
3511 : DIST_L1 or DIST_C distance type, the parameter is forced to 3 because a \f$3\times 3\f$ mask gives
3512 : the same result as \f$5\times 5\f$ or any larger aperture.
3513 : @param dstType Type of output image. It can be CV_8U or CV_32F. Type CV_8U can be used only for
3514 : the first variant of the function and distanceType == DIST_L1.
3515 : */
3516 : CV_EXPORTS_W void distanceTransform( InputArray src, OutputArray dst,
3517 : int distanceType, int maskSize, int dstType=CV_32F);
3518 :
3519 : /** @example ffilldemo.cpp
3520 : An example using the FloodFill technique
3521 : */
3522 :
3523 : /** @overload
3524 :
3525 : variant without `mask` parameter
3526 : */
3527 : CV_EXPORTS int floodFill( InputOutputArray image,
3528 : Point seedPoint, Scalar newVal, CV_OUT Rect* rect = 0,
3529 : Scalar loDiff = Scalar(), Scalar upDiff = Scalar(),
3530 : int flags = 4 );
3531 :
3532 : /** @brief Fills a connected component with the given color.
3533 :
3534 : The function cv::floodFill fills a connected component starting from the seed point with the specified
3535 : color. The connectivity is determined by the color/brightness closeness of the neighbor pixels. The
3536 : pixel at \f$(x,y)\f$ is considered to belong to the repainted domain if:
3537 :
3538 : - in case of a grayscale image and floating range
3539 : \f[\texttt{src} (x',y')- \texttt{loDiff} \leq \texttt{src} (x,y) \leq \texttt{src} (x',y')+ \texttt{upDiff}\f]
3540 :
3541 :
3542 : - in case of a grayscale image and fixed range
3543 : \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]
3544 :
3545 :
3546 : - in case of a color image and floating range
3547 : \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]
3548 : \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]
3549 : and
3550 : \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]
3551 :
3552 :
3553 : - in case of a color image and fixed range
3554 : \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]
3555 : \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]
3556 : and
3557 : \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]
3558 :
3559 :
3560 : where \f$src(x',y')\f$ is the value of one of pixel neighbors that is already known to belong to the
3561 : component. That is, to be added to the connected component, a color/brightness of the pixel should
3562 : be close enough to:
3563 : - Color/brightness of one of its neighbors that already belong to the connected component in case
3564 : of a floating range.
3565 : - Color/brightness of the seed point in case of a fixed range.
3566 :
3567 : Use these functions to either mark a connected component with the specified color in-place, or build
3568 : a mask and then extract the contour, or copy the region to another image, and so on.
3569 :
3570 : @param image Input/output 1- or 3-channel, 8-bit, or floating-point image. It is modified by the
3571 : function unless the FLOODFILL_MASK_ONLY flag is set in the second variant of the function. See
3572 : the details below.
3573 : @param mask Operation mask that should be a single-channel 8-bit image, 2 pixels wider and 2 pixels
3574 : taller than image. Since this is both an input and output parameter, you must take responsibility
3575 : of initializing it. Flood-filling cannot go across non-zero pixels in the input mask. For example,
3576 : an edge detector output can be used as a mask to stop filling at edges. On output, pixels in the
3577 : mask corresponding to filled pixels in the image are set to 1 or to the a value specified in flags
3578 : as described below. Additionally, the function fills the border of the mask with ones to simplify
3579 : internal processing. It is therefore possible to use the same mask in multiple calls to the function
3580 : to make sure the filled areas do not overlap.
3581 : @param seedPoint Starting point.
3582 : @param newVal New value of the repainted domain pixels.
3583 : @param loDiff Maximal lower brightness/color difference between the currently observed pixel and
3584 : one of its neighbors belonging to the component, or a seed pixel being added to the component.
3585 : @param upDiff Maximal upper brightness/color difference between the currently observed pixel and
3586 : one of its neighbors belonging to the component, or a seed pixel being added to the component.
3587 : @param rect Optional output parameter set by the function to the minimum bounding rectangle of the
3588 : repainted domain.
3589 : @param flags Operation flags. The first 8 bits contain a connectivity value. The default value of
3590 : 4 means that only the four nearest neighbor pixels (those that share an edge) are considered. A
3591 : connectivity value of 8 means that the eight nearest neighbor pixels (those that share a corner)
3592 : will be considered. The next 8 bits (8-16) contain a value between 1 and 255 with which to fill
3593 : the mask (the default value is 1). For example, 4 | ( 255 \<\< 8 ) will consider 4 nearest
3594 : neighbours and fill the mask with a value of 255. The following additional options occupy higher
3595 : bits and therefore may be further combined with the connectivity and mask fill values using
3596 : bit-wise or (|), see cv::FloodFillFlags.
3597 :
3598 : @note Since the mask is larger than the filled image, a pixel \f$(x, y)\f$ in image corresponds to the
3599 : pixel \f$(x+1, y+1)\f$ in the mask .
3600 :
3601 : @sa findContours
3602 : */
3603 : CV_EXPORTS_W int floodFill( InputOutputArray image, InputOutputArray mask,
3604 : Point seedPoint, Scalar newVal, CV_OUT Rect* rect=0,
3605 : Scalar loDiff = Scalar(), Scalar upDiff = Scalar(),
3606 : int flags = 4 );
3607 :
3608 : /** @brief Converts an image from one color space to another.
3609 :
3610 : The function converts an input image from one color space to another. In case of a transformation
3611 : to-from RGB color space, the order of the channels should be specified explicitly (RGB or BGR). Note
3612 : that the default color format in OpenCV is often referred to as RGB but it is actually BGR (the
3613 : bytes are reversed). So the first byte in a standard (24-bit) color image will be an 8-bit Blue
3614 : component, the second byte will be Green, and the third byte will be Red. The fourth, fifth, and
3615 : sixth bytes would then be the second pixel (Blue, then Green, then Red), and so on.
3616 :
3617 : The conventional ranges for R, G, and B channel values are:
3618 : - 0 to 255 for CV_8U images
3619 : - 0 to 65535 for CV_16U images
3620 : - 0 to 1 for CV_32F images
3621 :
3622 : In case of linear transformations, the range does not matter. But in case of a non-linear
3623 : transformation, an input RGB image should be normalized to the proper value range to get the correct
3624 : results, for example, for RGB \f$\rightarrow\f$ L\*u\*v\* transformation. For example, if you have a
3625 : 32-bit floating-point image directly converted from an 8-bit image without any scaling, then it will
3626 : have the 0..255 value range instead of 0..1 assumed by the function. So, before calling cvtColor ,
3627 : you need first to scale the image down:
3628 : @code
3629 : img *= 1./255;
3630 : cvtColor(img, img, COLOR_BGR2Luv);
3631 : @endcode
3632 : If you use cvtColor with 8-bit images, the conversion will have some information lost. For many
3633 : applications, this will not be noticeable but it is recommended to use 32-bit images in applications
3634 : that need the full range of colors or that convert an image before an operation and then convert
3635 : back.
3636 :
3637 : If conversion adds the alpha channel, its value will set to the maximum of corresponding channel
3638 : range: 255 for CV_8U, 65535 for CV_16U, 1 for CV_32F.
3639 :
3640 : @param src input image: 8-bit unsigned, 16-bit unsigned ( CV_16UC... ), or single-precision
3641 : floating-point.
3642 : @param dst output image of the same size and depth as src.
3643 : @param code color space conversion code (see cv::ColorConversionCodes).
3644 : @param dstCn number of channels in the destination image; if the parameter is 0, the number of the
3645 : channels is derived automatically from src and code.
3646 :
3647 : @see @ref imgproc_color_conversions
3648 : */
3649 : CV_EXPORTS_W void cvtColor( InputArray src, OutputArray dst, int code, int dstCn = 0 );
3650 :
3651 : //! @} imgproc_misc
3652 :
3653 : // main function for all demosaicing processes
3654 : CV_EXPORTS_W void demosaicing(InputArray _src, OutputArray _dst, int code, int dcn = 0);
3655 :
3656 : //! @addtogroup imgproc_shape
3657 : //! @{
3658 :
3659 : /** @brief Calculates all of the moments up to the third order of a polygon or rasterized shape.
3660 :
3661 : The function computes moments, up to the 3rd order, of a vector shape or a rasterized shape. The
3662 : results are returned in the structure cv::Moments.
3663 :
3664 : @param array Raster image (single-channel, 8-bit or floating-point 2D array) or an array (
3665 : \f$1 \times N\f$ or \f$N \times 1\f$ ) of 2D points (Point or Point2f ).
3666 : @param binaryImage If it is true, all non-zero image pixels are treated as 1's. The parameter is
3667 : used for images only.
3668 : @returns moments.
3669 :
3670 : @note Only applicable to contour moments calculations from Python bindings: Note that the numpy
3671 : type for the input array should be either np.int32 or np.float32.
3672 :
3673 : @sa contourArea, arcLength
3674 : */
3675 : CV_EXPORTS_W Moments moments( InputArray array, bool binaryImage = false );
3676 :
3677 : /** @brief Calculates seven Hu invariants.
3678 :
3679 : The function calculates seven Hu invariants (introduced in @cite Hu62; see also
3680 : <http://en.wikipedia.org/wiki/Image_moment>) defined as:
3681 :
3682 : \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]
3683 :
3684 : where \f$\eta_{ji}\f$ stands for \f$\texttt{Moments::nu}_{ji}\f$ .
3685 :
3686 : These values are proved to be invariants to the image scale, rotation, and reflection except the
3687 : seventh one, whose sign is changed by reflection. This invariance is proved with the assumption of
3688 : infinite image resolution. In case of raster images, the computed Hu invariants for the original and
3689 : transformed images are a bit different.
3690 :
3691 : @param moments Input moments computed with moments .
3692 : @param hu Output Hu invariants.
3693 :
3694 : @sa matchShapes
3695 : */
3696 : CV_EXPORTS void HuMoments( const Moments& moments, double hu[7] );
3697 :
3698 : /** @overload */
3699 : CV_EXPORTS_W void HuMoments( const Moments& m, OutputArray hu );
3700 :
3701 : //! @} imgproc_shape
3702 :
3703 : //! @addtogroup imgproc_object
3704 : //! @{
3705 :
3706 : //! type of the template matching operation
3707 : enum TemplateMatchModes {
3708 : TM_SQDIFF = 0, //!< \f[R(x,y)= \sum _{x',y'} (T(x',y')-I(x+x',y+y'))^2\f]
3709 : TM_SQDIFF_NORMED = 1, //!< \f[R(x,y)= \frac{\sum_{x',y'} (T(x',y')-I(x+x',y+y'))^2}{\sqrt{\sum_{x',y'}T(x',y')^2 \cdot \sum_{x',y'} I(x+x',y+y')^2}}\f]
3710 : TM_CCORR = 2, //!< \f[R(x,y)= \sum _{x',y'} (T(x',y') \cdot I(x+x',y+y'))\f]
3711 : TM_CCORR_NORMED = 3, //!< \f[R(x,y)= \frac{\sum_{x',y'} (T(x',y') \cdot I(x+x',y+y'))}{\sqrt{\sum_{x',y'}T(x',y')^2 \cdot \sum_{x',y'} I(x+x',y+y')^2}}\f]
3712 : TM_CCOEFF = 4, //!< \f[R(x,y)= \sum _{x',y'} (T'(x',y') \cdot I'(x+x',y+y'))\f]
3713 : //!< where
3714 : //!< \f[\begin{array}{l} T'(x',y')=T(x',y') - 1/(w \cdot h) \cdot \sum _{x'',y''} T(x'',y'') \\ I'(x+x',y+y')=I(x+x',y+y') - 1/(w \cdot h) \cdot \sum _{x'',y''} I(x+x'',y+y'') \end{array}\f]
3715 : TM_CCOEFF_NORMED = 5 //!< \f[R(x,y)= \frac{ \sum_{x',y'} (T'(x',y') \cdot I'(x+x',y+y')) }{ \sqrt{\sum_{x',y'}T'(x',y')^2 \cdot \sum_{x',y'} I'(x+x',y+y')^2} }\f]
3716 : };
3717 :
3718 : /** @example MatchTemplate_Demo.cpp
3719 : An example using Template Matching algorithm
3720 : */
3721 : /** @brief Compares a template against overlapped image regions.
3722 :
3723 : The function slides through image , compares the overlapped patches of size \f$w \times h\f$ against
3724 : templ using the specified method and stores the comparison results in result . Here are the formulae
3725 : for the available comparison methods ( \f$I\f$ denotes image, \f$T\f$ template, \f$R\f$ result ). The summation
3726 : is done over template and/or the image patch: \f$x' = 0...w-1, y' = 0...h-1\f$
3727 :
3728 : After the function finishes the comparison, the best matches can be found as global minimums (when
3729 : TM_SQDIFF was used) or maximums (when TM_CCORR or TM_CCOEFF was used) using the
3730 : minMaxLoc function. In case of a color image, template summation in the numerator and each sum in
3731 : the denominator is done over all of the channels and separate mean values are used for each channel.
3732 : That is, the function can take a color template and a color image. The result will still be a
3733 : single-channel image, which is easier to analyze.
3734 :
3735 : @param image Image where the search is running. It must be 8-bit or 32-bit floating-point.
3736 : @param templ Searched template. It must be not greater than the source image and have the same
3737 : data type.
3738 : @param result Map of comparison results. It must be single-channel 32-bit floating-point. If image
3739 : 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$ .
3740 : @param method Parameter specifying the comparison method, see cv::TemplateMatchModes
3741 : @param mask Mask of searched template. It must have the same datatype and size with templ. It is
3742 : not set by default. Currently, only the TM_SQDIFF and TM_CCORR_NORMED methods are supported.
3743 : */
3744 : CV_EXPORTS_W void matchTemplate( InputArray image, InputArray templ,
3745 : OutputArray result, int method, InputArray mask = noArray() );
3746 :
3747 : //! @}
3748 :
3749 : //! @addtogroup imgproc_shape
3750 : //! @{
3751 :
3752 : /** @brief computes the connected components labeled image of boolean image
3753 :
3754 : image with 4 or 8 way connectivity - returns N, the total number of labels [0, N-1] where 0
3755 : represents the background label. ltype specifies the output label image type, an important
3756 : consideration based on the total number of labels or alternatively the total number of pixels in
3757 : the source image. ccltype specifies the connected components labeling algorithm to use, currently
3758 : Grana (BBDT) and Wu's (SAUF) algorithms are supported, see the cv::ConnectedComponentsAlgorithmsTypes
3759 : for details. Note that SAUF algorithm forces a row major ordering of labels while BBDT does not.
3760 : This function uses parallel version of both Grana and Wu's algorithms if at least one allowed
3761 : parallel framework is enabled and if the rows of the image are at least twice the number returned by getNumberOfCPUs.
3762 :
3763 : @param image the 8-bit single-channel image to be labeled
3764 : @param labels destination labeled image
3765 : @param connectivity 8 or 4 for 8-way or 4-way connectivity respectively
3766 : @param ltype output image label type. Currently CV_32S and CV_16U are supported.
3767 : @param ccltype connected components algorithm type (see the cv::ConnectedComponentsAlgorithmsTypes).
3768 : */
3769 : CV_EXPORTS_AS(connectedComponentsWithAlgorithm) int connectedComponents(InputArray image, OutputArray labels,
3770 : int connectivity, int ltype, int ccltype);
3771 :
3772 :
3773 : /** @overload
3774 :
3775 : @param image the 8-bit single-channel image to be labeled
3776 : @param labels destination labeled image
3777 : @param connectivity 8 or 4 for 8-way or 4-way connectivity respectively
3778 : @param ltype output image label type. Currently CV_32S and CV_16U are supported.
3779 : */
3780 : CV_EXPORTS_W int connectedComponents(InputArray image, OutputArray labels,
3781 : int connectivity = 8, int ltype = CV_32S);
3782 :
3783 :
3784 : /** @brief computes the connected components labeled image of boolean image and also produces a statistics output for each label
3785 :
3786 : image with 4 or 8 way connectivity - returns N, the total number of labels [0, N-1] where 0
3787 : represents the background label. ltype specifies the output label image type, an important
3788 : consideration based on the total number of labels or alternatively the total number of pixels in
3789 : the source image. ccltype specifies the connected components labeling algorithm to use, currently
3790 : Grana's (BBDT) and Wu's (SAUF) algorithms are supported, see the cv::ConnectedComponentsAlgorithmsTypes
3791 : for details. Note that SAUF algorithm forces a row major ordering of labels while BBDT does not.
3792 : This function uses parallel version of both Grana and Wu's algorithms (statistics included) if at least one allowed
3793 : parallel framework is enabled and if the rows of the image are at least twice the number returned by getNumberOfCPUs.
3794 :
3795 : @param image the 8-bit single-channel image to be labeled
3796 : @param labels destination labeled image
3797 : @param stats statistics output for each label, including the background label, see below for
3798 : available statistics. Statistics are accessed via stats(label, COLUMN) where COLUMN is one of
3799 : cv::ConnectedComponentsTypes. The data type is CV_32S.
3800 : @param centroids centroid output for each label, including the background label. Centroids are
3801 : accessed via centroids(label, 0) for x and centroids(label, 1) for y. The data type CV_64F.
3802 : @param connectivity 8 or 4 for 8-way or 4-way connectivity respectively
3803 : @param ltype output image label type. Currently CV_32S and CV_16U are supported.
3804 : @param ccltype connected components algorithm type (see the cv::ConnectedComponentsAlgorithmsTypes).
3805 : */
3806 : CV_EXPORTS_AS(connectedComponentsWithStatsWithAlgorithm) int connectedComponentsWithStats(InputArray image, OutputArray labels,
3807 : OutputArray stats, OutputArray centroids,
3808 : int connectivity, int ltype, int ccltype);
3809 :
3810 : /** @overload
3811 : @param image the 8-bit single-channel image to be labeled
3812 : @param labels destination labeled image
3813 : @param stats statistics output for each label, including the background label, see below for
3814 : available statistics. Statistics are accessed via stats(label, COLUMN) where COLUMN is one of
3815 : cv::ConnectedComponentsTypes. The data type is CV_32S.
3816 : @param centroids centroid output for each label, including the background label. Centroids are
3817 : accessed via centroids(label, 0) for x and centroids(label, 1) for y. The data type CV_64F.
3818 : @param connectivity 8 or 4 for 8-way or 4-way connectivity respectively
3819 : @param ltype output image label type. Currently CV_32S and CV_16U are supported.
3820 : */
3821 : CV_EXPORTS_W int connectedComponentsWithStats(InputArray image, OutputArray labels,
3822 : OutputArray stats, OutputArray centroids,
3823 : int connectivity = 8, int ltype = CV_32S);
3824 :
3825 :
3826 : /** @brief Finds contours in a binary image.
3827 :
3828 : The function retrieves contours from the binary image using the algorithm @cite Suzuki85 . The contours
3829 : are a useful tool for shape analysis and object detection and recognition. See squares.cpp in the
3830 : OpenCV sample directory.
3831 : @note Since opencv 3.2 source image is not modified by this function.
3832 :
3833 : @param image Source, an 8-bit single-channel image. Non-zero pixels are treated as 1's. Zero
3834 : pixels remain 0's, so the image is treated as binary . You can use cv::compare, cv::inRange, cv::threshold ,
3835 : cv::adaptiveThreshold, cv::Canny, and others to create a binary image out of a grayscale or color one.
3836 : If mode equals to cv::RETR_CCOMP or cv::RETR_FLOODFILL, the input can also be a 32-bit integer image of labels (CV_32SC1).
3837 : @param contours Detected contours. Each contour is stored as a vector of points (e.g.
3838 : std::vector<std::vector<cv::Point> >).
3839 : @param hierarchy Optional output vector (e.g. std::vector<cv::Vec4i>), containing information about the image topology. It has
3840 : as many elements as the number of contours. For each i-th contour contours[i], the elements
3841 : hierarchy[i][0] , hierarchy[i][1] , hierarchy[i][2] , and hierarchy[i][3] are set to 0-based indices
3842 : in contours of the next and previous contours at the same hierarchical level, the first child
3843 : contour and the parent contour, respectively. If for the contour i there are no next, previous,
3844 : parent, or nested contours, the corresponding elements of hierarchy[i] will be negative.
3845 : @param mode Contour retrieval mode, see cv::RetrievalModes
3846 : @param method Contour approximation method, see cv::ContourApproximationModes
3847 : @param offset Optional offset by which every contour point is shifted. This is useful if the
3848 : contours are extracted from the image ROI and then they should be analyzed in the whole image
3849 : context.
3850 : */
3851 : CV_EXPORTS_W void findContours( InputOutputArray image, OutputArrayOfArrays contours,
3852 : OutputArray hierarchy, int mode,
3853 : int method, Point offset = Point());
3854 :
3855 : /** @overload */
3856 : CV_EXPORTS void findContours( InputOutputArray image, OutputArrayOfArrays contours,
3857 : int mode, int method, Point offset = Point());
3858 :
3859 : /** @brief Approximates a polygonal curve(s) with the specified precision.
3860 :
3861 : The function cv::approxPolyDP approximates a curve or a polygon with another curve/polygon with less
3862 : vertices so that the distance between them is less or equal to the specified precision. It uses the
3863 : Douglas-Peucker algorithm <http://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm>
3864 :
3865 : @param curve Input vector of a 2D point stored in std::vector or Mat
3866 : @param approxCurve Result of the approximation. The type should match the type of the input curve.
3867 : @param epsilon Parameter specifying the approximation accuracy. This is the maximum distance
3868 : between the original curve and its approximation.
3869 : @param closed If true, the approximated curve is closed (its first and last vertices are
3870 : connected). Otherwise, it is not closed.
3871 : */
3872 : CV_EXPORTS_W void approxPolyDP( InputArray curve,
3873 : OutputArray approxCurve,
3874 : double epsilon, bool closed );
3875 :
3876 : /** @brief Calculates a contour perimeter or a curve length.
3877 :
3878 : The function computes a curve length or a closed contour perimeter.
3879 :
3880 : @param curve Input vector of 2D points, stored in std::vector or Mat.
3881 : @param closed Flag indicating whether the curve is closed or not.
3882 : */
3883 : CV_EXPORTS_W double arcLength( InputArray curve, bool closed );
3884 :
3885 : /** @brief Calculates the up-right bounding rectangle of a point set.
3886 :
3887 : The function calculates and returns the minimal up-right bounding rectangle for the specified point set.
3888 :
3889 : @param points Input 2D point set, stored in std::vector or Mat.
3890 : */
3891 : CV_EXPORTS_W Rect boundingRect( InputArray points );
3892 :
3893 : /** @brief Calculates a contour area.
3894 :
3895 : The function computes a contour area. Similarly to moments , the area is computed using the Green
3896 : formula. Thus, the returned area and the number of non-zero pixels, if you draw the contour using
3897 : drawContours or fillPoly , can be different. Also, the function will most certainly give a wrong
3898 : results for contours with self-intersections.
3899 :
3900 : Example:
3901 : @code
3902 : vector<Point> contour;
3903 : contour.push_back(Point2f(0, 0));
3904 : contour.push_back(Point2f(10, 0));
3905 : contour.push_back(Point2f(10, 10));
3906 : contour.push_back(Point2f(5, 4));
3907 :
3908 : double area0 = contourArea(contour);
3909 : vector<Point> approx;
3910 : approxPolyDP(contour, approx, 5, true);
3911 : double area1 = contourArea(approx);
3912 :
3913 : cout << "area0 =" << area0 << endl <<
3914 : "area1 =" << area1 << endl <<
3915 : "approx poly vertices" << approx.size() << endl;
3916 : @endcode
3917 : @param contour Input vector of 2D points (contour vertices), stored in std::vector or Mat.
3918 : @param oriented Oriented area flag. If it is true, the function returns a signed area value,
3919 : depending on the contour orientation (clockwise or counter-clockwise). Using this feature you can
3920 : determine orientation of a contour by taking the sign of an area. By default, the parameter is
3921 : false, which means that the absolute value is returned.
3922 : */
3923 : CV_EXPORTS_W double contourArea( InputArray contour, bool oriented = false );
3924 :
3925 : /** @brief Finds a rotated rectangle of the minimum area enclosing the input 2D point set.
3926 :
3927 : The function calculates and returns the minimum-area bounding rectangle (possibly rotated) for a
3928 : specified point set. Developer should keep in mind that the returned RotatedRect can contain negative
3929 : indices when data is close to the containing Mat element boundary.
3930 :
3931 : @param points Input vector of 2D points, stored in std::vector\<\> or Mat
3932 : */
3933 : CV_EXPORTS_W RotatedRect minAreaRect( InputArray points );
3934 :
3935 : /** @brief Finds the four vertices of a rotated rect. Useful to draw the rotated rectangle.
3936 :
3937 : The function finds the four vertices of a rotated rectangle. This function is useful to draw the
3938 : rectangle. In C++, instead of using this function, you can directly use box.points() method. Please
3939 : visit the [tutorial on bounding
3940 : rectangle](http://docs.opencv.org/doc/tutorials/imgproc/shapedescriptors/bounding_rects_circles/bounding_rects_circles.html#bounding-rects-circles)
3941 : for more information.
3942 :
3943 : @param box The input rotated rectangle. It may be the output of
3944 : @param points The output array of four vertices of rectangles.
3945 : */
3946 : CV_EXPORTS_W void boxPoints(RotatedRect box, OutputArray points);
3947 :
3948 : /** @brief Finds a circle of the minimum area enclosing a 2D point set.
3949 :
3950 : The function finds the minimal enclosing circle of a 2D point set using an iterative algorithm.
3951 :
3952 : @param points Input vector of 2D points, stored in std::vector\<\> or Mat
3953 : @param center Output center of the circle.
3954 : @param radius Output radius of the circle.
3955 : */
3956 : CV_EXPORTS_W void minEnclosingCircle( InputArray points,
3957 : CV_OUT Point2f& center, CV_OUT float& radius );
3958 :
3959 : /** @example minarea.cpp
3960 : */
3961 :
3962 : /** @brief Finds a triangle of minimum area enclosing a 2D point set and returns its area.
3963 :
3964 : The function finds a triangle of minimum area enclosing the given set of 2D points and returns its
3965 : area. The output for a given 2D point set is shown in the image below. 2D points are depicted in
3966 : *red* and the enclosing triangle in *yellow*.
3967 :
3968 : ![Sample output of the minimum enclosing triangle function](pics/minenclosingtriangle.png)
3969 :
3970 : The implementation of the algorithm is based on O'Rourke's @cite ORourke86 and Klee and Laskowski's
3971 : @cite KleeLaskowski85 papers. O'Rourke provides a \f$\theta(n)\f$ algorithm for finding the minimal
3972 : enclosing triangle of a 2D convex polygon with n vertices. Since the minEnclosingTriangle function
3973 : takes a 2D point set as input an additional preprocessing step of computing the convex hull of the
3974 : 2D point set is required. The complexity of the convexHull function is \f$O(n log(n))\f$ which is higher
3975 : than \f$\theta(n)\f$. Thus the overall complexity of the function is \f$O(n log(n))\f$.
3976 :
3977 : @param points Input vector of 2D points with depth CV_32S or CV_32F, stored in std::vector\<\> or Mat
3978 : @param triangle Output vector of three 2D points defining the vertices of the triangle. The depth
3979 : of the OutputArray must be CV_32F.
3980 : */
3981 : CV_EXPORTS_W double minEnclosingTriangle( InputArray points, CV_OUT OutputArray triangle );
3982 :
3983 : /** @brief Compares two shapes.
3984 :
3985 : The function compares two shapes. All three implemented methods use the Hu invariants (see cv::HuMoments)
3986 :
3987 : @param contour1 First contour or grayscale image.
3988 : @param contour2 Second contour or grayscale image.
3989 : @param method Comparison method, see cv::ShapeMatchModes
3990 : @param parameter Method-specific parameter (not supported now).
3991 : */
3992 : CV_EXPORTS_W double matchShapes( InputArray contour1, InputArray contour2,
3993 : int method, double parameter );
3994 :
3995 : /** @example convexhull.cpp
3996 : An example using the convexHull functionality
3997 : */
3998 :
3999 : /** @brief Finds the convex hull of a point set.
4000 :
4001 : The function cv::convexHull finds the convex hull of a 2D point set using the Sklansky's algorithm @cite Sklansky82
4002 : that has *O(N logN)* complexity in the current implementation. See the OpenCV sample convexhull.cpp
4003 : that demonstrates the usage of different function variants.
4004 :
4005 : @param points Input 2D point set, stored in std::vector or Mat.
4006 : @param hull Output convex hull. It is either an integer vector of indices or vector of points. In
4007 : the first case, the hull elements are 0-based indices of the convex hull points in the original
4008 : array (since the set of convex hull points is a subset of the original point set). In the second
4009 : case, hull elements are the convex hull points themselves.
4010 : @param clockwise Orientation flag. If it is true, the output convex hull is oriented clockwise.
4011 : Otherwise, it is oriented counter-clockwise. The assumed coordinate system has its X axis pointing
4012 : to the right, and its Y axis pointing upwards.
4013 : @param returnPoints Operation flag. In case of a matrix, when the flag is true, the function
4014 : returns convex hull points. Otherwise, it returns indices of the convex hull points. When the
4015 : output array is std::vector, the flag is ignored, and the output depends on the type of the
4016 : vector: std::vector\<int\> implies returnPoints=false, std::vector\<Point\> implies
4017 : returnPoints=true.
4018 :
4019 : @note `points` and `hull` should be different arrays, inplace processing isn't supported.
4020 : */
4021 : CV_EXPORTS_W void convexHull( InputArray points, OutputArray hull,
4022 : bool clockwise = false, bool returnPoints = true );
4023 :
4024 : /** @brief Finds the convexity defects of a contour.
4025 :
4026 : The figure below displays convexity defects of a hand contour:
4027 :
4028 : ![image](pics/defects.png)
4029 :
4030 : @param contour Input contour.
4031 : @param convexhull Convex hull obtained using convexHull that should contain indices of the contour
4032 : points that make the hull.
4033 : @param convexityDefects The output vector of convexity defects. In C++ and the new Python/Java
4034 : interface each convexity defect is represented as 4-element integer vector (a.k.a. cv::Vec4i):
4035 : (start_index, end_index, farthest_pt_index, fixpt_depth), where indices are 0-based indices
4036 : in the original contour of the convexity defect beginning, end and the farthest point, and
4037 : fixpt_depth is fixed-point approximation (with 8 fractional bits) of the distance between the
4038 : farthest contour point and the hull. That is, to get the floating-point value of the depth will be
4039 : fixpt_depth/256.0.
4040 : */
4041 : CV_EXPORTS_W void convexityDefects( InputArray contour, InputArray convexhull, OutputArray convexityDefects );
4042 :
4043 : /** @brief Tests a contour convexity.
4044 :
4045 : The function tests whether the input contour is convex or not. The contour must be simple, that is,
4046 : without self-intersections. Otherwise, the function output is undefined.
4047 :
4048 : @param contour Input vector of 2D points, stored in std::vector\<\> or Mat
4049 : */
4050 : CV_EXPORTS_W bool isContourConvex( InputArray contour );
4051 :
4052 : //! finds intersection of two convex polygons
4053 : CV_EXPORTS_W float intersectConvexConvex( InputArray _p1, InputArray _p2,
4054 : OutputArray _p12, bool handleNested = true );
4055 :
4056 : /** @example fitellipse.cpp
4057 : An example using the fitEllipse technique
4058 : */
4059 :
4060 : /** @brief Fits an ellipse around a set of 2D points.
4061 :
4062 : The function calculates the ellipse that fits (in a least-squares sense) a set of 2D points best of
4063 : all. It returns the rotated rectangle in which the ellipse is inscribed. The first algorithm described by @cite Fitzgibbon95
4064 : is used. Developer should keep in mind that it is possible that the returned
4065 : ellipse/rotatedRect data contains negative indices, due to the data points being close to the
4066 : border of the containing Mat element.
4067 :
4068 : @param points Input 2D point set, stored in std::vector\<\> or Mat
4069 : */
4070 : CV_EXPORTS_W RotatedRect fitEllipse( InputArray points );
4071 :
4072 : /** @brief Fits an ellipse around a set of 2D points.
4073 :
4074 : The function calculates the ellipse that fits a set of 2D points.
4075 : It returns the rotated rectangle in which the ellipse is inscribed.
4076 : The Approximate Mean Square (AMS) proposed by @cite Taubin1991 is used.
4077 :
4078 : For an ellipse, this basis set is \f$ \chi= \left(x^2, x y, y^2, x, y, 1\right) \f$,
4079 : 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$.
4080 : However, to specify an ellipse, all that is needed is five numbers; the major and minor axes lengths \f$ (a,b) \f$,
4081 : the position \f$ (x_0,y_0) \f$, and the orientation \f$ \theta \f$. This is because the basis set includes lines,
4082 : quadratics, parabolic and hyperbolic functions as well as elliptical functions as possible fits.
4083 : If the fit is found to be a parabolic or hyperbolic function then the standard fitEllipse method is used.
4084 : The AMS method restricts the fit to parabolic, hyperbolic and elliptical curves
4085 : by imposing the condition that \f$ A^T ( D_x^T D_x + D_y^T D_y) A = 1 \f$ where
4086 : the matrices \f$ Dx \f$ and \f$ Dy \f$ are the partial derivatives of the design matrix \f$ D \f$ with
4087 : respect to x and y. The matrices are formed row by row applying the following to
4088 : each of the points in the set:
4089 : \f{align*}{
4090 : D(i,:)&=\left\{x_i^2, x_i y_i, y_i^2, x_i, y_i, 1\right\} &
4091 : D_x(i,:)&=\left\{2 x_i,y_i,0,1,0,0\right\} &
4092 : D_y(i,:)&=\left\{0,x_i,2 y_i,0,1,0\right\}
4093 : \f}
4094 : The AMS method minimizes the cost function
4095 : \f{equation*}{
4096 : \epsilon ^2=\frac{ A^T D^T D A }{ A^T (D_x^T D_x + D_y^T D_y) A^T }
4097 : \f}
4098 :
4099 : The minimum cost is found by solving the generalized eigenvalue problem.
4100 :
4101 : \f{equation*}{
4102 : D^T D A = \lambda \left( D_x^T D_x + D_y^T D_y\right) A
4103 : \f}
4104 :
4105 : @param points Input 2D point set, stored in std::vector\<\> or Mat
4106 : */
4107 : CV_EXPORTS_W RotatedRect fitEllipseAMS( InputArray points );
4108 :
4109 :
4110 : /** @brief Fits an ellipse around a set of 2D points.
4111 :
4112 : The function calculates the ellipse that fits a set of 2D points.
4113 : It returns the rotated rectangle in which the ellipse is inscribed.
4114 : The Direct least square (Direct) method by @cite Fitzgibbon1999 is used.
4115 :
4116 : For an ellipse, this basis set is \f$ \chi= \left(x^2, x y, y^2, x, y, 1\right) \f$,
4117 : 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$.
4118 : However, to specify an ellipse, all that is needed is five numbers; the major and minor axes lengths \f$ (a,b) \f$,
4119 : the position \f$ (x_0,y_0) \f$, and the orientation \f$ \theta \f$. This is because the basis set includes lines,
4120 : quadratics, parabolic and hyperbolic functions as well as elliptical functions as possible fits.
4121 : The Direct method confines the fit to ellipses by ensuring that \f$ 4 A_{xx} A_{yy}- A_{xy}^2 > 0 \f$.
4122 : The condition imposed is that \f$ 4 A_{xx} A_{yy}- A_{xy}^2=1 \f$ which satisfies the inequality
4123 : and as the coefficients can be arbitrarily scaled is not overly restrictive.
4124 :
4125 : \f{equation*}{
4126 : \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}
4127 : 0 & 0 & 2 & 0 & 0 & 0 \\
4128 : 0 & -1 & 0 & 0 & 0 & 0 \\
4129 : 2 & 0 & 0 & 0 & 0 & 0 \\
4130 : 0 & 0 & 0 & 0 & 0 & 0 \\
4131 : 0 & 0 & 0 & 0 & 0 & 0 \\
4132 : 0 & 0 & 0 & 0 & 0 & 0
4133 : \end{matrix} \right)
4134 : \f}
4135 :
4136 : The minimum cost is found by solving the generalized eigenvalue problem.
4137 :
4138 : \f{equation*}{
4139 : D^T D A = \lambda \left( C\right) A
4140 : \f}
4141 :
4142 : The system produces only one positive eigenvalue \f$ \lambda\f$ which is chosen as the solution
4143 : with its eigenvector \f$\mathbf{u}\f$. These are used to find the coefficients
4144 :
4145 : \f{equation*}{
4146 : A = \sqrt{\frac{1}{\mathbf{u}^T C \mathbf{u}}} \mathbf{u}
4147 : \f}
4148 : The scaling factor guarantees that \f$A^T C A =1\f$.
4149 :
4150 : @param points Input 2D point set, stored in std::vector\<\> or Mat
4151 : */
4152 : CV_EXPORTS_W RotatedRect fitEllipseDirect( InputArray points );
4153 :
4154 : /** @brief Fits a line to a 2D or 3D point set.
4155 :
4156 : The function fitLine fits a line to a 2D or 3D point set by minimizing \f$\sum_i \rho(r_i)\f$ where
4157 : \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
4158 : of the following:
4159 : - DIST_L2
4160 : \f[\rho (r) = r^2/2 \quad \text{(the simplest and the fastest least-squares method)}\f]
4161 : - DIST_L1
4162 : \f[\rho (r) = r\f]
4163 : - DIST_L12
4164 : \f[\rho (r) = 2 \cdot ( \sqrt{1 + \frac{r^2}{2}} - 1)\f]
4165 : - DIST_FAIR
4166 : \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]
4167 : - DIST_WELSCH
4168 : \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]
4169 : - DIST_HUBER
4170 : \f[\rho (r) = \fork{r^2/2}{if \(r < C\)}{C \cdot (r-C/2)}{otherwise} \quad \text{where} \quad C=1.345\f]
4171 :
4172 : The algorithm is based on the M-estimator ( <http://en.wikipedia.org/wiki/M-estimator> ) technique
4173 : that iteratively fits the line using the weighted least-squares algorithm. After each iteration the
4174 : weights \f$w_i\f$ are adjusted to be inversely proportional to \f$\rho(r_i)\f$ .
4175 :
4176 : @param points Input vector of 2D or 3D points, stored in std::vector\<\> or Mat.
4177 : @param line Output line parameters. In case of 2D fitting, it should be a vector of 4 elements
4178 : (like Vec4f) - (vx, vy, x0, y0), where (vx, vy) is a normalized vector collinear to the line and
4179 : (x0, y0) is a point on the line. In case of 3D fitting, it should be a vector of 6 elements (like
4180 : Vec6f) - (vx, vy, vz, x0, y0, z0), where (vx, vy, vz) is a normalized vector collinear to the line
4181 : and (x0, y0, z0) is a point on the line.
4182 : @param distType Distance used by the M-estimator, see cv::DistanceTypes
4183 : @param param Numerical parameter ( C ) for some types of distances. If it is 0, an optimal value
4184 : is chosen.
4185 : @param reps Sufficient accuracy for the radius (distance between the coordinate origin and the line).
4186 : @param aeps Sufficient accuracy for the angle. 0.01 would be a good default value for reps and aeps.
4187 : */
4188 : CV_EXPORTS_W void fitLine( InputArray points, OutputArray line, int distType,
4189 : double param, double reps, double aeps );
4190 :
4191 : /** @brief Performs a point-in-contour test.
4192 :
4193 : The function determines whether the point is inside a contour, outside, or lies on an edge (or
4194 : coincides with a vertex). It returns positive (inside), negative (outside), or zero (on an edge)
4195 : value, correspondingly. When measureDist=false , the return value is +1, -1, and 0, respectively.
4196 : Otherwise, the return value is a signed distance between the point and the nearest contour edge.
4197 :
4198 : See below a sample output of the function where each image pixel is tested against the contour:
4199 :
4200 : ![sample output](pics/pointpolygon.png)
4201 :
4202 : @param contour Input contour.
4203 : @param pt Point tested against the contour.
4204 : @param measureDist If true, the function estimates the signed distance from the point to the
4205 : nearest contour edge. Otherwise, the function only checks if the point is inside a contour or not.
4206 : */
4207 : CV_EXPORTS_W double pointPolygonTest( InputArray contour, Point2f pt, bool measureDist );
4208 :
4209 : /** @brief Finds out if there is any intersection between two rotated rectangles.
4210 :
4211 : If there is then the vertices of the intersecting region are returned as well.
4212 :
4213 : Below are some examples of intersection configurations. The hatched pattern indicates the
4214 : intersecting region and the red vertices are returned by the function.
4215 :
4216 : ![intersection examples](pics/intersection.png)
4217 :
4218 : @param rect1 First rectangle
4219 : @param rect2 Second rectangle
4220 : @param intersectingRegion The output array of the vertices of the intersecting region. It returns
4221 : at most 8 vertices. Stored as std::vector\<cv::Point2f\> or cv::Mat as Mx1 of type CV_32FC2.
4222 : @returns One of cv::RectanglesIntersectTypes
4223 : */
4224 : CV_EXPORTS_W int rotatedRectangleIntersection( const RotatedRect& rect1, const RotatedRect& rect2, OutputArray intersectingRegion );
4225 :
4226 : //! @} imgproc_shape
4227 :
4228 : CV_EXPORTS_W Ptr<CLAHE> createCLAHE(double clipLimit = 40.0, Size tileGridSize = Size(8, 8));
4229 :
4230 : //! Ballard, D.H. (1981). Generalizing the Hough transform to detect arbitrary shapes. Pattern Recognition 13 (2): 111-122.
4231 : //! Detects position only without translation and rotation
4232 : CV_EXPORTS Ptr<GeneralizedHoughBallard> createGeneralizedHoughBallard();
4233 :
4234 : //! Guil, N., González-Linares, J.M. and Zapata, E.L. (1999). Bidimensional shape detection using an invariant approach. Pattern Recognition 32 (6): 1025-1038.
4235 : //! Detects position, translation and rotation
4236 : CV_EXPORTS Ptr<GeneralizedHoughGuil> createGeneralizedHoughGuil();
4237 :
4238 : //! Performs linear blending of two images:
4239 : //! \f[ \texttt{dst}(i,j) = \texttt{weights1}(i,j)*\texttt{src1}(i,j) + \texttt{weights2}(i,j)*\texttt{src2}(i,j) \f]
4240 : //! @param src1 It has a type of CV_8UC(n) or CV_32FC(n), where n is a positive integer.
4241 : //! @param src2 It has the same type and size as src1.
4242 : //! @param weights1 It has a type of CV_32FC1 and the same size with src1.
4243 : //! @param weights2 It has a type of CV_32FC1 and the same size with src1.
4244 : //! @param dst It is created if it does not have the same size and type with src1.
4245 : CV_EXPORTS void blendLinear(InputArray src1, InputArray src2, InputArray weights1, InputArray weights2, OutputArray dst);
4246 :
4247 : //! @addtogroup imgproc_colormap
4248 : //! @{
4249 :
4250 : //! GNU Octave/MATLAB equivalent colormaps
4251 : enum ColormapTypes
4252 : {
4253 : COLORMAP_AUTUMN = 0, //!< ![autumn](pics/colormaps/colorscale_autumn.jpg)
4254 : COLORMAP_BONE = 1, //!< ![bone](pics/colormaps/colorscale_bone.jpg)
4255 : COLORMAP_JET = 2, //!< ![jet](pics/colormaps/colorscale_jet.jpg)
4256 : COLORMAP_WINTER = 3, //!< ![winter](pics/colormaps/colorscale_winter.jpg)
4257 : COLORMAP_RAINBOW = 4, //!< ![rainbow](pics/colormaps/colorscale_rainbow.jpg)
4258 : COLORMAP_OCEAN = 5, //!< ![ocean](pics/colormaps/colorscale_ocean.jpg)
4259 : COLORMAP_SUMMER = 6, //!< ![summer](pics/colormaps/colorscale_summer.jpg)
4260 : COLORMAP_SPRING = 7, //!< ![spring](pics/colormaps/colorscale_spring.jpg)
4261 : COLORMAP_COOL = 8, //!< ![cool](pics/colormaps/colorscale_cool.jpg)
4262 : COLORMAP_HSV = 9, //!< ![HSV](pics/colormaps/colorscale_hsv.jpg)
4263 : COLORMAP_PINK = 10, //!< ![pink](pics/colormaps/colorscale_pink.jpg)
4264 : COLORMAP_HOT = 11, //!< ![hot](pics/colormaps/colorscale_hot.jpg)
4265 : COLORMAP_PARULA = 12 //!< ![parula](pics/colormaps/colorscale_parula.jpg)
4266 : };
4267 :
4268 : /** @example falsecolor.cpp
4269 : An example using applyColorMap function
4270 : */
4271 : /** @brief Applies a GNU Octave/MATLAB equivalent colormap on a given image.
4272 :
4273 : @param src The source image, grayscale or colored of type CV_8UC1 or CV_8UC3.
4274 : @param dst The result is the colormapped source image. Note: Mat::create is called on dst.
4275 : @param colormap The colormap to apply, see cv::ColormapTypes
4276 : */
4277 : CV_EXPORTS_W void applyColorMap(InputArray src, OutputArray dst, int colormap);
4278 :
4279 : /** @brief Applies a user colormap on a given image.
4280 :
4281 : @param src The source image, grayscale or colored of type CV_8UC1 or CV_8UC3.
4282 : @param dst The result is the colormapped source image. Note: Mat::create is called on dst.
4283 : @param userColor The colormap to apply of type CV_8UC1 or CV_8UC3 and size 256
4284 : */
4285 : CV_EXPORTS_W void applyColorMap(InputArray src, OutputArray dst, InputArray userColor);
4286 :
4287 : //! @} imgproc_colormap
4288 :
4289 : //! @addtogroup imgproc_draw
4290 : //! @{
4291 :
4292 : /** @brief Draws a line segment connecting two points.
4293 :
4294 : The function line draws the line segment between pt1 and pt2 points in the image. The line is
4295 : clipped by the image boundaries. For non-antialiased lines with integer coordinates, the 8-connected
4296 : or 4-connected Bresenham algorithm is used. Thick lines are drawn with rounding endings. Antialiased
4297 : lines are drawn using Gaussian filtering.
4298 :
4299 : @param img Image.
4300 : @param pt1 First point of the line segment.
4301 : @param pt2 Second point of the line segment.
4302 : @param color Line color.
4303 : @param thickness Line thickness.
4304 : @param lineType Type of the line, see cv::LineTypes.
4305 : @param shift Number of fractional bits in the point coordinates.
4306 : */
4307 : CV_EXPORTS_W void line(InputOutputArray img, Point pt1, Point pt2, const Scalar& color,
4308 : int thickness = 1, int lineType = LINE_8, int shift = 0);
4309 :
4310 : /** @brief Draws a arrow segment pointing from the first point to the second one.
4311 :
4312 : The function arrowedLine draws an arrow between pt1 and pt2 points in the image. See also cv::line.
4313 :
4314 : @param img Image.
4315 : @param pt1 The point the arrow starts from.
4316 : @param pt2 The point the arrow points to.
4317 : @param color Line color.
4318 : @param thickness Line thickness.
4319 : @param line_type Type of the line, see cv::LineTypes
4320 : @param shift Number of fractional bits in the point coordinates.
4321 : @param tipLength The length of the arrow tip in relation to the arrow length
4322 : */
4323 : CV_EXPORTS_W void arrowedLine(InputOutputArray img, Point pt1, Point pt2, const Scalar& color,
4324 : int thickness=1, int line_type=8, int shift=0, double tipLength=0.1);
4325 :
4326 : /** @brief Draws a simple, thick, or filled up-right rectangle.
4327 :
4328 : The function rectangle draws a rectangle outline or a filled rectangle whose two opposite corners
4329 : are pt1 and pt2.
4330 :
4331 : @param img Image.
4332 : @param pt1 Vertex of the rectangle.
4333 : @param pt2 Vertex of the rectangle opposite to pt1 .
4334 : @param color Rectangle color or brightness (grayscale image).
4335 : @param thickness Thickness of lines that make up the rectangle. Negative values, like CV_FILLED ,
4336 : mean that the function has to draw a filled rectangle.
4337 : @param lineType Type of the line. See the line description.
4338 : @param shift Number of fractional bits in the point coordinates.
4339 : */
4340 : CV_EXPORTS_W void rectangle(InputOutputArray img, Point pt1, Point pt2,
4341 : const Scalar& color, int thickness = 1,
4342 : int lineType = LINE_8, int shift = 0);
4343 :
4344 : /** @overload
4345 :
4346 : use `rec` parameter as alternative specification of the drawn rectangle: `r.tl() and
4347 : r.br()-Point(1,1)` are opposite corners
4348 : */
4349 : CV_EXPORTS void rectangle(CV_IN_OUT Mat& img, Rect rec,
4350 : const Scalar& color, int thickness = 1,
4351 : int lineType = LINE_8, int shift = 0);
4352 :
4353 : /** @example Drawing_2.cpp
4354 : An example using drawing functions
4355 : */
4356 : /** @brief Draws a circle.
4357 :
4358 : The function circle draws a simple or filled circle with a given center and radius.
4359 : @param img Image where the circle is drawn.
4360 : @param center Center of the circle.
4361 : @param radius Radius of the circle.
4362 : @param color Circle color.
4363 : @param thickness Thickness of the circle outline, if positive. Negative thickness means that a
4364 : filled circle is to be drawn.
4365 : @param lineType Type of the circle boundary. See the line description.
4366 : @param shift Number of fractional bits in the coordinates of the center and in the radius value.
4367 : */
4368 : CV_EXPORTS_W void circle(InputOutputArray img, Point center, int radius,
4369 : const Scalar& color, int thickness = 1,
4370 : int lineType = LINE_8, int shift = 0);
4371 :
4372 : /** @brief Draws a simple or thick elliptic arc or fills an ellipse sector.
4373 :
4374 : The function cv::ellipse with more parameters draws an ellipse outline, a filled ellipse, an elliptic
4375 : arc, or a filled ellipse sector. The drawing code uses general parametric form.
4376 : A piecewise-linear curve is used to approximate the elliptic arc
4377 : boundary. If you need more control of the ellipse rendering, you can retrieve the curve using
4378 : cv::ellipse2Poly and then render it with polylines or fill it with cv::fillPoly. If you use the first
4379 : variant of the function and want to draw the whole ellipse, not an arc, pass `startAngle=0` and
4380 : `endAngle=360`. If `startAngle` is greater than `endAngle`, they are swapped. The figure below explains
4381 : the meaning of the parameters to draw the blue arc.
4382 :
4383 : ![Parameters of Elliptic Arc](pics/ellipse.svg)
4384 :
4385 : @param img Image.
4386 : @param center Center of the ellipse.
4387 : @param axes Half of the size of the ellipse main axes.
4388 : @param angle Ellipse rotation angle in degrees.
4389 : @param startAngle Starting angle of the elliptic arc in degrees.
4390 : @param endAngle Ending angle of the elliptic arc in degrees.
4391 : @param color Ellipse color.
4392 : @param thickness Thickness of the ellipse arc outline, if positive. Otherwise, this indicates that
4393 : a filled ellipse sector is to be drawn.
4394 : @param lineType Type of the ellipse boundary. See the line description.
4395 : @param shift Number of fractional bits in the coordinates of the center and values of axes.
4396 : */
4397 : CV_EXPORTS_W void ellipse(InputOutputArray img, Point center, Size axes,
4398 : double angle, double startAngle, double endAngle,
4399 : const Scalar& color, int thickness = 1,
4400 : int lineType = LINE_8, int shift = 0);
4401 :
4402 : /** @overload
4403 : @param img Image.
4404 : @param box Alternative ellipse representation via RotatedRect. This means that the function draws
4405 : an ellipse inscribed in the rotated rectangle.
4406 : @param color Ellipse color.
4407 : @param thickness Thickness of the ellipse arc outline, if positive. Otherwise, this indicates that
4408 : a filled ellipse sector is to be drawn.
4409 : @param lineType Type of the ellipse boundary. See the line description.
4410 : */
4411 : CV_EXPORTS_W void ellipse(InputOutputArray img, const RotatedRect& box, const Scalar& color,
4412 : int thickness = 1, int lineType = LINE_8);
4413 :
4414 : /* ----------------------------------------------------------------------------------------- */
4415 : /* ADDING A SET OF PREDEFINED MARKERS WHICH COULD BE USED TO HIGHLIGHT POSITIONS IN AN IMAGE */
4416 : /* ----------------------------------------------------------------------------------------- */
4417 :
4418 : //! Possible set of marker types used for the cv::drawMarker function
4419 : enum MarkerTypes
4420 : {
4421 : MARKER_CROSS = 0, //!< A crosshair marker shape
4422 : MARKER_TILTED_CROSS = 1, //!< A 45 degree tilted crosshair marker shape
4423 : MARKER_STAR = 2, //!< A star marker shape, combination of cross and tilted cross
4424 : MARKER_DIAMOND = 3, //!< A diamond marker shape
4425 : MARKER_SQUARE = 4, //!< A square marker shape
4426 : MARKER_TRIANGLE_UP = 5, //!< An upwards pointing triangle marker shape
4427 : MARKER_TRIANGLE_DOWN = 6 //!< A downwards pointing triangle marker shape
4428 : };
4429 :
4430 : /** @brief Draws a marker on a predefined position in an image.
4431 :
4432 : The function drawMarker draws a marker on a given position in the image. For the moment several
4433 : marker types are supported, see cv::MarkerTypes for more information.
4434 :
4435 : @param img Image.
4436 : @param position The point where the crosshair is positioned.
4437 : @param color Line color.
4438 : @param markerType The specific type of marker you want to use, see cv::MarkerTypes
4439 : @param thickness Line thickness.
4440 : @param line_type Type of the line, see cv::LineTypes
4441 : @param markerSize The length of the marker axis [default = 20 pixels]
4442 : */
4443 : CV_EXPORTS_W void drawMarker(CV_IN_OUT Mat& img, Point position, const Scalar& color,
4444 : int markerType = MARKER_CROSS, int markerSize=20, int thickness=1,
4445 : int line_type=8);
4446 :
4447 : /* ----------------------------------------------------------------------------------------- */
4448 : /* END OF MARKER SECTION */
4449 : /* ----------------------------------------------------------------------------------------- */
4450 :
4451 : /** @overload */
4452 : CV_EXPORTS void fillConvexPoly(Mat& img, const Point* pts, int npts,
4453 : const Scalar& color, int lineType = LINE_8,
4454 : int shift = 0);
4455 :
4456 : /** @brief Fills a convex polygon.
4457 :
4458 : The function fillConvexPoly draws a filled convex polygon. This function is much faster than the
4459 : function cv::fillPoly . It can fill not only convex polygons but any monotonic polygon without
4460 : self-intersections, that is, a polygon whose contour intersects every horizontal line (scan line)
4461 : twice at the most (though, its top-most and/or the bottom edge could be horizontal).
4462 :
4463 : @param img Image.
4464 : @param points Polygon vertices.
4465 : @param color Polygon color.
4466 : @param lineType Type of the polygon boundaries. See the line description.
4467 : @param shift Number of fractional bits in the vertex coordinates.
4468 : */
4469 : CV_EXPORTS_W void fillConvexPoly(InputOutputArray img, InputArray points,
4470 : const Scalar& color, int lineType = LINE_8,
4471 : int shift = 0);
4472 :
4473 : /** @overload */
4474 : CV_EXPORTS void fillPoly(Mat& img, const Point** pts,
4475 : const int* npts, int ncontours,
4476 : const Scalar& color, int lineType = LINE_8, int shift = 0,
4477 : Point offset = Point() );
4478 :
4479 : /** @example Drawing_1.cpp
4480 : An example using drawing functions
4481 : */
4482 : /** @brief Fills the area bounded by one or more polygons.
4483 :
4484 : The function fillPoly fills an area bounded by several polygonal contours. The function can fill
4485 : complex areas, for example, areas with holes, contours with self-intersections (some of their
4486 : parts), and so forth.
4487 :
4488 : @param img Image.
4489 : @param pts Array of polygons where each polygon is represented as an array of points.
4490 : @param color Polygon color.
4491 : @param lineType Type of the polygon boundaries. See the line description.
4492 : @param shift Number of fractional bits in the vertex coordinates.
4493 : @param offset Optional offset of all points of the contours.
4494 : */
4495 : CV_EXPORTS_W void fillPoly(InputOutputArray img, InputArrayOfArrays pts,
4496 : const Scalar& color, int lineType = LINE_8, int shift = 0,
4497 : Point offset = Point() );
4498 :
4499 : /** @overload */
4500 : CV_EXPORTS void polylines(Mat& img, const Point* const* pts, const int* npts,
4501 : int ncontours, bool isClosed, const Scalar& color,
4502 : int thickness = 1, int lineType = LINE_8, int shift = 0 );
4503 :
4504 : /** @brief Draws several polygonal curves.
4505 :
4506 : @param img Image.
4507 : @param pts Array of polygonal curves.
4508 : @param isClosed Flag indicating whether the drawn polylines are closed or not. If they are closed,
4509 : the function draws a line from the last vertex of each curve to its first vertex.
4510 : @param color Polyline color.
4511 : @param thickness Thickness of the polyline edges.
4512 : @param lineType Type of the line segments. See the line description.
4513 : @param shift Number of fractional bits in the vertex coordinates.
4514 :
4515 : The function polylines draws one or more polygonal curves.
4516 : */
4517 : CV_EXPORTS_W void polylines(InputOutputArray img, InputArrayOfArrays pts,
4518 : bool isClosed, const Scalar& color,
4519 : int thickness = 1, int lineType = LINE_8, int shift = 0 );
4520 :
4521 : /** @example contours2.cpp
4522 : An example program illustrates the use of cv::findContours and cv::drawContours
4523 : \image html WindowsQtContoursOutput.png "Screenshot of the program"
4524 : */
4525 :
4526 : /** @example segment_objects.cpp
4527 : An example using drawContours to clean up a background segmentation result
4528 : */
4529 :
4530 : /** @brief Draws contours outlines or filled contours.
4531 :
4532 : The function draws contour outlines in the image if \f$\texttt{thickness} \ge 0\f$ or fills the area
4533 : bounded by the contours if \f$\texttt{thickness}<0\f$ . The example below shows how to retrieve
4534 : connected components from the binary image and label them: :
4535 : @code
4536 : #include "opencv2/imgproc.hpp"
4537 : #include "opencv2/highgui.hpp"
4538 :
4539 : using namespace cv;
4540 : using namespace std;
4541 :
4542 : int main( int argc, char** argv )
4543 : {
4544 : Mat src;
4545 : // the first command-line parameter must be a filename of the binary
4546 : // (black-n-white) image
4547 : if( argc != 2 || !(src=imread(argv[1], 0)).data)
4548 : return -1;
4549 :
4550 : Mat dst = Mat::zeros(src.rows, src.cols, CV_8UC3);
4551 :
4552 : src = src > 1;
4553 : namedWindow( "Source", 1 );
4554 : imshow( "Source", src );
4555 :
4556 : vector<vector<Point> > contours;
4557 : vector<Vec4i> hierarchy;
4558 :
4559 : findContours( src, contours, hierarchy,
4560 : RETR_CCOMP, CHAIN_APPROX_SIMPLE );
4561 :
4562 : // iterate through all the top-level contours,
4563 : // draw each connected component with its own random color
4564 : int idx = 0;
4565 : for( ; idx >= 0; idx = hierarchy[idx][0] )
4566 : {
4567 : Scalar color( rand()&255, rand()&255, rand()&255 );
4568 : drawContours( dst, contours, idx, color, FILLED, 8, hierarchy );
4569 : }
4570 :
4571 : namedWindow( "Components", 1 );
4572 : imshow( "Components", dst );
4573 : waitKey(0);
4574 : }
4575 : @endcode
4576 :
4577 : @param image Destination image.
4578 : @param contours All the input contours. Each contour is stored as a point vector.
4579 : @param contourIdx Parameter indicating a contour to draw. If it is negative, all the contours are drawn.
4580 : @param color Color of the contours.
4581 : @param thickness Thickness of lines the contours are drawn with. If it is negative (for example,
4582 : thickness=CV_FILLED ), the contour interiors are drawn.
4583 : @param lineType Line connectivity. See cv::LineTypes.
4584 : @param hierarchy Optional information about hierarchy. It is only needed if you want to draw only
4585 : some of the contours (see maxLevel ).
4586 : @param maxLevel Maximal level for drawn contours. If it is 0, only the specified contour is drawn.
4587 : If it is 1, the function draws the contour(s) and all the nested contours. If it is 2, the function
4588 : draws the contours, all the nested contours, all the nested-to-nested contours, and so on. This
4589 : parameter is only taken into account when there is hierarchy available.
4590 : @param offset Optional contour shift parameter. Shift all the drawn contours by the specified
4591 : \f$\texttt{offset}=(dx,dy)\f$ .
4592 : @note When thickness=CV_FILLED, the function is designed to handle connected components with holes correctly
4593 : even when no hierarchy date is provided. This is done by analyzing all the outlines together
4594 : using even-odd rule. This may give incorrect results if you have a joint collection of separately retrieved
4595 : contours. In order to solve this problem, you need to call drawContours separately for each sub-group
4596 : of contours, or iterate over the collection using contourIdx parameter.
4597 : */
4598 : CV_EXPORTS_W void drawContours( InputOutputArray image, InputArrayOfArrays contours,
4599 : int contourIdx, const Scalar& color,
4600 : int thickness = 1, int lineType = LINE_8,
4601 : InputArray hierarchy = noArray(),
4602 : int maxLevel = INT_MAX, Point offset = Point() );
4603 :
4604 : /** @brief Clips the line against the image rectangle.
4605 :
4606 : The function cv::clipLine calculates a part of the line segment that is entirely within the specified
4607 : rectangle. it returns false if the line segment is completely outside the rectangle. Otherwise,
4608 : it returns true .
4609 : @param imgSize Image size. The image rectangle is Rect(0, 0, imgSize.width, imgSize.height) .
4610 : @param pt1 First line point.
4611 : @param pt2 Second line point.
4612 : */
4613 : CV_EXPORTS bool clipLine(Size imgSize, CV_IN_OUT Point& pt1, CV_IN_OUT Point& pt2);
4614 :
4615 : /** @overload
4616 : @param imgSize Image size. The image rectangle is Rect(0, 0, imgSize.width, imgSize.height) .
4617 : @param pt1 First line point.
4618 : @param pt2 Second line point.
4619 : */
4620 : CV_EXPORTS bool clipLine(Size2l imgSize, CV_IN_OUT Point2l& pt1, CV_IN_OUT Point2l& pt2);
4621 :
4622 : /** @overload
4623 : @param imgRect Image rectangle.
4624 : @param pt1 First line point.
4625 : @param pt2 Second line point.
4626 : */
4627 : CV_EXPORTS_W bool clipLine(Rect imgRect, CV_OUT CV_IN_OUT Point& pt1, CV_OUT CV_IN_OUT Point& pt2);
4628 :
4629 : /** @brief Approximates an elliptic arc with a polyline.
4630 :
4631 : The function ellipse2Poly computes the vertices of a polyline that approximates the specified
4632 : elliptic arc. It is used by cv::ellipse. If `arcStart` is greater than `arcEnd`, they are swapped.
4633 :
4634 : @param center Center of the arc.
4635 : @param axes Half of the size of the ellipse main axes. See the ellipse for details.
4636 : @param angle Rotation angle of the ellipse in degrees. See the ellipse for details.
4637 : @param arcStart Starting angle of the elliptic arc in degrees.
4638 : @param arcEnd Ending angle of the elliptic arc in degrees.
4639 : @param delta Angle between the subsequent polyline vertices. It defines the approximation
4640 : accuracy.
4641 : @param pts Output vector of polyline vertices.
4642 : */
4643 : CV_EXPORTS_W void ellipse2Poly( Point center, Size axes, int angle,
4644 : int arcStart, int arcEnd, int delta,
4645 : CV_OUT std::vector<Point>& pts );
4646 :
4647 : /** @overload
4648 : @param center Center of the arc.
4649 : @param axes Half of the size of the ellipse main axes. See the ellipse for details.
4650 : @param angle Rotation angle of the ellipse in degrees. See the ellipse for details.
4651 : @param arcStart Starting angle of the elliptic arc in degrees.
4652 : @param arcEnd Ending angle of the elliptic arc in degrees.
4653 : @param delta Angle between the subsequent polyline vertices. It defines the approximation
4654 : accuracy.
4655 : @param pts Output vector of polyline vertices.
4656 : */
4657 : CV_EXPORTS void ellipse2Poly(Point2d center, Size2d axes, int angle,
4658 : int arcStart, int arcEnd, int delta,
4659 : CV_OUT std::vector<Point2d>& pts);
4660 :
4661 : /** @brief Draws a text string.
4662 :
4663 : The function putText renders the specified text string in the image. Symbols that cannot be rendered
4664 : using the specified font are replaced by question marks. See getTextSize for a text rendering code
4665 : example.
4666 :
4667 : @param img Image.
4668 : @param text Text string to be drawn.
4669 : @param org Bottom-left corner of the text string in the image.
4670 : @param fontFace Font type, see cv::HersheyFonts.
4671 : @param fontScale Font scale factor that is multiplied by the font-specific base size.
4672 : @param color Text color.
4673 : @param thickness Thickness of the lines used to draw a text.
4674 : @param lineType Line type. See the line for details.
4675 : @param bottomLeftOrigin When true, the image data origin is at the bottom-left corner. Otherwise,
4676 : it is at the top-left corner.
4677 : */
4678 : CV_EXPORTS_W void putText( InputOutputArray img, const String& text, Point org,
4679 : int fontFace, double fontScale, Scalar color,
4680 : int thickness = 1, int lineType = LINE_8,
4681 : bool bottomLeftOrigin = false );
4682 :
4683 : /** @brief Calculates the width and height of a text string.
4684 :
4685 : The function getTextSize calculates and returns the size of a box that contains the specified text.
4686 : That is, the following code renders some text, the tight box surrounding it, and the baseline: :
4687 : @code
4688 : String text = "Funny text inside the box";
4689 : int fontFace = FONT_HERSHEY_SCRIPT_SIMPLEX;
4690 : double fontScale = 2;
4691 : int thickness = 3;
4692 :
4693 : Mat img(600, 800, CV_8UC3, Scalar::all(0));
4694 :
4695 : int baseline=0;
4696 : Size textSize = getTextSize(text, fontFace,
4697 : fontScale, thickness, &baseline);
4698 : baseline += thickness;
4699 :
4700 : // center the text
4701 : Point textOrg((img.cols - textSize.width)/2,
4702 : (img.rows + textSize.height)/2);
4703 :
4704 : // draw the box
4705 : rectangle(img, textOrg + Point(0, baseline),
4706 : textOrg + Point(textSize.width, -textSize.height),
4707 : Scalar(0,0,255));
4708 : // ... and the baseline first
4709 : line(img, textOrg + Point(0, thickness),
4710 : textOrg + Point(textSize.width, thickness),
4711 : Scalar(0, 0, 255));
4712 :
4713 : // then put the text itself
4714 : putText(img, text, textOrg, fontFace, fontScale,
4715 : Scalar::all(255), thickness, 8);
4716 : @endcode
4717 :
4718 : @param text Input text string.
4719 : @param fontFace Font to use, see cv::HersheyFonts.
4720 : @param fontScale Font scale factor that is multiplied by the font-specific base size.
4721 : @param thickness Thickness of lines used to render the text. See putText for details.
4722 : @param[out] baseLine y-coordinate of the baseline relative to the bottom-most text
4723 : point.
4724 : @return The size of a box that contains the specified text.
4725 :
4726 : @see cv::putText
4727 : */
4728 : CV_EXPORTS_W Size getTextSize(const String& text, int fontFace,
4729 : double fontScale, int thickness,
4730 : CV_OUT int* baseLine);
4731 :
4732 : /** @brief Line iterator
4733 :
4734 : The class is used to iterate over all the pixels on the raster line
4735 : segment connecting two specified points.
4736 :
4737 : The class LineIterator is used to get each pixel of a raster line. It
4738 : can be treated as versatile implementation of the Bresenham algorithm
4739 : where you can stop at each pixel and do some extra processing, for
4740 : example, grab pixel values along the line or draw a line with an effect
4741 : (for example, with XOR operation).
4742 :
4743 : The number of pixels along the line is stored in LineIterator::count.
4744 : The method LineIterator::pos returns the current position in the image:
4745 :
4746 : @code{.cpp}
4747 : // grabs pixels along the line (pt1, pt2)
4748 : // from 8-bit 3-channel image to the buffer
4749 : LineIterator it(img, pt1, pt2, 8);
4750 : LineIterator it2 = it;
4751 : vector<Vec3b> buf(it.count);
4752 :
4753 : for(int i = 0; i < it.count; i++, ++it)
4754 : buf[i] = *(const Vec3b)*it;
4755 :
4756 : // alternative way of iterating through the line
4757 : for(int i = 0; i < it2.count; i++, ++it2)
4758 : {
4759 : Vec3b val = img.at<Vec3b>(it2.pos());
4760 : CV_Assert(buf[i] == val);
4761 : }
4762 : @endcode
4763 : */
4764 : class CV_EXPORTS LineIterator
4765 : {
4766 : public:
4767 : /** @brief intializes the iterator
4768 :
4769 : creates iterators for the line connecting pt1 and pt2
4770 : the line will be clipped on the image boundaries
4771 : the line is 8-connected or 4-connected
4772 : If leftToRight=true, then the iteration is always done
4773 : from the left-most point to the right most,
4774 : not to depend on the ordering of pt1 and pt2 parameters
4775 : */
4776 : LineIterator( const Mat& img, Point pt1, Point pt2,
4777 : int connectivity = 8, bool leftToRight = false );
4778 : /** @brief returns pointer to the current pixel
4779 : */
4780 : uchar* operator *();
4781 : /** @brief prefix increment operator (++it). shifts iterator to the next pixel
4782 : */
4783 : LineIterator& operator ++();
4784 : /** @brief postfix increment operator (it++). shifts iterator to the next pixel
4785 : */
4786 : LineIterator operator ++(int);
4787 : /** @brief returns coordinates of the current pixel
4788 : */
4789 : Point pos() const;
4790 :
4791 : uchar* ptr;
4792 : const uchar* ptr0;
4793 : int step, elemSize;
4794 : int err, count;
4795 : int minusDelta, plusDelta;
4796 : int minusStep, plusStep;
4797 : };
4798 :
4799 : //! @cond IGNORED
4800 :
4801 : // === LineIterator implementation ===
4802 :
4803 : inline
4804 : uchar* LineIterator::operator *()
4805 : {
4806 : return ptr;
4807 : }
4808 :
4809 : inline
4810 : LineIterator& LineIterator::operator ++()
4811 : {
4812 : int mask = err < 0 ? -1 : 0;
4813 : err += minusDelta + (plusDelta & mask);
4814 : ptr += minusStep + (plusStep & mask);
4815 : return *this;
4816 : }
4817 :
4818 : inline
4819 : LineIterator LineIterator::operator ++(int)
4820 : {
4821 : LineIterator it = *this;
4822 : ++(*this);
4823 : return it;
4824 : }
4825 :
4826 : inline
4827 : Point LineIterator::pos() const
4828 : {
4829 : Point p;
4830 : p.y = (int)((ptr - ptr0)/step);
4831 : p.x = (int)(((ptr - ptr0) - p.y*step)/elemSize);
4832 : return p;
4833 : }
4834 :
4835 : //! @endcond
4836 :
4837 : //! @} imgproc_draw
4838 :
4839 : //! @} imgproc
4840 :
4841 : } // cv
4842 :
4843 : #ifndef DISABLE_OPENCV_24_COMPATIBILITY
4844 : #include "opencv2/imgproc/imgproc_c.h"
4845 : #endif
4846 :
4847 : #endif
|