feature_detection.rst 25.9 KB

Feature Detection

Canny

Finds edges in an image using the [Canny86] algorithm.

The function finds edges in the input image image and marks them in the output map edges using the Canny algorithm. The smallest value between threshold1 and threshold2 is used for edge linking. The largest value is used to find initial segments of strong edges. See http://en.wikipedia.org/wiki/Canny_edge_detector

Note

  • An example on using the canny edge detector can be found at opencv_source_code/samples/cpp/edge.cpp
  • (Python) An example on using the canny edge detector can be found at opencv_source_code/samples/python/edge.py

cornerEigenValsAndVecs

Calculates eigenvalues and eigenvectors of image blocks for corner detection.

For every pixel p , the function cornerEigenValsAndVecs considers a blockSize \times blockSize neighborhood S(p) . It calculates the covariation matrix of derivatives over the neighborhood as:

M =  \begin{bmatrix} \sum _{S(p)}(dI/dx)^2 &  \sum _{S(p)}(dI/dx dI/dy)^2  \\ \sum _{S(p)}(dI/dx dI/dy)^2 &  \sum _{S(p)}(dI/dy)^2 \end{bmatrix}

where the derivatives are computed using the :ocv:func:`Sobel` operator.

After that, it finds eigenvectors and eigenvalues of M and stores them in the destination image as (\lambda_1, \lambda_2, x_1, y_1, x_2, y_2) where

  • \lambda_1, \lambda_2 are the non-sorted eigenvalues of M
  • x_1, y_1 are the eigenvectors corresponding to \lambda_1
  • x_2, y_2 are the eigenvectors corresponding to \lambda_2

The output of the function can be used for robust edge or corner detection.

Note

  • (Python) An example on how to use eigenvectors and eigenvalues to estimate image texture flow direction can be found at opencv_source_code/samples/python2/texture_flow.py

cornerHarris

Harris edge detector.

The function runs the Harris edge detector on the image. Similarly to :ocv:func:`cornerMinEigenVal` and :ocv:func:`cornerEigenValsAndVecs` , for each pixel (x, y) it calculates a 2\times2 gradient covariance matrix M^{(x,y)} over a \texttt{blockSize} \times \texttt{blockSize} neighborhood. Then, it computes the following characteristic:

\texttt{dst} (x,y) =  \mathrm{det} M^{(x,y)} - k  \cdot \left ( \mathrm{tr} M^{(x,y)} \right )^2

Corners in the image can be found as the local maxima of this response map.

cornerMinEigenVal

Calculates the minimal eigenvalue of gradient matrices for corner detection.

The function is similar to :ocv:func:`cornerEigenValsAndVecs` but it calculates and stores only the minimal eigenvalue of the covariance matrix of derivatives, that is, \min(\lambda_1, \lambda_2) in terms of the formulae in the :ocv:func:`cornerEigenValsAndVecs` description.

cornerSubPix

Refines the corner locations.

The function iterates to find the sub-pixel accurate location of corners or radial saddle points, as shown on the figure below.

pics/cornersubpix.png

Sub-pixel accurate corner locator is based on the observation that every vector from the center q to a point p located within a neighborhood of q is orthogonal to the image gradient at p subject to image and measurement noise. Consider the expression:

\epsilon _i = {DI_{p_i}}^T  \cdot (q - p_i)

where {DI_{p_i}} is an image gradient at one of the points p_i in a neighborhood of q . The value of q is to be found so that \epsilon_i is minimized. A system of equations may be set up with \epsilon_i set to zero:

\sum _i(DI_{p_i}  \cdot {DI_{p_i}}^T) -  \sum _i(DI_{p_i}  \cdot {DI_{p_i}}^T  \cdot p_i)

where the gradients are summed within a neighborhood ("search window") of q . Calling the first gradient term G and the second gradient term b gives:

q = G^{-1}  \cdot b

The algorithm sets the center of the neighborhood window at this new center q and then iterates until the center stays within a set threshold.

goodFeaturesToTrack

Determines strong corners on an image.

The function finds the most prominent corners in the image or in the specified image region, as described in [Shi94]:

  1. Function calculates the corner quality measure at every source image pixel using the :ocv:func:`cornerMinEigenVal` or :ocv:func:`cornerHarris` .
  2. Function performs a non-maximum suppression (the local maximums in 3 x 3 neighborhood are retained).
  3. The corners with the minimal eigenvalue less than \texttt{qualityLevel} \cdot \max_{x,y} qualityMeasureMap(x,y) are rejected.
  4. The remaining corners are sorted by the quality measure in the descending order.
  5. Function throws away each corner for which there is a stronger corner at a distance less than maxDistance.

The function can be used to initialize a point-based tracker of an object.

Note

If the function is called with different values A and B of the parameter qualityLevel , and A > {B}, the vector of returned corners with qualityLevel=A will be the prefix of the output vector with qualityLevel=B .

HoughCircles

Finds circles in a grayscale image using the Hough transform.

The function finds circles in a grayscale image using a modification of the Hough transform.

Example:

#include <cv.h>
#include <highgui.h>
#include <math.h>

using namespace cv;

