sobel convolution in x and y directions in matlab

The Sobel operator is widely used in image processing for edge detection. Here is how to apply Sobel convolution in the x and y directions using Matlab:

main.m
%% Read image
I = imread('image.jpg');

%% Convert to grayscale
I_gray = rgb2gray(I);

%% Apply sobel operator in x and y directions
Sx = [-1 0 1; -2 0 2; -1 0 1]; % Sobel X
Sy = [-1 -2 -1; 0 0 0; 1 2 1]; % Sobel Y

Gx = conv2(double(I_gray), Sx, 'same');
Gy = conv2(double(I_gray), Sy, 'same');

%% Compute magnitude and orientation
G = sqrt(Gx.^2 + Gy.^2);
theta = atan2(Gy, Gx);

%% Show results
figure;
subplot(2,2,1); imshow(I); title('Original image');
subplot(2,2,2); imshow(Gx, []); title('Sobel X');
subplot(2,2,3); imshow(Gy, []); title('Sobel Y');
subplot(2,2,4); imshow(G, []); title('Magnitude');
610 chars
24 lines

In this code, we first read an image and convert it to grayscale. We then apply the Sobel operator in the x and y directions using convolution. Finally, we compute the magnitude and orientation of the edges, and display the results.

gistlibby LogSnag