# Canny Edge Detection Algorithm problem?

Asked by Steve on 2 Jun 2012
Latest activity Answered by Walter Roberson on 3 Jun 2012

Hello Dear Experts,

Here is what I have written as an implementation of the Canny Edge detection algorithm but I get non accurate results. Please try to help me, what can be the reason, where did I do a mistake?

function [ newImg ] = edgeDetect( img )
% Step 0: Initialization, smoothing the matrix to eliminate the noise:
[imgRows imgCols] = size(img);
% Gaussian Filter:
GaussianFilter = fspecial('gaussian', 5, 1);
%T = T/sum(sum(T)); % Normalizing the filter
SmoothMat = conv2(img,GaussianFilter,'same'); % Smoothing
epsilon = exp(-10);
newImg = zeros(size(img));
HiT = 0.15;
LoT = 0.07;
% Step 1: Calculating the derivative of the smoothed image using convolution:
dx = conv2(SmoothMat,[-1 1],'same');
dy = conv2(SmoothMat,[-1 1]','same');
% Substep: There can be dx(i,j) = 0 and dy(i,j)/dx(i,j) will be +/-inf to
% avoid it we will add an epsilon to eliminate the +/-inf problem:
idx = dx == 0;
dx(idx) = epsilon;
% Step 2: Calculating the gradient and the angle:
TanTheta = dy./dx;
% Avoiding the edges of the matrix - first and last rows and columns
% Step 3: Checking direction condition and gradient value along with NMS
for i = 2:imgRows+1
for j = 2:imgCols+1
if ((TempTanTheta(i,j) >= -0.4142) && (TempTanTheta(i,j) <= 0.4142))
elseif ((TempTanTheta(i,j) > 0.4142) && (TempTanTheta(i,j) <= 2.4142))
elseif (abs(TempTanTheta(i,j)) > 2.4142)
elseif ((TempTanTheta(i,j) >= -2.4142) && (TempTanTheta(i,j) < -0.4142))
end
end
end
% Step 4: The hysteresis part, using the predefined threshold values
for i = 2:imgRows-1
for j = 2:imgCols-1
else
end
end
end
end
function [num] = isMax(p1,p2,p3)
%if p2 is the biggest
if p2>=p3 && p2>=p1
num=p2;
else
num=0;
end
end

## Products

Answer by Image Analyst on 2 Jun 2012

No - I'm not into reinventing wheels for basic building block functions like this. Any reason why you don't just use the edge() function that's built in to MATLAB's Image Processing Toolbox? It does a Canny filter.

## 1 Comment

Steve on 2 Jun 2012

I need to write it myself as part of some big project.
I know there is such function but I need your professional help to understand what is wrong.

There are a lot of experts here who help a lot including you.

Answer by Walter Roberson on 3 Jun 2012

Those do convert (some) floating point results to exact 0's and 1's, and store those exact values back into TempGradVec over-top of the previous floating point values. But if the floating point value does not happen to be in that particular range, you go on to the test