int main(int argc, char** argv)
{
    Mat img, gray;
    if( argc != 2 && !(img=imread(argv[1], 1)).data)
        return -1;
    cvtColor(img, gray, CV_BGR2GRAY);
    // smooth it, otherwise a lot of false circles may be detected
    GaussianBlur( gray, gray, Size(9, 9), 2, 2 );
    vector<Vec3f> circles;
    HoughCircles(gray, circles, CV_HOUGH_GRADIENT,
                 2, gray->rows/4, 200, 100 );
    for( size_t i = 0; i < circles.size(); i++ )
    {
         Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));
         int radius = cvRound(circles[i][2]);
         // draw the circle center
         circle( img, center, 3, Scalar(0,255,0), -1, 8, 0 );
         // draw the circle outline
         circle( img, center, radius, Scalar(0,0,255), 3, 8, 0 );
    }
    namedWindow( "circles", 1 );
    imshow( "circles", img );
    return 0;
}

Note

Usually the function detects the centers of circles well. However, it may fail to find correct radii. You can assist to the function by specifying the radius range ( minRadius and maxRadius ) if you know it. Or, you may ignore the returned radius, use only the center, and find the correct radius using an additional procedure.

Note

  • An example using the Hough circle detector can be found at opencv_source_code/samples/cpp/houghcircles.cpp

HoughLines

Finds lines in a binary image using the standard Hough transform.

The function implements the standard or standard multi-scale Hough transform algorithm for line detection. See http://homepages.inf.ed.ac.uk/rbf/HIPR2/hough.htm for a good explanation of Hough transform. See also the example in :ocv:func:`HoughLinesP` description.

Note

  • An example using the Hough line detector can be found at opencv_source_code/samples/cpp/houghlines.cpp

HoughLinesP

Finds line segments in a binary image using the probabilistic Hough transform.

The function implements the probabilistic Hough transform algorithm for line detection, described in [Matas00]. See the line detection example below:

/* This is a standalone program. Pass an image name as the first parameter
of the program.  Switch between standard and probabilistic Hough transform
by changing "#if 1" to "#if 0" and back */
#include <cv.h>
#include <highgui.h>
#include <math.h>

using namespace cv;

int main(int argc, char** argv)
{
    Mat src, dst, color_dst;
    if( argc != 2 || !(src=imread(argv[1], 0)).data)
        return -1;

    Canny( src, dst, 50, 200, 3 );
    cvtColor( dst, color_dst, CV_GRAY2BGR );

#if 0
    vector<Vec2f> lines;
    HoughLines( dst, lines, 1, CV_PI/180, 100 );

    for( size_t i = 0; i < lines.size(); i++ )
    {
        float rho = lines[i][0];
        float theta = lines[i][1];
        double a = cos(theta), b = sin(theta);
        double x0 = a*rho, y0 = b*rho;
        Point pt1(cvRound(x0 + 1000*(-b)),
                  cvRound(y0 + 1000*(a)));
        Point pt2(cvRound(x0 - 1000*(-b)),
                  cvRound(y0 - 1000*(a)));
        line( color_dst, pt1, pt2, Scalar(0,0,255), 3, 8 );
    }
#else
    vector<Vec4i> lines;
    HoughLinesP( dst, lines, 1, CV_PI/180, 80, 30, 10 );
    for( size_t i = 0; i < lines.size(); i++ )
    {
        line( color_dst, Point(lines[i][0], lines[i][1]),
            Point(lines[i][2], lines[i][3]), Scalar(0,0,255), 3, 8 );
    }
#endif
    namedWindow( "Source", 1 );
    imshow( "Source", src );

    namedWindow( "Detected Lines", 1 );
    imshow( "Detected Lines", color_dst );

    waitKey(0);
    return 0;
}

This is a sample picture the function parameters have been tuned for:

pics/building.jpg

And this is the output of the above program in case of the probabilistic Hough transform:

pics/houghp.png

preCornerDetect

Calculates a feature map for corner detection.

The function calculates the complex spatial derivative-based function of the source image

\texttt{dst} = (D_x  \texttt{src} )^2  \cdot D_{yy}  \texttt{src} + (D_y  \texttt{src} )^2  \cdot D_{xx}  \texttt{src} - 2 D_x  \texttt{src} \cdot D_y  \texttt{src} \cdot D_{xy}  \texttt{src}

where D_x ,:math:D_y are the first image derivatives, D_{xx} ,:math:D_{yy} are the second image derivatives, and D_{xy} is the mixed derivative.

The corners can be found as local maximums of the functions, as shown below:

Mat corners, dilated_corners;
preCornerDetect(image, corners, 3);
// dilation with 3x3 rectangular structuring element
dilate(corners, dilated_corners, Mat(), 1);
Mat corner_mask = corners == dilated_corners;
[Canny86]
  1. Canny. A Computational Approach to Edge Detection, IEEE Trans. on Pattern Analysis and Machine Intelligence, 8(6), pp. 679-698 (1986).
[Matas00] Matas, J. and Galambos, C. and Kittler, J.V., Robust Detection of Lines Using the Progressive Probabilistic Hough Transform. CVIU 78 1, pp 119-137 (2000)
[Shi94]
  1. Shi and C. Tomasi. Good Features to Track. Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pages 593-600, June 1994.
[Yuen90] Yuen, H. K. and Princen, J. and Illingworth, J. and Kittler, J., Comparative study of Hough transform methods for circle finding. Image Vision Comput. 8 1, pp 71–77 (1990)