OpenCV
4.1.0
Open Source Computer Vision
|
Prev Tutorial: Laplace Operator
Next Tutorial: Hough Line Transform
In this tutorial you will learn how to:
The Canny Edge detectorCanny86 was developed by John F. Canny in 1986. Also known to many as the optimal detector, the Canny algorithm aims to satisfy three main criteria:
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}\]
Find the intensity gradient of the image. For this, we follow a procedure analogous to Sobel:
\[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}\]
\[\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)Hysteresis: The final step. Canny does use two thresholds (upper and lower):
Canny recommended a upper:lower ratio between 2:1 and 3:1.
Create some needed variables:
Note the following:
Create a Trackbar for the user to enter the lower threshold for our Canny detector:
Observe the following:
Second, we apply the OpenCV function cv::Canny :
where the arguments are:
After compiling the code above, we can run it giving as argument the path to an image. For example, using as an input the following image:
Moving the slider, trying different threshold, we obtain the following result: