Search code examples
matlabimage-processingedge-detection

Canny Edge Detector - trouble in implementation


I am trying to implement the canny edge detector. I have made some code which generates what I think should be correct up to the non-maxima suppression stage, however when I run it I get an image that just about shows the outlines, but is not my expected result.

I have spent hours trying to fix it, but can't find where I have gone wrong. Can anyone point me in the right direction?

% Set direction to either 0, 45, -45 or 90 depending on angle.
[x,y]=size(f1);
for i=1:x-1,
    for j=1:y-1,
        if ((gradAngle(i,j)>67.5 && gradAngle(i,j)<=90) || (gradAngle(i,j)>=-90 && gradAngle(i,j)<=-67.5)) 
            gradDirection(i,j)=0;
        elseif ((gradAngle(i,j)>22.5 && gradAngle(i,j)<=67.5))
            gradDirection(i,j)=45;
        elseif ((gradAngle(i,j)>-22.5 && gradAngle(i,j)<=22.5))
            gradDirection(i,j)=90;
        elseif ((gradAngle(i,j)>-67.5 && gradAngle(i,j)<=-22.5))
            gradDirection(i,j)=-45;
        end
    end
end

% Non-maxima suppression. 
% Compare to neighbours and set as 0 if smaller than either of them
for i=2:x-2,
    for j=2:y-2,
        if(gradDirection(i,j)==90)
           if (gradDirection(i,j)<(gradDirection(i,j-1) | gradDirection(i,j+1)))
               gradDirection(i,j)=0;
           end 
        end
        if(gradDirection(i,j)==45)
           if (gradDirection(i,j)<(gradDirection(i+1,j-1) | gradDirection(i-1,j+1)))
               gradDirection(i,j)=0;
           end 
        end
        if(gradDirection(i,j)==-45)
           if (gradDirection(i,j)<(gradDirection(i-1,j-1) | gradDirection(i+1,j+1)))
               gradDirection(i,j)=0;
           end 
        end
    end
end

Solution

  • I think the problem is with the bitwise OR's you have there:

     if (gradDirection(i,j)<(gradDirection(i,j-1) | gradDirection(i,j+1)))
    

    I think it should be something like:

     if (gradDirection(i,j)<gradDirection(i,j-1) || gradDirection(i,j)<gradDirection(i,j+1))