Fully working code of canny edge detection is given at the end. For explanation read complete article thanks.
Edges in an image are those points which show sudden change of intensity and with help of derivatives(1st order, 2nd order) we can find this change in an image.
Canny Edge Detector:
Canny edge detector is a complex but accurate detector as compared to Marr-Hilderth detector. And it is based on these 3 following objectives:
1. Low Error Rate:
Its says that all edges should be found and these detected edges should be as much close to true edges as possible
2. Edge points should be well localized:
It states that the edges located should be as close to true edges as possible. In other words, the distance between a point detected or marked as an edge by canny detector and the centre of the true edge should be minimum.
3. Single Edge Point Response:
The detector must output one edge point for each true edge point.
The Canny Edge Detector: Algorithm
Let f(x,y) denote the input image and G(x,y) denote the Gaussian function:
G(x,y)=e^-(x^2 + y^2/2 a^2)
We form a smoothed image fs(x,y) by convolving G and f:
fs(x,y) = G(x,y) * f(x,y)
Compute the gradient magnitude and direction(angle):
M(x,y) =√gx^2 + gy^2
where gx = ∂fs/∂x and gy=∂fs/∂y
The gradient M(x,y) typically contains wide range around local maxima. Next step is to thin those ridges.
Let d1,d2,d3, and d4 denote the four basic edge directions for a 3×3 region: horizontal, -45 degrees, vertical, +45 degrees, respectively.
1. Find the direction dk that is closest to a(x,y)
2. If the value of M(x,y) is less than at least one of its two neighbours along dk, let gn(x,y)=0(suppression);
otherwise, let gn(x,y)=M(x,y)
Figure below shows this
Final operation is to threshold gn(x,y) to reduce false edge points.
Mathematically its done like this:
gnh(x,y) = gn(x,y)>=Th
gnl(x,y) = gn(x,y)>=Tl
gnl(x,y) = gnl(x,y) – gnh(x,y)
Depending on the value of Th, the edges in gnh(x,y) typically have gaps. Longer edges are formed using the following procedure:
(a). Locate the next unvisited edge pixel p, in gnh(x,y)
(b). Mark as valid edge pixel all the weak pixels in gnl(x,y) that are connected to p using 8-connectivity.
(c). If all non-zero pixel in gnh(x,y) that were not marked as valid edge pixels .
The Canny Edge Detection: Summary
1. Smooth the input image with a Gaussian filter
2. Compute the gradient magnitude and angle images
3. Apply non-maxima suppression to the gradient magnitude image
4. Use double thresholding and connectivity analysis to detect and link edges
Click this link to download m-file of Canny Edge Detector. For any queries feel free to comment. Thanks!