edge detection in matlab

One way to perform edge detection in Matlab is by using the Sobel operator. The following code shows an example of using the Sobel operator to detect edges in an image:

main.m
% Load the image
img = imread('example.jpg');

% Convert the image to grayscale
gray = rgb2gray(img);

% Apply the Sobel operator
dx = [-1 0 1; -2 0 2; -1 0 1];
dy = dx';
edge_x = imfilter(double(gray), dx);
edge_y = imfilter(double(gray), dy);
edge = sqrt(edge_x.^2 + edge_y.^2);

% Display the result
imshow(edge);
317 chars
16 lines

In this code, we first load an image and convert it to grayscale. Then we define the Sobel operator kernels dx and dy and apply them to the image using the imfilter function. We compute the gradient magnitude by taking the square root of the sum of squared x and y gradients. Finally, we display the result using the imshow function.

gistlibby LogSnag