OpenCV  3.0.0-rc1
Open Source Computer Vision
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
Canny Edge Detector

Goal

In this tutorial you will learn how to:

Theory

The Canny Edge detector was developed by John F. Canny in 1986. Also known to many as the optimal detector, Canny algorithm aims to satisfy three main criteria:

Steps

  1. Filter out any noise. The Gaussian filter is used for this purpose. An example of a Gaussian kernel of \(size = 5\) that might be used is shown below:

    \[K = \dfrac{1}{159}\begin{bmatrix} 2 & 4 & 5 & 4 & 2 \\ 4 & 9 & 12 & 9 & 4 \\ 5 & 12 & 15 & 12 & 5 \\ 4 & 9 & 12 & 9 & 4 \\ 2 & 4 & 5 & 4 & 2 \end{bmatrix}\]

  2. Find the intensity gradient of the image. For this, we follow a procedure analogous to Sobel:
    1. Apply a pair of convolution masks (in \(x\) and \(y\) directions:

      \[G_{x} = \begin{bmatrix} -1 & 0 & +1 \\ -2 & 0 & +2 \\ -1 & 0 & +1 \end{bmatrix}\]

      \[G_{y} = \begin{bmatrix} -1 & -2 & -1 \\ 0 & 0 & 0 \\ +1 & +2 & +1 \end{bmatrix}\]

    2. Find the gradient strength and direction with:

      \[\begin{array}{l} G = \sqrt{ G_{x}^{2} + G_{y}^{2} } \\ \theta = \arctan(\dfrac{ G_{y} }{ G_{x} }) \end{array}\]

      The direction is rounded to one of four possible angles (namely 0, 45, 90 or 135)
  3. Non-maximum suppression is applied. This removes pixels that are not considered to be part of an edge. Hence, only thin lines (candidate edges) will remain.
  4. Hysteresis: The final step. Canny does use two thresholds (upper and lower):

    1. If a pixel gradient is higher than the upper threshold, the pixel is accepted as an edge
    2. If a pixel gradient value is below the lower threshold, then it is rejected.
    3. If the pixel gradient is between the two thresholds, then it will be accepted only if it is connected to a pixel that is above the upper threshold.

    Canny recommended a upper:lower ratio between 2:1 and 3:1.

  5. For more details, you can always consult your favorite Computer Vision book.

Code

  1. What does this program do?
    • Asks the user to enter a numerical value to set the lower threshold for our Canny Edge Detector (by means of a Trackbar)
    • Applies the Canny Detector and generates a mask (bright lines representing the edges on a black background).
    • Applies the mask obtained on the original image and display it in a window.
  2. The tutorial code's is shown lines below. You can also download it from here
    1 
    8 #include "opencv2/imgcodecs.hpp"
    10 #include <stdlib.h>
    11 #include <stdio.h>
    12 
    13 using namespace cv;
    14 
    16 
    17 Mat src, src_gray;
    18 Mat dst, detected_edges;
    19 
    20 int edgeThresh = 1;
    21 int lowThreshold;
    22 int const max_lowThreshold = 100;
    23 int ratio = 3;
    24 int kernel_size = 3;
    25 const char* window_name = "Edge Map";
    26 
    31 static void CannyThreshold(int, void*)
    32 {
    34  blur( src_gray, detected_edges, Size(3,3) );
    35 
    37  Canny( detected_edges, detected_edges, lowThreshold, lowThreshold*ratio, kernel_size );
    38 
    40  dst = Scalar::all(0);
    41 
    42  src.copyTo( dst, detected_edges);
    43  imshow( window_name, dst );
    44 }
    45 
    46 
    50 int main( int, char** argv )
    51 {
    53  src = imread( argv[1] );
    54 
    55  if( src.empty() )
    56  { return -1; }
    57 
    59  dst.create( src.size(), src.type() );
    60 
    62  cvtColor( src, src_gray, COLOR_BGR2GRAY );
    63 
    65  namedWindow( window_name, WINDOW_AUTOSIZE );
    66 
    68  createTrackbar( "Min Threshold:", window_name, &lowThreshold, max_lowThreshold, CannyThreshold );
    69 
    71  CannyThreshold(0, 0);
    72 
    74  waitKey(0);
    75 
    76  return 0;
    77 }
    void blur(InputArray src, OutputArray dst, Size ksize, Point anchor=Point(-1,-1), int borderType=BORDER_DEFAULT)
    Blurs an image using the normalized box filter.
    void cvtColor(InputArray src, OutputArray dst, int code, int dstCn=0)
    Converts an image from one color space to another.
    Mat imread(const String &filename, int flags=IMREAD_COLOR)
    Loads an image from a file.
    void imshow(const String &winname, InputArray mat)
    Displays an image in the specified window.
    int createTrackbar(const String &trackbarname, const String &winname, int *value, int count, TrackbarCallback onChange=0, void *userdata=0)
    Creates a trackbar and attaches it to the specified window.
    void namedWindow(const String &winname, int flags=WINDOW_AUTOSIZE)
    Creates a window.
    void Canny(InputArray image, OutputArray edges, double threshold1, double threshold2, int apertureSize=3, bool L2gradient=false)
    Finds edges in an image using the Canny algorithm .
    Size2i Size
    Definition: types.hpp:308
    Definition: highgui.hpp:138
    int main(int argc, const char *argv[])
    Definition: facerec_demo.cpp:67
    static Scalar_< double > all(doublev0)
    returns a scalar with all elements set to v0
    n-dimensional dense array class
    Definition: mat.hpp:726
    convert between RGB/BGR and grayscale, color conversions
    Definition: imgproc.hpp:511
    int waitKey(int delay=0)
    Waits for a pressed key.

Explanation

  1. Create some needed variables:
    Mat src, src_gray;
    Mat dst, detected_edges;
    int edgeThresh = 1;
    int lowThreshold;
    int const max_lowThreshold = 100;
    int ratio = 3;
    int kernel_size = 3;
    char* window_name = "Edge Map";
    Note the following:
    1. We establish a ratio of lower:upper threshold of 3:1 (with the variable ratio)
    2. We set the kernel size of \(3\) (for the Sobel operations to be performed internally by the Canny function)
    3. We set a maximum value for the lower Threshold of \(100\).
  2. Loads the source image:
    src = imread( argv[1] );
    if( !src.data )
    { return -1; }
  3. Create a matrix of the same type and size of src (to be dst)
    dst.create( src.size(), src.type() );
  4. Convert the image to grayscale (using the function cv::cvtColor :
    cvtColor( src, src_gray, COLOR_BGR2GRAY );
  5. Create a window to display the results
    namedWindow( window_name, WINDOW_AUTOSIZE );
  6. Create a Trackbar for the user to enter the lower threshold for our Canny detector:
    createTrackbar( "Min Threshold:", window_name, &lowThreshold, max_lowThreshold, CannyThreshold );
    Observe the following:
    1. The variable to be controlled by the Trackbar is lowThreshold with a limit of max_lowThreshold (which we set to 100 previously)
    2. Each time the Trackbar registers an action, the callback function CannyThreshold will be invoked.
  7. Let's check the CannyThreshold function, step by step:
    1. First, we blur the image with a filter of kernel size 3:
      blur( src_gray, detected_edges, Size(3,3) );
    2. Second, we apply the OpenCV function cv::Canny :
      Canny( detected_edges, detected_edges, lowThreshold, lowThreshold*ratio, kernel_size );
      where the arguments are:
      • detected_edges: Source image, grayscale
      • detected_edges: Output of the detector (can be the same as the input)
      • lowThreshold: The value entered by the user moving the Trackbar
      • highThreshold: Set in the program as three times the lower threshold (following Canny's recommendation)
      • kernel_size: We defined it to be 3 (the size of the Sobel kernel to be used internally)
  8. We fill a dst image with zeros (meaning the image is completely black).
    dst = Scalar::all(0);
  9. Finally, we will use the function cv::Mat::copyTo to map only the areas of the image that are identified as edges (on a black background).
    src.copyTo( dst, detected_edges);
    cv::Mat::copyTo copy the src image onto dst. However, it will only copy the pixels in the locations where they have non-zero values. Since the output of the Canny detector is the edge contours on a black background, the resulting dst will be black in all the area but the detected edges.
  10. We display our result:
    imshow( window_name, dst );

Result