write nonmaxsup from scratch in matlab

Non-maximum suppression is a technique used in edge detection to simplify the output by getting rid of non-essential pixels. Here's how you can implement non-maximum suppression from scratch in Matlab:

function output = nonmaxsup(input, orientation)

% Read in size of image
[m, n] = size(input);

% Initialize output
output = zeros(m, n);

% Compute magnitude and convert orientation from radians to degrees
magnitude = hypot(imag(input), real(input));
angle = orientation * 180/pi;

% Create a binary image based on the angle of orientation
angle(angle < -90) = angle(angle < -90) + 180;
angle(angle > 90) = angle(angle > 90) - 180;
angle(angle < 0) = angle(angle < 0) + 180;
angle = angle/180;
angle = round(angle * 4) + 1;

% Iterate through each pixel in the image
for i = 2:m-1
   for j = 2:n-1
       
       % Obtain the two pixel values adjacent to the current pixel
       p1 = magnitude(i-1,j-1);
       p2 = magnitude(i+1,j+1);
       
       % Compute the weighted average of the two pixels
       w1 = (p2 - magnitude(i,j))/(p2 - p1);
       weighted_average1 = w1*magnitude(i-1,j-1) + (1-w1)*magnitude(i+1,j+1);
       
       % Obtain the two other adjacent pixels
       p1 = magnitude(i-1,j+1);
       p2 = magnitude(i+1,j-1);
       
       % Compute the weighted average of these pixels
       w2 = (p2 - magnitude(i,j))/(p2 - p1);
       weighted_average2 = w2*magnitude(i-1,j+1) + (1-w2)*magnitude(i+1,j-1);
       
       % Compute a final weighted average based on the angle of the current pixel
       if angle(i,j) == 1 || angle(i,j) == 3
           output(i,j) = (magnitude(i,j) > weighted_average1) && (magnitude(i,j) > weighted_average2);
       else
           output(i,j) = (magnitude(i,j) > weighted_average1) && (magnitude(i,j) >= weighted_average2);
       end
   end
end
1604 chars
48 lines

Here, we compute the magnitude of the input image by taking the absolute value of the real and imaginary components of the input matrix. We also convert the orientation from radians to degrees, and then divide the degrees by 45 to form 4 categories, which correspond to the four main directions (horizontal, vertical, and the two diagonals). We then iterate through each pixel in the input image and compute the weighted average of the adjacent pixels in the direction of the current pixel. Finally, we check whether the magnitude of the current pixel is greater than both weighted averages, and output a binary matrix where the edge pixels have a value of 1 and all other pixels are 0.

gistlibby LogSnag