1 | % CANNY - Canny edge detection |
---|
2 | % |
---|
3 | % Function to perform Canny edge detection. Code uses modifications as |
---|
4 | % suggested by Fleck (IEEE PAMI No. 3, Vol. 14. March 1992. pp 337-345) |
---|
5 | % |
---|
6 | % Usage: [gradient or] = canny(im, sigma) |
---|
7 | % |
---|
8 | % Arguments: im - image to be procesed |
---|
9 | % sigma - standard deviation of Gaussian smoothing filter |
---|
10 | % (typically 1) |
---|
11 | % |
---|
12 | % Returns: gradient - edge strength image (gradient amplitude) |
---|
13 | % or - orientation image (in degrees 0-180, positive |
---|
14 | % anti-clockwise) |
---|
15 | % |
---|
16 | % See also: NONMAXSUP, HYSTHRESH |
---|
17 | |
---|
18 | % Copyright (c) 1999-2003 Peter Kovesi |
---|
19 | % School of Computer Science & Software Engineering |
---|
20 | % The University of Western Australia |
---|
21 | % http://www.csse.uwa.edu.au/ |
---|
22 | % |
---|
23 | % Permission is hereby granted, free of charge, to any person obtaining a copy |
---|
24 | % of this software and associated documentation files (the "Software"), to deal |
---|
25 | % in the Software without restriction, subject to the following conditions: |
---|
26 | % |
---|
27 | % The above copyright notice and this permission notice shall be included in all |
---|
28 | % copies or substantial portions of the Software. |
---|
29 | % |
---|
30 | % The Software is provided "as is", without warranty of any kind. |
---|
31 | |
---|
32 | % April 1999 Original version |
---|
33 | % January 2003 Error in calculation of d2 corrected |
---|
34 | |
---|
35 | function [gradient, or] = canny(im, sigma) |
---|
36 | |
---|
37 | [rows, cols] = size(im); |
---|
38 | im = double(im); % Ensure double |
---|
39 | |
---|
40 | hsize = [6*sigma+1, 6*sigma+1]; % The filter size. |
---|
41 | |
---|
42 | gaussian = fspecial('gaussian',hsize,sigma); |
---|
43 | im = filter2(gaussian,im); % Smoothed image. |
---|
44 | |
---|
45 | h = [ im(:,2:cols) zeros(rows,1) ] - [ zeros(rows,1) im(:,1:cols-1) ]; |
---|
46 | v = [ im(2:rows,:); zeros(1,cols) ] - [ zeros(1,cols); im(1:rows-1,:) ]; |
---|
47 | d1 = [ im(2:rows,2:cols) zeros(rows-1,1); zeros(1,cols) ] - ... |
---|
48 | [ zeros(1,cols); zeros(rows-1,1) im(1:rows-1,1:cols-1) ]; |
---|
49 | d2 = [ zeros(1,cols); im(1:rows-1,2:cols) zeros(rows-1,1); ] - ... |
---|
50 | [ zeros(rows-1,1) im(2:rows,1:cols-1); zeros(1,cols) ]; |
---|
51 | |
---|
52 | X = h + (d1 + d2)/2.0; |
---|
53 | Y = v + (d1 - d2)/2.0; |
---|
54 | |
---|
55 | gradient = sqrt(X.*X + Y.*Y); % Gradient amplitude. |
---|
56 | |
---|
57 | or = atan2(-Y, X); % Angles -pi to + pi. |
---|
58 | neg = or<0; % Map angles to 0-pi. |
---|
59 | or = or.*~neg + (or+pi).*neg; |
---|
60 | or = or*180/pi; % Convert to degrees. |
---|