sobel operator in matlab

Here is an implementation of Sobel operator in MATLAB for edge detection:

main.m
% Read the image
img = imread('your_image.jpg');

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

% Apply Sobel operator to get the edges
sobel_x = [-1 0 1; -2 0 2; -1 0 1];
sobel_y = [-1 -2 -1; 0 0 0; 1 2 1];

img_x = imfilter(double(gray_img), sobel_x);
img_y = imfilter(double(gray_img), sobel_y);

edges = sqrt(img_x.^2 + img_y.^2);

% Show the original and edge detected images
imshowpair(gray_img, edges, 'montage');
title('Original Image (Left) and Sobel Operator Edge Detection (Right)');
509 chars
19 lines

In this code, imread function is used to read an image from file. rgb2gray function is used to convert the image to grayscale. Then, we define two filters for x and y directions using Sobel operator. We apply these filters using imfilter function. Finally, we compute the magnitude of the gradient using the two filtered images and display the original and edge detected images side by side using imshowpair function.

gistlibby LogSnag