\section{Image Filtering}

Functions and classes described in this section are used to perform various linear or non-linear filtering operations on 2D images (represented as \cvCppCross{Mat}'s), that is, for each pixel location $(x,y)$ in the source image some its (normally rectangular) neighborhood is considered and used to compute the response. In case of a linear filter it is a weighted sum of pixel values, in case of morphological operations it is the minimum or maximum etc. The computed response is stored to the destination image at the same location $(x,y)$. It means, that the output image will be of the same size as the input image. Normally, the functions supports multi-channel arrays, in which case every channel is processed independently, therefore the output image will also have the same number of channels as the input one.

Another common feature of the functions and classes described in this section is that, unlike simple arithmetic functions, they need to extrapolate values of some non-existing pixels. For example, if we want to smooth an image using a Gaussian $3 \times 3$ filter, then during the processing of the left-most pixels in each row we need pixels to the left of them, i.e. outside of the image. We can let those pixels be the same as the left-most image pixels (i.e. use "replicated border" extrapolation method), or assume that all the non-existing pixels are zeros ("contant border" extrapolation method) etc. \cvCpp{OpenCV let the user to specify the extrapolation method; see the function \cvCppCross{borderInterpolate} and discussion of \texttt{borderType} parameter in various functions below.}

\ifCPy

\cvclass{IplConvKernel}

An IplConvKernel is a rectangular convolution kernel, created by function \cross{CreateStructuringElementEx}.

\cvCPyFunc{CopyMakeBorder}
Copies an image and makes a border around it.

\cvdefC{
void cvCopyMakeBorder(
\par const CvArr* src,
\par CvArr* dst,
\par CvPoint offset,
\par int bordertype,
\par CvScalar value=cvScalarAll(0) );}
\cvdefPy{CopyMakeBorder(src,dst,offset,bordertype,value=(0,0,0,0))-> None}

\begin{description}
\cvarg{src}{The source image}
\cvarg{dst}{The destination image}
\cvarg{offset}{Coordinates of the top-left corner (or bottom-left in the case of images with bottom-left origin) of the destination image rectangle where the source image (or its ROI) is copied. Size of the rectanlge matches the source image size/ROI size}
\cvarg{bordertype}{Type of the border to create around the copied source image rectangle; types include:
\begin{description}
\cvarg{IPL\_BORDER\_CONSTANT}{border is filled with the fixed value, passed as last parameter of the function.}
\cvarg{IPL\_BORDER\_REPLICATE}{the pixels from the top and bottom rows, the left-most and right-most columns are replicated to fill the border.}
\end{description}
(The other two border types from IPL, \texttt{IPL\_BORDER\_REFLECT} and \texttt{IPL\_BORDER\_WRAP}, are currently unsupported)}
\cvarg{value}{Value of the border pixels if \texttt{bordertype} is \texttt{IPL\_BORDER\_CONSTANT}}
\end{description}

The function copies the source 2D array into the interior of the destination array and makes a border of the specified type around the copied area. The function is useful when one needs to emulate border type that is different from the one embedded into a specific algorithm implementation. For example, morphological functions, as well as most of other filtering functions in OpenCV, internally use replication border type, while the user may need a zero border or a border, filled with 1's or 255's.

\cvCPyFunc{CreateStructuringElementEx}
Creates a structuring element.

\cvdefC{IplConvKernel* cvCreateStructuringElementEx(\par int cols,
 \par int rows, \par int anchorX, \par int anchorY, \par int shape, \par int* values=NULL );}
\cvdefPy{CreateStructuringElementEx(cols,rows,anchorX,anchorY,shape,values=None)-> kernel}

\begin{description}
\cvarg{cols}{Number of columns in the structuring element}
\cvarg{rows}{Number of rows in the structuring element}
\cvarg{anchorX}{Relative horizontal offset of the anchor point}
\cvarg{anchorY}{Relative vertical offset of the anchor point}
\cvarg{shape}{Shape of the structuring element; may have the following values:
\begin{description}
  \cvarg{CV\_SHAPE\_RECT}{a rectangular element}
  \cvarg{CV\_SHAPE\_CROSS}{a cross-shaped element}
  \cvarg{CV\_SHAPE\_ELLIPSE}{an elliptic element}
  \cvarg{CV\_SHAPE\_CUSTOM}{a user-defined element. In this case the parameter \texttt{values} specifies the mask, that is, which neighbors of the pixel must be considered}
\end{description}}
\cvarg{values}{Pointer to the structuring element data, a plane array, representing row-by-row scanning of the element matrix. Non-zero values indicate points that belong to the element. If the pointer is \texttt{NULL}, then all values are considered non-zero, that is, the element is of a rectangular shape. This parameter is considered only if the shape is \texttt{CV\_SHAPE\_CUSTOM} }
\end{description}

The function CreateStructuringElementEx allocates and fills the structure \texttt{IplConvKernel}, which can be used as a structuring element in the morphological operations.

\cvCPyFunc{Dilate}
Dilates an image by using a specific structuring element.

\cvdefC{void cvDilate(\par const CvArr* src,\par CvArr* dst,\par IplConvKernel* element=NULL,\par int iterations=1 );}
\cvdefPy{Dilate(src,dst,element=None,iterations=1)-> None}

\begin{description}
\cvarg{src}{Source image}
\cvarg{dst}{Destination image}
\cvarg{element}{Structuring element used for dilation. If it is
\cvC{\texttt{NULL},}
\cvPy{\texttt{None},}
a $3\times 3$ rectangular structuring element is used}
\cvarg{iterations}{Number of times dilation is applied}
\end{description}

The function dilates the source image using the specified structuring element that determines the shape of a pixel neighborhood over which the maximum is taken:

\[
\max_{(x',y') \, in \, \texttt{element}}src(x+x',y+y')
\]

The function supports the in-place mode. Dilation can be applied several (\texttt{iterations}) times. For color images, each channel is processed independently.

\cvCPyFunc{Erode}
Erodes an image by using a specific structuring element.

\cvdefC{void cvErode(\par const CvArr* src,\par  CvArr* dst,\par  IplConvKernel* element=NULL,\par  int iterations=1);}
\cvdefPy{Erode(src,dst,element=None,iterations=1)-> None}

\begin{description}
\cvarg{src}{Source image}
\cvarg{dst}{Destination image}
\cvarg{element}{Structuring element used for erosion. If it is
\cvC{\texttt{NULL},}
\cvPy{\texttt{None},}
a $3\times 3$ rectangular structuring element is used}
\cvarg{iterations}{Number of times erosion is applied}
\end{description}

The function erodes the source image using the specified structuring element that determines the shape of a pixel neighborhood over which the minimum is taken:

\[
\min_{(x',y') \, in \, \texttt{element}}src(x+x',y+y')
\]

The function supports the in-place mode. Erosion can be applied several (\texttt{iterations}) times. For color images, each channel is processed independently.

\cvCPyFunc{Filter2D}
Convolves an image with the kernel.

\cvdefC{void cvFilter2D(
\par const CvArr* src,\par  CvArr* dst,\par  const CvMat* kernel,\par  CvPoint anchor=cvPoint(-1,-1));}
\cvdefPy{Filter2D(src,dst,kernel,anchor=(-1,-1))-> None}

\begin{description}
\cvarg{src}{The source image}
\cvarg{dst}{The destination image}
\cvarg{kernel}{Convolution kernel, a single-channel floating point matrix. If you want to apply different kernels to different channels, split the image into separate color planes using \cvCPyCross{Split} and process them individually}
\cvarg{anchor}{The anchor of the kernel that indicates the relative position of a filtered point within the kernel. The anchor shoud lie within the kernel. The special default value (-1,-1) means that it is at the kernel center}
\end{description}

The function applies an arbitrary linear filter to the image. In-place operation is supported. When the aperture is partially outside the image, the function interpolates outlier pixel values from the nearest pixels that are inside the image.

\cvCPyFunc{Laplace}
Calculates the Laplacian of an image.

\cvdefC{void cvLaplace(\par const CvArr* src,\par  CvArr* dst,\par  int apertureSize=3);}
\cvdefPy{Laplace(src,dst,apertureSize=3)-> None}
\begin{description}
\cvarg{src}{Source image}
\cvarg{dst}{Destination image}
\cvarg{apertureSize}{Aperture size (it has the same meaning as \cvCPyCross{Sobel})}
\end{description}

The function calculates the Laplacian of the source image by adding up the second x and y derivatives calculated using the Sobel operator:

\[
\texttt{dst}(x,y) = \frac{d^2 \texttt{src}}{dx^2} + \frac{d^2 \texttt{src}}{dy^2}
\]

Setting \texttt{apertureSize} = 1 gives the fastest variant that is equal to convolving the image with the following kernel:

\[ \vecthreethree {0}{1}{0}{1}{-4}{1}{0}{1}{0} \]

Similar to the \cvCPyCross{Sobel} function, no scaling is done and the same combinations of input and output formats are supported.

\cvCPyFunc{MorphologyEx}
Performs advanced morphological transformations.

\cvdefC{void cvMorphologyEx(
\par const CvArr* src,\par  CvArr* dst,\par  CvArr* temp,\par  IplConvKernel* element,
\par int operation,\par  int iterations=1 );}
\cvdefPy{MorphologyEx(src,dst,temp,element,operation,iterations=1)-> None}

\begin{description}
\cvarg{src}{Source image}
\cvarg{dst}{Destination image}
\cvarg{temp}{Temporary image, required in some cases}
\cvarg{element}{Structuring element}
\cvarg{operation}{Type of morphological operation, one of the following:
\begin{description}
\cvarg{CV\_MOP\_OPEN}{opening}
\cvarg{CV\_MOP\_CLOSE}{closing}
\cvarg{CV\_MOP\_GRADIENT}{morphological gradient}
\cvarg{CV\_MOP\_TOPHAT}{"top hat"}
\cvarg{CV\_MOP\_BLACKHAT}{"black hat"}
\end{description}}
\cvarg{iterations}{Number of times erosion and dilation are applied}
\end{description}

The function can perform advanced morphological transformations using erosion and dilation as basic operations.

Opening:

\[
dst=open(src,element)=dilate(erode(src,element),element)
\]

Closing:

\[
dst=close(src,element)=erode(dilate(src,element),element)
\]

Morphological gradient:

\[
dst=morph\_grad(src,element)=dilate(src,element)-erode(src,element)
\]

"Top hat":

\[
dst=tophat(src,element)=src-open(src,element)
\]

"Black hat":

\[
dst=blackhat(src,element)=close(src,element)-src
\]

The temporary image \texttt{temp} is required for a morphological gradient and, in the case of in-place operation, for "top hat" and "black hat".

\cvCPyFunc{PyrDown}
Downsamples an image.

\cvdefC{void cvPyrDown(\par const CvArr* src,\par CvArr* dst,\par int filter=CV\_GAUSSIAN\_5x5 );}
\cvdefPy{PyrDown(src,dst,filter=CV\_GAUSSIAN\_5X5)-> None}

\begin{description}
\cvarg{src}{The source image}
\cvarg{dst}{The destination image, should have a half as large width and height than the source}
\cvarg{filter}{Type of the filter used for convolution; only \texttt{CV\_GAUSSIAN\_5x5} is currently supported}
\end{description}

The function performs the downsampling step of the Gaussian pyramid decomposition. First it convolves the source image with the specified filter and then downsamples the image by rejecting even rows and columns.

\ifC
\cvCPyFunc{ReleaseStructuringElement}
Deletes a structuring element.

\cvdefC{void cvReleaseStructuringElement( IplConvKernel** element );}

\begin{description}
\cvarg{element}{Pointer to the deleted structuring element}
\end{description}

The function releases the structure \texttt{IplConvKernel} that is no longer needed. If \texttt{*element} is \texttt{NULL}, the function has no effect.
\fi

\cvCPyFunc{Smooth}
Smooths the image in one of several ways.

\cvdefC{void cvSmooth(\par const CvArr* src,
\par CvArr* dst,\par  int smoothtype=CV\_GAUSSIAN,\par  int param1=3,\par  int param2=0,\par  double param3=0, \par double param4=0);}
\cvdefPy{Smooth(src,dst,smoothtype=CV\_GAUSSIAN,param1=3,param2=0,param3=0,param4=0)-> None}

\begin{description}
\cvarg{src}{The source image}
\cvarg{dst}{The destination image}
\cvarg{smoothtype}{Type of the smoothing:
\begin{description}
  \cvarg{CV\_BLUR\_NO\_SCALE}{linear convolution with $\texttt{param1}\times\texttt{param2}$ box kernel (all 1's). If you want to smooth different pixels with different-size box kernels, you can use the integral image that is computed using \cvCPyCross{Integral}}
  \cvarg{CV\_BLUR}{linear convolution with $\texttt{param1}\times\texttt{param2}$ box kernel (all 1's) with subsequent scaling by $1/(\texttt{param1}\cdot\texttt{param2})$}
  \cvarg{CV\_GAUSSIAN}{linear convolution with a $\texttt{param1}\times\texttt{param2}$ Gaussian kernel}
  \cvarg{CV\_MEDIAN}{median filter with a $\texttt{param1}\times\texttt{param1}$ square aperture}
  \cvarg{CV\_BILATERAL}{bilateral filter with a $\texttt{param1}\times\texttt{param1}$ square aperture, color sigma=\texttt{param3} and spatial sigma=\texttt{param4}. If \texttt{param1=0}, the aperture square side is set to \texttt{cvRound(param4*1.5)*2+1}. Information about bilateral filtering can be found at \url{http://www.dai.ed.ac.uk/CVonline/LOCAL\_COPIES/MANDUCHI1/Bilateral\_Filtering.html}}
\end{description}}
\cvarg{param1}{The first parameter of the smoothing operation, the aperture width. Must be a positive odd number (1, 3, 5, ...)}
\cvarg{param2}{The second parameter of the smoothing operation, the aperture height. Ignored by \texttt{CV\_MEDIAN} and \texttt{CV\_BILATERAL} methods. In the case of simple scaled/non-scaled and Gaussian blur if \texttt{param2} is zero, it is set to \texttt{param1}. Otherwise it must be a positive odd number.}
\cvarg{param3}{In the case of a Gaussian parameter this parameter may specify Gaussian $\sigma$ (standard deviation). If it is zero, it is calculated from the kernel size:
\[
\sigma = 0.3 (n/2 - 1) + 0.8 \quad \text{where} \quad n=
\begin{array}{l l}
\mbox{\texttt{param1} for horizontal kernel}\\
\mbox{\texttt{param2} for vertical kernel}
\end{array}
\]

Using standard sigma for small kernels ($3\times 3$ to $7\times 7$) gives better speed. If \texttt{param3} is not zero, while \texttt{param1} and \texttt{param2} are zeros, the kernel size is calculated from the sigma (to provide accurate enough operation).}
\end{description}

The function smooths an image using one of several methods. Every of the methods has some features and restrictions listed below

Blur with no scaling works with single-channel images only and supports accumulation of 8-bit to 16-bit format (similar to \cvCPyCross{Sobel} and \cvCPyCross{Laplace}) and 32-bit floating point to 32-bit floating-point format.

Simple blur and Gaussian blur support 1- or 3-channel, 8-bit and 32-bit floating point images. These two methods can process images in-place.

Median and bilateral filters work with 1- or 3-channel 8-bit images and can not process images in-place.

\cvCPyFunc{Sobel}
Calculates the first, second, third or mixed image derivatives using an extended Sobel operator.

\cvdefC{void cvSobel(\par const CvArr* src,\par  CvArr* dst,\par  int xorder,\par  int yorder,\par  int apertureSize=3 );}
\cvdefPy{Sobel(src,dst,xorder,yorder,apertureSize = 3)-> None}

\begin{description}
\cvarg{src}{Source image of type CvArr*}
\cvarg{dst}{Destination image}
\cvarg{xorder}{Order of the derivative x}
\cvarg{yorder}{Order of the derivative y}
\cvarg{apertureSize}{Size of the extended Sobel kernel, must be 1, 3, 5 or 7}
\end{description}

In all cases except 1, an $\texttt{apertureSize} \times
\texttt{apertureSize}$ separable kernel will be used to calculate the
derivative. For $\texttt{apertureSize} = 1$ a $3 \times 1$ or $1 \times 3$
a kernel is used (Gaussian smoothing is not done). There is also the special
value \texttt{CV\_SCHARR} (-1) that corresponds to a $3\times3$ Scharr
filter that may give more accurate results than a $3\times3$ Sobel. Scharr
aperture is

\[ \vecthreethree
{-3}{0}{3}
{-10}{0}{10}
{-3}{0}{3}
\]

for the x-derivative or transposed for the y-derivative.

The function calculates the image derivative by convolving the image with the appropriate kernel:

\[
\texttt{dst}(x,y) = \frac{d^{xorder+yorder} \texttt{src}}{dx^{xorder} \cdot dy^{yorder}}
\]

The Sobel operators combine Gaussian smoothing and differentiation
so the result is more or less resistant to the noise. Most often,
the function is called with (\texttt{xorder} = 1, \texttt{yorder} = 0,
\texttt{apertureSize} = 3) or (\texttt{xorder} = 0, \texttt{yorder} = 1,
\texttt{apertureSize} = 3) to calculate the first x- or y- image
derivative. The first case corresponds to a kernel of:

\[ \vecthreethree
{-1}{0}{1}
{-2}{0}{2}
{-1}{0}{1}
\]

and the second one corresponds to a kernel of:
\[ \vecthreethree
{-1}{-2}{-1}
{0}{0}{0}
{1}{2}{1}
\]
or a kernel of:
\[ \vecthreethree
{1}{2}{1}
{0}{0}{0}
{-1}{2}{-1}
\]

depending on the image origin (\texttt{origin} field of
\texttt{IplImage} structure). No scaling is done, so the destination image
usually has larger numbers (in absolute values) than the source image does. To
avoid overflow, the function requires a 16-bit destination image if the
source image is 8-bit. The result can be converted back to 8-bit using the
\cvCPyCross{ConvertScale} or the \cvCPyCross{ConvertScaleAbs} function. Besides 8-bit images
the function can process 32-bit floating-point images. Both the source and the 
destination must be single-channel images of equal size or equal ROI size.

\fi

\ifCpp

\cvclass{BaseColumnFilter}
Base class for filters with single-column kernels

\begin{lstlisting}
class BaseColumnFilter
{
public:
    virtual ~BaseColumnFilter();
    
    // To be overriden by the user.
    //
    // runs filtering operation on the set of rows,
    // "dstcount + ksize - 1" rows on input,
    // "dstcount" rows on output,
    // each input and output row has "width" elements
    // the filtered rows are written into "dst" buffer.
    virtual void operator()(const uchar** src, uchar* dst, int dststep,
                            int dstcount, int width) = 0;
    // resets the filter state (may be needed for IIR filters)
    virtual void reset();
    
    int ksize; // the aperture size
    int anchor; // position of the anchor point,
                // normally not used during the processing
};
\end{lstlisting}

The class \texttt{BaseColumnFilter} is the base class for filtering data using single-column kernels. The filtering does not have to be a linear operation. In general, it could be written as following:

\[\texttt{dst}(x,y) = F(\texttt{src}[y](x),\;\texttt{src}[y+1](x),\;...,\;\texttt{src}[y+\texttt{ksize}-1](x)\]

where $F$ is the filtering function, but, as it is represented as a class, it can produce any side effects, memorize previously processed data etc. The class only defines the interface and is not used directly. Instead, there are several functions in OpenCV (and you can add more) that return pointers to the derived classes that implement specific filtering operations. Those pointers are then passed to \cvCppCross{FilterEngine} constructor. While the filtering operation interface uses \texttt{uchar} type, a particular implementation is not limited to 8-bit data.

See also: \cvCppCross{BaseRowFilter}, \cvCppCross{BaseFilter}, \cvCppCross{FilterEngine},
    \cvCppCross{getColumnSumFilter}, \cvCppCross{getLinearColumnFilter}, \cvCppCross{getMorphologyColumnFilter}


\cvclass{BaseFilter}
Base class for 2D image filters

\begin{lstlisting}
class BaseFilter
{
public:
    virtual ~BaseFilter();
    
    // To be overriden by the user.
    //
    // runs filtering operation on the set of rows,
    // "dstcount + ksize.height - 1" rows on input,
    // "dstcount" rows on output,
    // each input row has "(width + ksize.width-1)*cn" elements
    // each output row has "width*cn" elements.
    // the filtered rows are written into "dst" buffer.
    virtual void operator()(const uchar** src, uchar* dst, int dststep,
                            int dstcount, int width, int cn) = 0;
    // resets the filter state (may be needed for IIR filters)                        
    virtual void reset();
    Size ksize;
    Point anchor;
};
\end{lstlisting}

The class \texttt{BaseFilter} is the base class for filtering data using 2D kernels. The filtering does not have to be a linear operation. In general, it could be written as following:

\[
  \begin{array}{l}
  \texttt{dst}(x,y) = F( \texttt{src}[y](x),\;\texttt{src}[y](x+1),\;...,\;\texttt{src}[y](x+\texttt{ksize.width}-1), \\
  \texttt{src}[y+1](x),\;\texttt{src}[y+1](x+1),\;...,\;\texttt{src}[y+1](x+\texttt{ksize.width}-1), \\
  ......................................................................................... \\
  \texttt{src}[y+\texttt{ksize.height-1}](x),\\
  \texttt{src}[y+\texttt{ksize.height-1}](x+1),\\
  ...
  \texttt{src}[y+\texttt{ksize.height-1}](x+\texttt{ksize.width}-1))
  \end{array}
  \]

where $F$ is the filtering function. The class only defines the interface and is not used directly. Instead, there are several functions in OpenCV (and you can add more) that return pointers to the derived classes that implement specific filtering operations. Those pointers are then passed to \cvCppCross{FilterEngine} constructor. While the filtering operation interface uses \texttt{uchar} type, a particular implementation is not limited to 8-bit data.

See also: \cvCppCross{BaseColumnFilter}, \cvCppCross{BaseRowFilter}, \cvCppCross{FilterEngine},
    \cvCppCross{getLinearFilter}, \cvCppCross{getMorphologyFilter}

\cvclass{BaseRowFilter}
Base class for filters with single-row kernels

\begin{lstlisting}
class BaseRowFilter
{
public:
    virtual ~BaseRowFilter();
    
    // To be overriden by the user.
    //
    // runs filtering operation on the single input row
    // of "width" element, each element is has "cn" channels.
    // the filtered row is written into "dst" buffer.
    virtual void operator()(const uchar* src, uchar* dst,
                            int width, int cn) = 0;
    int ksize, anchor;
};
\end{lstlisting}

The class \texttt{BaseRowFilter} is the base class for filtering data using single-row kernels. The filtering does not have to be a linear operation. In general, it could be written as following:

\[\texttt{dst}(x,y) = F(\texttt{src}[y](x),\;\texttt{src}[y](x+1),\;...,\;\texttt{src}[y](x+\texttt{ksize.width}-1))\]

where $F$ is the filtering function. The class only defines the interface and is not used directly. Instead, there are several functions in OpenCV (and you can add more) that return pointers to the derived classes that implement specific filtering operations. Those pointers are then passed to \cvCppCross{FilterEngine} constructor. While the filtering operation interface uses \texttt{uchar} type, a particular implementation is not limited to 8-bit data.

See also: \cvCppCross{BaseColumnFilter}, \cvCppCross{Filter}, \cvCppCross{FilterEngine},
 \cvCppCross{getLinearRowFilter}, \cvCppCross{getMorphologyRowFilter}, \cvCppCross{getRowSumFilter}

\cvclass{FilterEngine}
Generic image filtering class

\begin{lstlisting}
class FilterEngine
{
public:
    // empty constructor
    FilterEngine();
    // builds a 2D non-separable filter (!_filter2D.empty()) or
    // a separable filter (!_rowFilter.empty() && !_columnFilter.empty())
    // the input data type will be "srcType", the output data type will be "dstType",
    // the intermediate data type is "bufType".
    // _rowBorderType and _columnBorderType determine how the image
    // will be extrapolated beyond the image boundaries.
    // _borderValue is only used when _rowBorderType and/or _columnBorderType
    // == cv::BORDER_CONSTANT
    FilterEngine(const Ptr<BaseFilter>& _filter2D,
                 const Ptr<BaseRowFilter>& _rowFilter,
                 const Ptr<BaseColumnFilter>& _columnFilter,
                 int srcType, int dstType, int bufType,
                 int _rowBorderType=BORDER_REPLICATE,
                 int _columnBorderType=-1, // use _rowBorderType by default 
                 const Scalar& _borderValue=Scalar());
    virtual ~FilterEngine();
    // separate function for the engine initialization
    void init(const Ptr<BaseFilter>& _filter2D,
              const Ptr<BaseRowFilter>& _rowFilter,
              const Ptr<BaseColumnFilter>& _columnFilter,
              int srcType, int dstType, int bufType,
              int _rowBorderType=BORDER_REPLICATE, int _columnBorderType=-1,
              const Scalar& _borderValue=Scalar());
    // starts filtering of the ROI in an image of size "wholeSize".
    // returns the starting y-position in the source image.
    virtual int start(Size wholeSize, Rect roi, int maxBufRows=-1);
    // alternative form of start that takes the image
    // itself instead of "wholeSize". Set isolated to true to pretend that
    // there are no real pixels outside of the ROI
    // (so that the pixels will be extrapolated using the specified border modes)
    virtual int start(const Mat& src, const Rect& srcRoi=Rect(0,0,-1,-1),
                      bool isolated=false, int maxBufRows=-1);
    // processes the next portion of the source image,
    // "srcCount" rows starting from "src" and
    // stores the results to "dst".
    // returns the number of produced rows
    virtual int proceed(const uchar* src, int srcStep, int srcCount,
                        uchar* dst, int dstStep);
    // higher-level function that processes the whole
    // ROI or the whole image with a single call
    virtual void apply( const Mat& src, Mat& dst,
                        const Rect& srcRoi=Rect(0,0,-1,-1),
                        Point dstOfs=Point(0,0),
                        bool isolated=false);
    bool isSeparable() const { return filter2D.empty(); }
    // how many rows from the input image are not yet processed
    int remainingInputRows() const;
    // how many output rows are not yet produced
    int remainingOutputRows() const;
    ...
    // the starting and the ending rows in the source image
    int startY, endY;
    
    // pointers to the filters
    Ptr<BaseFilter> filter2D;
    Ptr<BaseRowFilter> rowFilter;
    Ptr<BaseColumnFilter> columnFilter;
};
\end{lstlisting}

The class \texttt{FilterEngine} can be used to apply an arbitrary filtering operation to an image.
It contains all the necessary intermediate buffers, it computes extrapolated values
of the "virtual" pixels outside of the image etc. Pointers to the initialized \texttt{FilterEngine} instances
are returned by various \texttt{create*Filter} functions, see below, and they are used inside high-level functions such as \cvCppCross{filter2D}, \cvCppCross{erode}, \cvCppCross{dilate} etc, that is, the class is the workhorse in many of OpenCV filtering functions.

This class makes it easier (though, maybe not very easy yet) to combine filtering operations with other operations, such as color space conversions, thresholding, arithmetic operations, etc. By combining several operations together you can get much better performance because your data will stay in cache. For example, below is the implementation of Laplace operator for a floating-point images, which is a simplified implementation of \cvCppCross{Laplacian}:

\begin{lstlisting}
void laplace_f(const Mat& src, Mat& dst)
{
    CV_Assert( src.type() == CV_32F );
    dst.create(src.size(), src.type());
    
    // get the derivative and smooth kernels for d2I/dx2.
    // for d2I/dy2 we could use the same kernels, just swapped
    Mat kd, ks;
    getSobelKernels( kd, ks, 2, 0, ksize, false, ktype );
    
    // let's process 10 source rows at once
    int DELTA = std::min(10, src.rows);
    Ptr<FilterEngine> Fxx = createSeparableLinearFilter(src.type(),
        dst.type(), kd, ks, Point(-1,-1), 0, borderType, borderType, Scalar() ); 
    Ptr<FilterEngine> Fyy = createSeparableLinearFilter(src.type(),
        dst.type(), ks, kd, Point(-1,-1), 0, borderType, borderType, Scalar() );

    int y = Fxx->start(src), dsty = 0, dy = 0;
    Fyy->start(src);
    const uchar* sptr = src.data + y*src.step;

    // allocate the buffers for the spatial image derivatives;
    // the buffers need to have more than DELTA rows, because at the
    // last iteration the output may take max(kd.rows-1,ks.rows-1)
    // rows more than the input.
    Mat Ixx( DELTA + kd.rows - 1, src.cols, dst.type() );
    Mat Iyy( DELTA + kd.rows - 1, src.cols, dst.type() );
    
    // inside the loop we always pass DELTA rows to the filter
    // (note that the "proceed" method takes care of possibe overflow, since
    // it was given the actual image height in the "start" method)
    // on output we can get:
    //  * < DELTA rows (the initial buffer accumulation stage)
    //  * = DELTA rows (settled state in the middle)
    //  * > DELTA rows (then the input image is over, but we generate
    //                  "virtual" rows using the border mode and filter them)
    // this variable number of output rows is dy.
    // dsty is the current output row.
    // sptr is the pointer to the first input row in the portion to process
    for( ; dsty < dst.rows; sptr += DELTA*src.step, dsty += dy )
    {
        Fxx->proceed( sptr, (int)src.step, DELTA, Ixx.data, (int)Ixx.step );
        dy = Fyy->proceed( sptr, (int)src.step, DELTA, d2y.data, (int)Iyy.step );
        if( dy > 0 )
        {
            Mat dstripe = dst.rowRange(dsty, dsty + dy);
            add(Ixx.rowRange(0, dy), Iyy.rowRange(0, dy), dstripe);
        }
    }
}
\end{lstlisting}

If you do not need that much control of the filtering process, you can simply use the \texttt{FilterEngine::apply} method. Here is how the method is actually implemented:

\begin{lstlisting}
void FilterEngine::apply(const Mat& src, Mat& dst,
    const Rect& srcRoi, Point dstOfs, bool isolated)
{
    // check matrix types
    CV_Assert( src.type() == srcType && dst.type() == dstType );
    
    // handle the "whole image" case
    Rect _srcRoi = srcRoi;
    if( _srcRoi == Rect(0,0,-1,-1) )
        _srcRoi = Rect(0,0,src.cols,src.rows);
    
    // check if the destination ROI is inside the dst.
    // and FilterEngine::start will check if the source ROI is inside src.
    CV_Assert( dstOfs.x >= 0 && dstOfs.y >= 0 &&
        dstOfs.x + _srcRoi.width <= dst.cols &&
        dstOfs.y + _srcRoi.height <= dst.rows );

    // start filtering
    int y = start(src, _srcRoi, isolated);
    
    // process the whole ROI. Note that "endY - startY" is the total number
    // of the source rows to process
    // (including the possible rows outside of srcRoi but inside the source image)
    proceed( src.data + y*src.step,
             (int)src.step, endY - startY,
             dst.data + dstOfs.y*dst.step +
             dstOfs.x*dst.elemSize(), (int)dst.step );
}
\end{lstlisting}

Unlike the earlier versions of OpenCV, now the filtering operations fully support the notion of image ROI, that is, pixels outside of the ROI but inside the image can be used in the filtering operations. For example, you can take a ROI of a single pixel and filter it - that will be a filter response at that particular pixel (however, it's possible to emulate the old behavior by passing \texttt{isolated=false} to \texttt{FilterEngine::start} or \texttt{FilterEngine::apply}). You can pass the ROI explicitly to \texttt{FilterEngine::apply}, or construct a new matrix headers:

\begin{lstlisting}
// compute dI/dx derivative at src(x,y)

// method 1:
// form a matrix header for a single value
float val1 = 0;
Mat dst1(1,1,CV_32F,&val1);

Ptr<FilterEngine> Fx = createDerivFilter(CV_32F, CV_32F,
                        1, 0, 3, BORDER_REFLECT_101);
Fx->apply(src, Rect(x,y,1,1), Point(), dst1);

// method 2:
// form a matrix header for a single value
float val2 = 0;
Mat dst2(1,1,CV_32F,&val2);

Mat pix_roi(src, Rect(x,y,1,1));
Sobel(pix_roi, dst2, dst2.type(), 1, 0, 3, 1, 0, BORDER_REFLECT_101);

printf("method1 = %g, method2 = %g\n", val1, val2);
\end{lstlisting}

Note on the data types. As it was mentioned in \cvCppCross{BaseFilter} description, the specific filters can process data of any type, despite that \texttt{Base*Filter::operator()} only takes \texttt{uchar} pointers and no information about the actual types. To make it all work, the following rules are used:

\begin{itemize}
    \item in case of separable filtering \texttt{FilterEngine::rowFilter} applied first. It transforms the input image data (of type \texttt{srcType}) to the intermediate results stored in the internal buffers (of type \texttt{bufType}). Then these intermediate results are processed \emph{as single-channel data} with \texttt{FilterEngine::columnFilter} and stored in the output image (of type \texttt{dstType}). Thus, the input type for \texttt{rowFilter} is \texttt{srcType} and the output type is \texttt{bufType}; the input type for \texttt{columnFilter} is \texttt{CV\_MAT\_DEPTH(bufType)} and the output type is \texttt{CV\_MAT\_DEPTH(dstType)}.
    
    \item in case of non-separable filtering \texttt{bufType} must be the same as \texttt{srcType}. The source data is copied to the temporary buffer if needed and then just passed to \texttt{FilterEngine::filter2D}. That is, the input type for \texttt{filter2D} is \texttt{srcType} (=\texttt{bufType}) and the output type is \texttt{dstType}.
\end{itemize}

See also: \cvCppCross{BaseColumnFilter}, \cvCppCross{BaseFilter}, \cvCppCross{BaseRowFilter}, \cvCppCross{createBoxFilter},
\cvCppCross{createDerivFilter}, \cvCppCross{createGaussianFilter}, \cvCppCross{createLinearFilter},
\cvCppCross{createMorphologyFilter}, \cvCppCross{createSeparableLinearFilter}

\cvCppFunc{bilateralFilter}
Applies bilateral filter to the image

\cvdefCpp{void bilateralFilter( const Mat\& src, Mat\& dst, int d,\par
                      double sigmaColor, double sigmaSpace,\par
                      int borderType=BORDER\_DEFAULT );}
\begin{description}
\cvarg{src}{The source 8-bit or floating-point, 1-channel or 3-channel image}
\cvarg{dst}{The destination image; will have the same size and the same type as \texttt{src}}
\cvarg{d}{The diameter of each pixel neighborhood, that is used during filtering. If it is non-positive, it's computed from \texttt{sigmaSpace}}
\cvarg{sigmaColor}{Filter sigma in the color space. Larger value of the parameter means that farther colors within the pixel neighborhood (see \texttt{sigmaSpace}) will be mixed together, resulting in larger areas of semi-equal color}
\cvarg{sigmaSpace}{Filter sigma in the coordinate space. Larger value of the parameter means that farther pixels will influence each other (as long as their colors are close enough; see \texttt{sigmaColor}). Then \texttt{d>0}, it specifies the neighborhood size regardless of \texttt{sigmaSpace}, otherwise \texttt{d} is proportional to \texttt{sigmaSpace}}
\end{description}

The function applies bilateral filtering to the input image, as described in
\url{http://www.dai.ed.ac.uk/CVonline/LOCAL\_COPIES/MANDUCHI1/Bilateral\_Filtering.html}

\cvCppFunc{blur}
Smoothes image using normalized box filter

\cvdefCpp{void blur( const Mat\& src, Mat\& dst,\par
           Size ksize, Point anchor=Point(-1,-1),\par
           int borderType=BORDER\_DEFAULT );}
\begin{description}
\cvarg{src}{The source image}
\cvarg{dst}{The destination image; will have the same size and the same type as \texttt{src}}
\cvarg{ksize}{The smoothing kernel size}
\cvarg{anchor}{The anchor point. The default value \texttt{Point(-1,-1)} means that the anchor is at the kernel center}
\cvarg{borderType}{The border mode used to extrapolate pixels outside of the image}
\end{description}

The function smoothes the image using the kernel:

\[ \texttt{K} = \frac{1}{\texttt{ksize.width*ksize.height}}
\begin{bmatrix}
1 & 1 & 1 & \cdots & 1 & 1 \\
1 & 1 & 1 & \cdots & 1 & 1 \\
\hdotsfor{6} \\
1 & 1 & 1 & \cdots & 1 & 1 \\
\end{bmatrix}
\]

The call \texttt{blur(src, dst, ksize, anchor, borderType)} is equivalent to
\texttt{boxFilter(src, dst, src.type(), anchor, true, borderType)}.

See also: \cvCppCross{boxFilter}, \cvCppCross{bilateralFilter}, \cvCppCross{GaussianBlur}, \cvCppCross{medianBlur}.

\cvCppFunc{borderInterpolate}
Computes source location of extrapolated pixel

\cvdefCpp{int borderInterpolate( int p, int len, int borderType );}
\begin{description}
\cvarg{p}{0-based coordinate of the extrapolated pixel along one of the axes, likely <0 or >=\texttt{len}}
\cvarg{len}{length of the array along the corresponding axis}
\cvarg{borderType}{the border type, one of the \texttt{BORDER\_*}, except for \texttt{BORDER\_TRANSPARENT} and \texttt{BORDER\_ISOLATED}. When \texttt{borderType==BORDER\_CONSTANT} the function always returns -1, regardless of \texttt{p} and \texttt{len}}
\end{description}

The function computes and returns the coordinate of the donor pixel, corresponding to the specified extrapolated pixel when using the specified extrapolation border mode. For example, if we use \texttt{BORDER\_WRAP} mode in the horizontal direction, \texttt{BORDER\_REFLECT\_101} in the vertical direction and want to compute value of the "virtual" pixel \texttt{Point(-5, 100)} in a floating-point image \texttt{img}, it will be

\begin{lstlisting}
float val = img.at<float>(borderInterpolate(100, img.rows, BORDER_REFLECT_101),
                          borderInterpolate(-5, img.cols, BORDER_WRAP));
\end{lstlisting}

Normally, the function is not called directly; it is used inside \cvCppCross{FilterEngine} and \cvCppCross{copyMakeBorder} to compute tables for quick extrapolation.

See also: \cvCppCross{FilterEngine}, \cvCppCross{copyMakeBorder}

\cvCppFunc{boxFilter}
Smoothes image using box filter

\cvdefCpp{void boxFilter( const Mat\& src, Mat\& dst, int ddepth,\par
                Size ksize, Point anchor=Point(-1,-1),\par
                bool normalize=true,\par
                int borderType=BORDER\_DEFAULT );}
\begin{description}
\cvarg{src}{The source image}
\cvarg{dst}{The destination image; will have the same size and the same type as \texttt{src}}
\cvarg{ksize}{The smoothing kernel size}
\cvarg{anchor}{The anchor point. The default value \texttt{Point(-1,-1)} means that the anchor is at the kernel center}
\cvarg{normalize}{Indicates, whether the kernel is normalized by its area or not}
\cvarg{borderType}{The border mode used to extrapolate pixels outside of the image}
\end{description}

The function smoothes the image using the kernel:

\[ \texttt{K} = \alpha
\begin{bmatrix}
1 & 1 & 1 & \cdots & 1 & 1 \\
1 & 1 & 1 & \cdots & 1 & 1 \\
\hdotsfor{6} \\
1 & 1 & 1 & \cdots & 1 & 1
\end{bmatrix}
\]

where

\[\alpha=\fork
{\frac{1}{\texttt{ksize.width*ksize.height}}}{when \texttt{normalize=true}}
{1}{otherwise} \]

Unnormalized box filter is useful for computing various integral characteristics over each pixel neighborhood, such as covariation matrices of image derivatives (used in dense optical flow algorithms, \hyperref[conerHarris]{Harris corner detector} etc.). If you need to compute pixel sums over variable-size windows, use \cvCppCross{integral}.

See also: \cvCppCross{boxFilter}, \cvCppCross{bilateralFilter}, \cvCppCross{GaussianBlur}, \cvCppCross{medianBlur}, \cvCppCross{integral}.

\cvCppFunc{buildPyramid}
Constructs Gaussian pyramid for an image

\cvdefCpp{void buildPyramid( const Mat\& src, vector<Mat>\& dst, int maxlevel );}
\begin{description}
\cvarg{src}{The source image; check \cvCppCross{pyrDown} for the list of supported types}
\cvarg{dst}{The destination vector of \texttt{maxlevel+1} images of the same type as \texttt{src};
\texttt{dst[0]} will be the same as \texttt{src}, \texttt{dst[1]} is the next pyramid layer,
a smoothed and down-sized \texttt{src} etc.}
\cvarg{maxlevel}{The 0-based index of the last (i.e. the smallest) pyramid layer; it must be non-negative}
\end{description}

The function constructs a vector of images and builds the gaussian pyramid by recursively applying \cvCppCross{pyrDown} to the previously built pyramid layers, starting from \texttt{dst[0]==src}.

\cvCppFunc{copyMakeBorder}
Forms a border around the image

\cvdefCpp{void copyMakeBorder( const Mat\& src, Mat\& dst,\par
                    int top, int bottom, int left, int right,\par
                    int borderType, const Scalar\& value=Scalar() );}
\begin{description}
\cvarg{src}{The source image}
\cvarg{dst}{The destination image; will have the same type as \texttt{src} and the size \texttt{Size(src.cols+left+right, src.rows+top+bottom)}}
\cvarg{top, bottom, left, right}{Specify how much pixels in each direction from the source image rectangle one needs to extrapolate, e.g. \texttt{top=1, bottom=1, left=1, right=1} mean that 1 pixel-wide border needs to be built}
\cvarg{borderType}{The border type; see \cvCppCross{borderInterpolate}}
\cvarg{value}{The border value if \texttt{borderType==BORDER\_CONSTANT}}
\end{description}

The function copies the source image into the middle of the destination image. The areas to the left, to the right, above and below the copied source image will be filled with extrapolated pixels. This is not what \cvCppCross{FilterEngine} or based on it filtering functions do (they extrapolate pixels on-fly), but what other more complex functions, including your own, may do to simplify image boundary handling.

The function supports the mode when \texttt{src} is already in the middle of \texttt{dst}. In this case the function does not copy \texttt{src} itself, but simply constructs the border, e.g.:

\begin{lstlisting}
// let border be the same in all directions
int border=2;
// constructs a larger image to fit both the image and the border
Mat gray_buf(rgb.rows + border*2, rgb.cols + border*2, rgb.depth());
// select the middle part of it w/o copying data
Mat gray(gray_canvas, Rect(border, border, rgb.cols, rgb.rows));
// convert image from RGB to grayscale
cvtColor(rgb, gray, CV_RGB2GRAY);
// form a border in-place
copyMakeBorder(gray, gray_buf, border, border,
               border, border, BORDER_REPLICATE);
// now do some custom filtering ...
...
\end{lstlisting}

See also: \cvCppCross{borderInterpolate}

\cvCppFunc{createBoxFilter}
Returns box filter engine

\cvdefCpp{Ptr<FilterEngine> createBoxFilter( int srcType, int dstType,\par
                                 Size ksize, Point anchor=Point(-1,-1),\par
                                 bool normalize=true,\par
                                 int borderType=BORDER\_DEFAULT);\newline
Ptr<BaseRowFilter> getRowSumFilter(int srcType, int sumType,\par
                                   int ksize, int anchor=-1);\newline
Ptr<BaseColumnFilter> getColumnSumFilter(int sumType, int dstType,\par
                                   int ksize, int anchor=-1, double scale=1);}
\begin{description}
\cvarg{srcType}{The source image type}
\cvarg{sumType}{The intermediate horizontal sum type; must have as many channels as \texttt{srcType}}
\cvarg{dstType}{The destination image type; must have as many channels as \texttt{srcType}}
\cvarg{ksize}{The aperture size}
\cvarg{anchor}{The anchor position with the kernel; negative values mean that the anchor is at the kernel center}
\cvarg{normalize}{Whether the sums are normalized or not; see \cvCppCross{boxFilter}}
\cvarg{scale}{Another way to specify normalization in lower-level \texttt{getColumnSumFilter}}
\cvarg{borderType}{Which border type to use; see \cvCppCross{borderInterpolate}}
\end{description}

The function is a convenience function that retrieves horizontal sum primitive filter with \cvCppCross{getRowSumFilter}, vertical sum filter with \cvCppCross{getColumnSumFilter}, constructs new \cvCppCross{FilterEngine} and passes both of the primitive filters there. The constructed filter engine can be used for image filtering with normalized or unnormalized box filter.

The function itself is used by \cvCppCross{blur} and \cvCppCross{boxFilter}.

See also: \cvCppCross{FilterEngine}, \cvCppCross{blur}, \cvCppCross{boxFilter}.

\cvCppFunc{createDerivFilter}
Returns engine for computing image derivatives 

\cvdefCpp{Ptr<FilterEngine> createDerivFilter( int srcType, int dstType,\par
                                     int dx, int dy, int ksize,\par
                                     int borderType=BORDER\_DEFAULT );}
\begin{description}
\cvarg{srcType}{The source image type}
\cvarg{dstType}{The destination image type; must have as many channels as \texttt{srcType}}
\cvarg{dx}{The derivative order in respect with x}
\cvarg{dy}{The derivative order in respect with y}
\cvarg{ksize}{The aperture size; see \cvCppCross{getDerivKernels}}
\cvarg{borderType}{Which border type to use; see \cvCppCross{borderInterpolate}}
\end{description}

The function \cvCppCross{createDerivFilter} is a small convenience function that retrieves linear filter coefficients for computing image derivatives using \cvCppCross{getDerivKernels} and then creates a separable linear filter with \cvCppCross{createSeparableLinearFilter}. The function is used by \cvCppCross{Sobel} and \cvCppCross{Scharr}.

See also: \cvCppCross{createSeparableLinearFilter}, \cvCppCross{getDerivKernels}, \cvCppCross{Scharr}, \cvCppCross{Sobel}.

\cvCppFunc{createGaussianFilter}
Returns engine for smoothing images with a Gaussian filter

\cvdefCpp{Ptr<FilterEngine> createGaussianFilter( int type, Size ksize,\par
                                   double sigmaX, double sigmaY=0,\par
                                   int borderType=BORDER\_DEFAULT);}
\begin{description}
\cvarg{type}{The source and the destination image type}
\cvarg{ksize}{The aperture size; see \cvCppCross{getGaussianKernel}}
\cvarg{sigmaX}{The Gaussian sigma in the horizontal direction; see \cvCppCross{getGaussianKernel}}
\cvarg{sigmaY}{The Gaussian sigma in the vertical direction; if 0, then $\texttt{sigmaY}\leftarrow\texttt{sigmaX}$}
\cvarg{borderType}{Which border type to use; see \cvCppCross{borderInterpolate}}
\end{description}

The function \cvCppCross{createGaussianFilter} computes Gaussian kernel coefficients and then returns separable linear filter for that kernel. The function is used by \cvCppCross{GaussianBlur}. Note that while the function takes just one data type, both for input and output, you can pass by this limitation by calling \cvCppCross{getGaussianKernel} and then \cvCppCross{createSeparableFilter} directly.

See also: \cvCppCross{createSeparableLinearFilter}, \cvCppCross{getGaussianKernel}, \cvCppCross{GaussianBlur}.

\cvCppFunc{createLinearFilter}
Creates non-separable linear filter engine

\cvdefCpp{Ptr<FilterEngine> createLinearFilter(int srcType, int dstType,\par
               const Mat\& kernel, Point \_anchor=Point(-1,-1),\par
               double delta=0, int rowBorderType=BORDER\_DEFAULT,\par
               int columnBorderType=-1, const Scalar\& borderValue=Scalar());\newline
Ptr<BaseFilter> getLinearFilter(int srcType, int dstType,\par
                               const Mat\& kernel,\par
                               Point anchor=Point(-1,-1),\par
                               double delta=0, int bits=0);}
\begin{description}
\cvarg{srcType}{The source image type}
\cvarg{dstType}{The destination image type; must have as many channels as \texttt{srcType}}
\cvarg{kernel}{The 2D array of filter coefficients}
\cvarg{anchor}{The anchor point within the kernel; special value \texttt{Point(-1,-1)} means that the anchor is at the kernel center}
\cvarg{delta}{The value added to the filtered results before storing them}
\cvarg{bits}{When the kernel is an integer matrix representing fixed-point filter coefficients,
             the parameter specifies the number of the fractional bits}
\cvarg{rowBorderType, columnBorderType}{The pixel extrapolation methods in the horizontal and the vertical directions; see \cvCppCross{borderInterpolate}}
\cvarg{borderValue}{Used in case of constant border}
\end{description}

The function returns pointer to 2D linear filter for the specified kernel, the source array type and the destination array type. The function is a higher-level function that calls \texttt{getLinearFilter} and passes the retrieved 2D filter to \cvCppCross{FilterEngine} constructor.

See also: \cvCppCross{createSeparableLinearFilter}, \cvCppCross{FilterEngine}, \cvCppCross{filter2D}

\cvCppFunc{createMorphologyFilter}
Creates engine for non-separable morphological operations

\cvdefCpp{Ptr<FilterEngine> createMorphologyFilter(int op, int type,\par
    const Mat\& element, Point anchor=Point(-1,-1),\par
    int rowBorderType=BORDER\_CONSTANT,\par
    int columnBorderType=-1,\par
    const Scalar\& borderValue=morphologyDefaultBorderValue());\newline
Ptr<BaseFilter> getMorphologyFilter(int op, int type, const Mat\& element,\par
                                    Point anchor=Point(-1,-1));\newline
Ptr<BaseRowFilter> getMorphologyRowFilter(int op, int type,\par
                                          int esize, int anchor=-1);\newline
Ptr<BaseColumnFilter> getMorphologyColumnFilter(int op, int type,\par
                                                int esize, int anchor=-1);\newline
static inline Scalar morphologyDefaultBorderValue()\par
{ return Scalar::all(DBL\_MAX); }}
\begin{description}
\cvarg{op}{The morphology operation id, \texttt{MORPH\_ERODE} or \texttt{MORPH\_DILATE}}
\cvarg{type}{The input/output image type}
\cvarg{element}{The 2D 8-bit structuring element for the morphological operation. Non-zero elements indicate the pixels that belong to the element}
\cvarg{esize}{The horizontal or vertical structuring element size for separable morphological operations}
\cvarg{anchor}{The anchor position within the structuring element; negative values mean that the anchor is at the center}
\cvarg{rowBorderType, columnBorderType}{The pixel extrapolation methods in the horizontal and the vertical directions; see \cvCppCross{borderInterpolate}}
\cvarg{borderValue}{The border value in case of a constant border. The default value,\\ \texttt{morphologyDefaultBorderValue}, has the special meaning. It is transformed $+\inf$ for the erosion and to $-\inf$ for the dilation, which means that the minimum (maximum) is effectively computed only over the pixels that are inside the image.}
\end{description}

The functions construct primitive morphological filtering operations or a filter engine based on them. Normally it's enough to use \cvCppCross{createMorphologyFilter} or even higher-level \cvCppCross{erode}, \cvCppCross{dilate} or \cvCppCross{morphologyEx}, Note, that \cvCppCross{createMorphologyFilter} analyses the structuring element shape and builds a separable morphological filter engine when the structuring element is square.

See also: \cvCppCross{erode}, \cvCppCross{dilate}, \cvCppCross{morphologyEx}, \cvCppCross{FilterEngine}

\cvCppFunc{createSeparableLinearFilter}
Creates engine for separable linear filter

\cvdefCpp{Ptr<FilterEngine> createSeparableLinearFilter(int srcType, int dstType,\par
                         const Mat\& rowKernel, const Mat\& columnKernel,\par
                         Point anchor=Point(-1,-1), double delta=0,\par
                         int rowBorderType=BORDER\_DEFAULT,\par
                         int columnBorderType=-1,\par
                         const Scalar\& borderValue=Scalar());\newline
Ptr<BaseColumnFilter> getLinearColumnFilter(int bufType, int dstType,\par
                         const Mat\& columnKernel, int anchor,\par
                         int symmetryType, double delta=0,\par
                         int bits=0);\newline
Ptr<BaseRowFilter> getLinearRowFilter(int srcType, int bufType,\par
                         const Mat\& rowKernel, int anchor,\par
                         int symmetryType);}
\begin{description}
\cvarg{srcType}{The source array type}
\cvarg{dstType}{The destination image type; must have as many channels as \texttt{srcType}}
\cvarg{bufType}{The inermediate buffer type; must have as many channels as \texttt{srcType}}
\cvarg{rowKernel}{The coefficients for filtering each row}
\cvarg{columnKernel}{The coefficients for filtering each column}
\cvarg{anchor}{The anchor position within the kernel; negative values mean that anchor is positioned at the aperture center}
\cvarg{delta}{The value added to the filtered results before storing them}
\cvarg{bits}{When the kernel is an integer matrix representing fixed-point filter coefficients,
             the parameter specifies the number of the fractional bits}
\cvarg{rowBorderType, columnBorderType}{The pixel extrapolation methods in the horizontal and the vertical directions; see \cvCppCross{borderInterpolate}}
\cvarg{borderValue}{Used in case of a constant border}
\cvarg{symmetryType}{The type of each of the row and column kernel; see \cvCppCross{getKernelType}.}
\end{description}

The functions construct primitive separable linear filtering operations or a filter engine based on them. Normally it's enough to use \cvCppCross{createSeparableLinearFilter} or even higher-level \cvCppCross{sepFilter2D}. The function \cvCppCross{createMorphologyFilter} is smart enough to figure out the \texttt{symmetryType} for each of the two kernels, the intermediate \texttt{bufType}, and, if the filtering can be done in integer arithmetics, the number of \texttt{bits} to encode the filter coefficients. If it does not work for you, it's possible to call \texttt{getLinearColumnFilter}, \texttt{getLinearRowFilter} directly and then pass them to \cvCppCross{FilterEngine} constructor.

See also: \cvCppCross{sepFilter2D}, \cvCppCross{createLinearFilter}, \cvCppCross{FilterEngine}, \cvCppCross{getKernelType}


\cvCppFunc{dilate}
Dilates an image by using a specific structuring element.

\cvdefCpp{void dilate( const Mat\& src, Mat\& dst, const Mat\& element,\par
             Point anchor=Point(-1,-1), int iterations=1,\par
             int borderType=BORDER\_CONSTANT,\par
             const Scalar\& borderValue=morphologyDefaultBorderValue() );}
\begin{description}
\cvarg{src}{The source image}
\cvarg{dst}{The destination image. It will have the same size and the same type as \texttt{src}}
\cvarg{element}{The structuring element used for dilation. If \texttt{element=Mat()}, a $3\times 3$ rectangular structuring element is used}
\cvarg{anchor}{Position of the anchor within the element. The default value $(-1, -1)$ means that the anchor is at the element center}
\cvarg{iterations}{The number of times dilation is applied}
\cvarg{borderType}{The pixel extrapolation method; see \cvCppCross{borderInterpolate}}
\cvarg{borderValue}{The border value in case of a constant border. The default value has a special meaning, see \cvCppCross{createMorphologyFilter}}
\end{description}

The function dilates the source image using the specified structuring element that determines the shape of a pixel neighborhood over which the maximum is taken:

\[
\texttt{dst}(x,y) = \max_{(x',y'): \, \texttt{element}(x',y')\ne0}\texttt{src}(x+x',y+y')
\]

The function supports the in-place mode. Dilation can be applied several (\texttt{iterations}) times. In the case of multi-channel images each channel is processed independently.

See also: \cvCppCross{erode}, \cvCppCross{morphologyEx}, \cvCppCross{createMorphologyFilter}

\cvCppFunc{erode}
Erodes an image by using a specific structuring element.

\cvdefCpp{void erode( const Mat\& src, Mat\& dst, const Mat\& element,\par
            Point anchor=Point(-1,-1), int iterations=1,\par
            int borderType=BORDER\_CONSTANT,\par
            const Scalar\& borderValue=morphologyDefaultBorderValue() );}
\begin{description}
\cvarg{src}{The source image}
\cvarg{dst}{The destination image. It will have the same size and the same type as \texttt{src}}
\cvarg{element}{The structuring element used for dilation. If \texttt{element=Mat()}, a $3\times 3$ rectangular structuring element is used}
\cvarg{anchor}{Position of the anchor within the element. The default value $(-1, -1)$ means that the anchor is at the element center}
\cvarg{iterations}{The number of times erosion is applied}
\cvarg{borderType}{The pixel extrapolation method; see \cvCppCross{borderInterpolate}}
\cvarg{borderValue}{The border value in case of a constant border. The default value has a special meaning, see \cvCppCross{createMorphoogyFilter}}
\end{description}

The function erodes the source image using the specified structuring element that determines the shape of a pixel neighborhood over which the minimum is taken:

\[
\texttt{dst}(x,y) = \min_{(x',y'): \, \texttt{element}(x',y')\ne0}\texttt{src}(x+x',y+y')
\]

The function supports the in-place mode. Erosion can be applied several (\texttt{iterations}) times. In the case of multi-channel images each channel is processed independently.

See also: \cvCppCross{dilate}, \cvCppCross{morphologyEx}, \cvCppCross{createMorphologyFilter}

\cvCppFunc{filter2D}
Convolves an image with the kernel

\cvdefCpp{void filter2D( const Mat\& src, Mat\& dst, int ddepth,\par
               const Mat\& kernel, Point anchor=Point(-1,-1),\par
               double delta=0, int borderType=BORDER\_DEFAULT );}
\begin{description}
\cvarg{src}{The source image}
\cvarg{dst}{The destination image. It will have the same size and the same number of channels as \texttt{src}}
\cvarg{ddepth}{The desired depth of the destination image. If it is negative, it will be the same as \texttt{src.depth()}}
\cvarg{kernel}{Convolution kernel (or rather a correlation kernel), a single-channel floating point matrix. If you want to apply different kernels to different channels, split the image into separate color planes using \cvCppCross{split} and process them individually}
\cvarg{anchor}{The anchor of the kernel that indicates the relative position of a filtered point within the kernel. The anchor should lie within the kernel. The special default value (-1,-1) means that the anchor is at the kernel center}
\cvarg{delta}{The optional value added to the filtered pixels before storing them in \texttt{dst}}
\cvarg{borderType}{The pixel extrapolation method; see \cvCppCross{borderInterpolate}}
\end{description}

The function applies an arbitrary linear filter to the image. In-place operation is supported. When the aperture is partially outside the image, the function interpolates outlier pixel values according to the specified border mode.

The function does actually computes correlation, not the convolution:

\[
\texttt{dst}(x,y) = \sum_{\stackrel{0\leq x' < \texttt{kernel.cols},}{0\leq y' < \texttt{kernel.rows}}} \texttt{kernel}(x',y')*\texttt{src}(x+x'-\texttt{anchor.x},y+y'-\texttt{anchor.y})
\]

That is, the kernel is not mirrored around the anchor point. If you need a real convolution, flip the kernel using \cvCppCross{flip} and set the new anchor to \texttt{(kernel.cols - anchor.x - 1, kernel.rows - anchor.y - 1)}.

The function uses \hyperref[dft]{DFT}-based algorithm in case of sufficiently large kernels (~$11\times11$) and the direct algorithm (that uses the engine retrieved by \cvCppCross{createLinearFilter}) for small kernels.

See also: \cvCppCross{sepFilter2D}, \cvCppCross{createLinearFilter}, \cvCppCross{dft}, \cvCppCross{matchTemplate}

\cvCppFunc{GaussianBlur}
Smoothes image using a Gaussian filter

\cvdefCpp{void GaussianBlur( const Mat\& src, Mat\& dst, Size ksize,\par
                   double sigmaX, double sigmaY=0,\par
                   int borderType=BORDER\_DEFAULT );}
\begin{description}
\cvarg{src}{The source image}
\cvarg{dst}{The destination image; will have the same size and the same type as \texttt{src}}
\cvarg{ksize}{The Gaussian kernel size; \texttt{ksize.width} and \texttt{ksize.height} can differ, but they both must be positive and odd. Or, they can be zero's, then they are computed from \texttt{sigma*}}
\cvarg{sigmaX, sigmaY}{The Gaussian kernel standard deviations in X and Y direction. If \texttt{sigmaY} is zero, it is set to be equal to \texttt{sigmaX}. If they are both zeros, they are computed from \texttt{ksize.width} and \texttt{ksize.height}, respectively, see \cvCppCross{getGaussianKernel}. To fully control the result regardless of possible future modification of all this semantics, it is recommended to specify all of \texttt{ksize}, \texttt{sigmaX} and \texttt{sigmaY}}
\cvarg{borderType}{The pixel extrapolation method; see \cvCppCross{borderInterpolate}}
\end{description}

The function convolves the source image with the specified Gaussian kernel. In-place filtering is supported.

See also: \cvCppCross{sepFilter2D}, \cvCppCross{filter2D}, \cvCppCross{blur}, \cvCppCross{boxFilter}, \cvCppCross{bilateralFilter}, \cvCppCross{medianBlur}

\cvCppFunc{getDerivKernels}
Returns filter coefficients for computing spatial image derivatives

\cvdefCpp{void getDerivKernels( Mat\& kx, Mat\& ky, int dx, int dy, int ksize,\par
                      bool normalize=false, int ktype=CV\_32F );}
\begin{description}
\cvarg{kx}{The output matrix of row filter coefficients; will have type \texttt{ktype}}
\cvarg{ky}{The output matrix of column filter coefficients; will have type \texttt{ktype}}
\cvarg{dx}{The derivative order in respect with x}
\cvarg{dy}{The derivative order in respect with y}
\cvarg{ksize}{The aperture size. It can be \texttt{CV\_SCHARR}, 1, 3, 5 or 7}
\cvarg{normalize}{Indicates, whether to normalize (scale down) the filter coefficients or not. In theory the coefficients should have the denominator $=2^{ksize*2-dx-dy-2}$. If you are going to filter floating-point images, you will likely want to use the normalized kernels. But if you compute derivatives of a 8-bit image, store the results in 16-bit image and wish to preserve all the fractional bits, you may want to set \texttt{normalize=false}.}
\cvarg{ktype}{The type of filter coefficients. It can be \texttt{CV\_32f} or \texttt{CV\_64F}}
\end{description}

The function computes and returns the filter coefficients for spatial image derivatives. When \texttt{ksize=CV\_SCHARR}, the Scharr $3 \times 3$ kernels are generated, see \cvCppCross{Scharr}. Otherwise, Sobel kernels are generated, see \cvCppCross{Sobel}. The filters are normally passed to \cvCppCross{sepFilter2D} or to \cvCppCross{createSeparableLinearFilter}.

\cvCppFunc{getGaussianKernel}
Returns Gaussian filter coefficients

\cvdefCpp{Mat getGaussianKernel( int ksize, double sigma, int ktype=CV\_64F );}
\begin{description}
\cvarg{ksize}{The aperture size. It should be odd ($\texttt{ksize} \mod 2 = 1$) and positive.}
\cvarg{sigma}{The Gaussian standard deviation. If it is non-positive, it is computed from \texttt{ksize} as \\
\texttt{sigma = 0.3*(ksize/2 - 1) + 0.8}}
\cvarg{ktype}{The type of filter coefficients. It can be \texttt{CV\_32f} or \texttt{CV\_64F}}
\end{description}

The function computes and returns the $\texttt{ksize} \times 1$ matrix of Gaussian filter coefficients:

\[G_i=\alpha*e^{-(i-(\texttt{ksize}-1)/2)^2/(2*\texttt{sigma})^2},\]
 
where $i=0..\texttt{ksize}-1$ and $\alpha$ is the scale factor chosen so that $\sum_i G_i=1$

Two of such generated kernels can be passed to \cvCppCross{sepFilter2D} or to \cvCppCross{createSeparableLinearFilter} that will automatically detect that these are smoothing kernels and handle them accordingly. Also you may use the higher-level \cvCppCross{GaussianBlur}.

See also: \cvCppCross{sepFilter2D}, \cvCppCross{createSeparableLinearFilter}, \cvCppCross{getDerivKernels}, \cvCppCross{getStructuringElement}, \cvCppCross{GaussianBlur}.

\cvCppFunc{getKernelType}
Returns the kernel type

\cvdefCpp{int getKernelType(const Mat\& kernel, Point anchor);}

\begin{description}
\cvarg{kernel}{1D array of the kernel coefficients to analyze}
\cvarg{anchor}{The anchor position within the kernel}
\end{description}

The function analyzes the kernel coefficients and returns the corresponding kernel type:
\begin{description}
    \cvarg{KERNEL\_GENERAL}{Generic kernel - when there is no any type of symmetry or other properties}
    \cvarg{KERNEL\_SYMMETRICAL}{The kernel is symmetrical: $\texttt{kernel}_i == \texttt{kernel}_{ksize-i-1}$ and the anchor is at the center}
    \cvarg{KERNEL\_ASYMMETRICAL}{The kernel is asymmetrical: $\texttt{kernel}_i == -\texttt{kernel}_{ksize-i-1}$ and the anchor is at the center}
    \cvarg{KERNEL\_SMOOTH}{All the kernel elements are non-negative and sum to 1. E.g. the Gaussian kernel is both smooth kernel and symmetrical, so the function will return \texttt{KERNEL\_SMOOTH | KERNEL\_SYMMETRICAL}}
    \cvarg{KERNEL\_INTEGER}{Al the kernel coefficients are integer numbers. This flag can be combined with \texttt{KERNEL\_SYMMETRICAL} or \texttt{KERNEL\_ASYMMETRICAL}}
\end{description}

\cvCppFunc{getStructuringElement}
Returns the structuring element of the specified size and shape for morphological operations

\cvdefCpp{Mat getStructuringElement(int shape, Size esize,\par Point anchor=Point(-1,-1));}

\begin{description}
\cvarg{shape}{The element shape, one of:}
    \begin{itemize}
        \item \texttt{MORPH\_RECT} - rectangular structuring element
            \[E_{ij}=1\]

        \item \texttt{MORPH\_ELLIPSE} - elliptic structuring element, i.e. a filled ellipse inscribed into the rectangle
            \texttt{Rect(0, 0, esize.width, 0.esize.height)}

        \item \texttt{MORPH\_CROSS} - cross-shaped structuring element:
            \[
            E_{ij} = \fork{1}{if i=\texttt{anchor.y} or j=\texttt{anchor.x}}{0}{otherwise}
            \]
    \end{itemize}
\cvarg{esize}{Size of the structuring element}
\cvarg{anchor}{The anchor position within the element. The default value $(-1, -1)$ means that the anchor is at the center. Note that only the cross-shaped element's shape depends on the anchor position; in other cases the anchor just regulates by how much the result of the morphological operation is shifted}
\end{description}

The function constructs and returns the structuring element that can be then passed to \cvCppCross{createMorphologyFilter}, \cvCppCross{erode}, \cvCppCross{dilate} or \cvCppCross{morphologyEx}. But also you can construct an arbitrary binary mask yourself and use it as the structuring element.  

\cvCppFunc{medianBlur}
Smoothes image using median filter

\cvdefCpp{void medianBlur( const Mat\& src, Mat\& dst, int ksize );}
\begin{description}
\cvarg{src}{The source 1-, 3- or 4-channel image. When \texttt{ksize} is 3 or 5, the image depth should be \texttt{CV\_8U}, \texttt{CV\_16U} or \texttt{CV\_32F}. For larger aperture sizes it can only be \texttt{CV\_8U}}
\cvarg{dst}{The destination array; will have the same size and the same type as \texttt{src}}
\cvarg{ksize}{The aperture linear size. It must be odd and more than 1, i.e. 3, 5, 7 ...}
\end{description}

The function smoothes image using the median filter with $\texttt{ksize} \times \texttt{ksize}$ aperture. Each channel of a multi-channel image is processed independently. In-place operation is supported.

See also: \cvCppCross{bilateralFilter}, \cvCppCross{blur}, \cvCppCross{boxFilter}, \cvCppCross{GaussianBlur}

\cvCppFunc{morphologyEx}
Performs advanced morphological transformations

\cvdefCpp{void morphologyEx( const Mat\& src, Mat\& dst, \par
                   int op, const Mat\& element,\par
                   Point anchor=Point(-1,-1), int iterations=1,\par
                   int borderType=BORDER\_CONSTANT,\par
                   const Scalar\& borderValue=morphologyDefaultBorderValue() );}
\begin{description}
\cvarg{src}{Source image}
\cvarg{dst}{Destination image. It will have the same size and the same type as \texttt{src}}
\cvarg{element}{Structuring element}
\cvarg{op}{Type of morphological operation, one of the following:
\begin{description}
\cvarg{MORPH\_OPEN}{opening}
\cvarg{MORPH\_CLOSE}{closing}
\cvarg{MORPH\_GRADIENT}{morphological gradient}
\cvarg{MORPH\_TOPHAT}{"top hat"}
\cvarg{MORPH\_BLACKHAT}{"black hat"}
\end{description}}
\cvarg{iterations}{Number of times erosion and dilation are applied}
\cvarg{borderType}{The pixel extrapolation method; see \cvCppCross{borderInterpolate}}
\cvarg{borderValue}{The border value in case of a constant border. The default value has a special meaning, see \cvCppCross{createMorphoogyFilter}}
\end{description}

The function can perform advanced morphological transformations using erosion and dilation as basic operations.

Opening:

\[
\texttt{dst}=\mathrm{open}(\texttt{src},\texttt{element})=\mathrm{dilate}(\mathrm{erode}(\texttt{src},\texttt{element}))
\]

Closing:

\[
\texttt{dst}=\mathrm{close}(\texttt{src},\texttt{element})=\mathrm{erode}(\mathrm{dilate}(\texttt{src},\texttt{element}))
\]

Morphological gradient:

\[
\texttt{dst}=\mathrm{morph\_grad}(\texttt{src},\texttt{element})=\mathrm{dilate}(\texttt{src},\texttt{element})-\mathrm{erode}(\texttt{src},\texttt{element})
\]

"Top hat":

\[
\texttt{dst}=\mathrm{tophat}(\texttt{src},\texttt{element})=\texttt{src}-\mathrm{open}(\texttt{src},\texttt{element})
\]

"Black hat":

\[
\texttt{dst}=\mathrm{blackhat}(\texttt{src},\texttt{element})=\mathrm{close}(\texttt{src},\texttt{element})-\texttt{src}
\]

Any of the operations can be done in-place.

See also: \cvCppCross{dilate}, \cvCppCross{erode}, \cvCppCross{createMorphologyFilter}

\cvCppFunc{Laplacian}
Calculates the Laplacian of an image

\cvdefCpp{void Laplacian( const Mat\& src, Mat\& dst, int ddepth,\par
               int ksize=1, double scale=1, double delta=0,\par
               int borderType=BORDER\_DEFAULT );}
\begin{description}
\cvarg{src}{Source image}
\cvarg{dst}{Destination image; will have the same size and the same number of channels as \texttt{src}}
\cvarg{ddepth}{The desired depth of the destination image}
\cvarg{ksize}{The aperture size used to compute the second-derivative filters, see \cvCppCross{getDerivKernels}. It must be positive and odd}
\cvarg{scale}{The optional scale factor for the computed Laplacian values (by default, no scaling is applied, see \cvCppCross{getDerivKernels})}
\cvarg{delta}{The optional delta value, added to the results prior to storing them in \texttt{dst}}
\cvarg{borderType}{The pixel extrapolation method, see \cvCppCross{borderInterpolate}}
\end{description}

The function calculates the Laplacian of the source image by adding up the second x and y derivatives calculated using the Sobel operator:

\[
\texttt{dst} = \Delta \texttt{src} = \frac{\partial^2 \texttt{src}}{\partial x^2} + \frac{\partial^2 \texttt{src}}{\partial y^2}
\]


This is done when \texttt{ksize > 1}. When \texttt{ksize == 1}, the Laplacian is computed by filtering the image with the following $3 \times 3$ aperture:

\[ \vecthreethree {0}{1}{0}{1}{-4}{1}{0}{1}{0} \]

See also: \cvCppCross{Sobel}, \cvCppCross{Scharr} 

\cvCppFunc{pyrDown}
Smoothes an image and downsamples it.

\cvdefCpp{void pyrDown( const Mat\& src, Mat\& dst, const Size\& dstsize=Size());}
\begin{description}
\cvarg{src}{The source image}
\cvarg{dst}{The destination image. It will have the specified size and the same type as \texttt{src}}
\cvarg{dstsize}{Size of the destination image. By default it is computed as \texttt{Size((src.cols+1)/2, (src.rows+1)/2)}. But in any case the following conditions should be satisfied:
\[
\begin{array}{l}
|\texttt{dstsize.width}*2-src.cols|\leq 2 \\
|\texttt{dstsize.height}*2-src.rows|\leq 2
\end{array}
\]
}
\end{description}

The function performs the downsampling step of the Gaussian pyramid construction. First it convolves the source image with the kernel:

\[\frac{1}{16}
\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}
\]    

and then downsamples the image by rejecting even rows and columns.

\cvCppFunc{pyrUp}
Upsamples an image and then smoothes it

\cvdefCpp{void pyrUp( const Mat\& src, Mat\& dst, const Size\& dstsize=Size());}
\begin{description}
\cvarg{src}{The source image}
\cvarg{dst}{The destination image. It will have the specified size and the same type as \texttt{src}}
\cvarg{dstsize}{Size of the destination image. By default it is computed as \texttt{Size(src.cols*2, (src.rows*2)}. But in any case the following conditions should be satisfied:
\[
\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}
\]
}
\end{description}

The function performs the upsampling step of the Gaussian pyramid construction (it can actually be used to construct the Laplacian pyramid). First it upsamples the source image by injecting even zero rows and columns and then convolves the result with the same kernel as in \cvCppCross{pyrDown}, multiplied by 4.

\cvCppFunc{sepFilter2D}
Applies separable linear filter to an image

\cvdefCpp{void sepFilter2D( const Mat\& src, Mat\& dst, int ddepth,\par
                  const Mat\& rowKernel, const Mat\& columnKernel,\par
                  Point anchor=Point(-1,-1),\par
                  double delta=0, int borderType=BORDER\_DEFAULT );}
\begin{description}
\cvarg{src}{The source image}
\cvarg{dst}{The destination image; will have the same size and the same number of channels as \texttt{src}}
\cvarg{ddepth}{The destination image depth}
\cvarg{rowKernel}{The coefficients for filtering each row}
\cvarg{columnKernel}{The coefficients for filtering each column}
\cvarg{anchor}{The anchor position within the kernel; The default value $(-1, 1)$ means that the anchor is at the kernel center}
\cvarg{delta}{The value added to the filtered results before storing them}
\cvarg{borderType}{The pixel extrapolation method; see \cvCppCross{borderInterpolate}}
\end{description}

The function applies a separable linear filter to the image. That is, first, every row of \texttt{src} is filtered with 1D kernel \texttt{rowKernel}. Then, every column of the result is filtered with 1D kernel \texttt{columnKernel} and the final result shifted by \texttt{delta} is stored in \texttt{dst}.

See also: \cvCppCross{createSeparableLinearFilter}, \cvCppCross{filter2D}, \cvCppCross{Sobel}, \cvCppCross{GaussianBlur}, \cvCppCross{boxFilter}, \cvCppCross{blur}.

\cvCppFunc{Sobel}
Calculates the first, second, third or mixed image derivatives using an extended Sobel operator

\cvdefCpp{void Sobel( const Mat\& src, Mat\& dst, int ddepth,\par
            int xorder, int yorder, int ksize=3,\par
            double scale=1, double delta=0,\par
            int borderType=BORDER\_DEFAULT );}
\begin{description}
\cvarg{src}{The source image}
\cvarg{dst}{The destination image; will have the same size and the same number of channels as \texttt{src}}
\cvarg{ddepth}{The destination image depth}
\cvarg{xorder}{Order of the derivative x}
\cvarg{yorder}{Order of the derivative y}
\cvarg{ksize}{Size of the extended Sobel kernel, must be 1, 3, 5 or 7}
\cvarg{scale}{The optional scale factor for the computed derivative values (by default, no scaling is applied, see \cvCppCross{getDerivKernels})}
\cvarg{delta}{The optional delta value, added to the results prior to storing them in \texttt{dst}}
\cvarg{borderType}{The pixel extrapolation method, see \cvCppCross{borderInterpolate}}
\end{description}

In all cases except 1, an $\texttt{ksize} \times
\texttt{ksize}$ separable kernel will be used to calculate the
derivative. When $\texttt{ksize = 1}$, a $ 3 \times 1$ or $ 1 \times 3$
kernel will be used (i.e. no Gaussian smoothing is done). \texttt{ksize = 1} can only be used for the first or the second x- or y- derivatives.

There is also the special value \texttt{ksize = CV\_SCHARR} (-1) that corresponds to a $3\times3$ Scharr
filter that may give more accurate results than a $3\times3$ Sobel. The Scharr
aperture is

\[ \vecthreethree
{-3}{0}{3}
{-10}{0}{10}
{-3}{0}{3}
\]

for the x-derivative or transposed for the y-derivative.

The function calculates the image derivative by convolving the image with the appropriate kernel:

\[
\texttt{dst} = \frac{\partial^{xorder+yorder} \texttt{src}}{\partial x^{xorder} \partial y^{yorder}}
\]

The Sobel operators combine Gaussian smoothing and differentiation,
so the result is more or less resistant to the noise. Most often,
the function is called with (\texttt{xorder} = 1, \texttt{yorder} = 0,
\texttt{ksize} = 3) or (\texttt{xorder} = 0, \texttt{yorder} = 1,
\texttt{ksize} = 3) to calculate the first x- or y- image
derivative. The first case corresponds to a kernel of:

\[ \vecthreethree
{-1}{0}{1}
{-2}{0}{2}
{-1}{0}{1}
\]

and the second one corresponds to a kernel of:
\[ \vecthreethree
{-1}{-2}{-1}
{0}{0}{0}
{1}{2}{1}
\]

See also: \cvCppCross{Scharr}, \cvCppCross{Lapacian}, \cvCppCross{sepFilter2D}, \cvCppCross{filter2D}, \cvCppCross{GaussianBlur}

\cvCppFunc{Scharr}
Calculates the first x- or y- image derivative using Scharr operator

\cvdefCpp{void Scharr( const Mat\& src, Mat\& dst, int ddepth,\par
            int xorder, int yorder,\par
            double scale=1, double delta=0,\par
            int borderType=BORDER\_DEFAULT );}
\begin{description}
\cvarg{src}{The source image}
\cvarg{dst}{The destination image; will have the same size and the same number of channels as \texttt{src}}
\cvarg{ddepth}{The destination image depth}
\cvarg{xorder}{Order of the derivative x}
\cvarg{yorder}{Order of the derivative y}
\cvarg{scale}{The optional scale factor for the computed derivative values (by default, no scaling is applied, see \cvCppCross{getDerivKernels})}
\cvarg{delta}{The optional delta value, added to the results prior to storing them in \texttt{dst}}
\cvarg{borderType}{The pixel extrapolation method, see \cvCppCross{borderInterpolate}}
\end{description}

The function computes the first x- or y- spatial image derivative using Scharr operator. The call
\[\texttt{Scharr(src, dst, ddepth, xorder, yorder, scale, delta, borderType)}\]
is equivalent to
\[\texttt{Sobel(src, dst, ddepth, xorder, yorder, CV\_SCHARR, scale, delta, borderType)}.\]

\fi
