calculate gradient by applying sobel operator on image in matlab and seperable filtering in matlab

To calculate the gradient of an image in MATLAB, we can apply the Sobel operator using two separable filters, one in the horizontal direction and one in the vertical direction.

Here's the code to apply the Sobel operator and calculate the gradient using separable filtering:

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

% Convert to grayscale if necessary
if size(img, 3) == 3
    img = rgb2gray(img);
end

% Apply the horizontal and vertical Sobel filters
h = fspecial('sobel')';
v = fspecial('sobel');
img_h = imfilter(double(img), h, 'replicate');
img_v = imfilter(double(img), v, 'replicate');

% Calculate the gradient magnitude and direction
grad_mag = sqrt(img_h.^2 + img_v.^2);
grad_dir = atan2d(img_v, img_h);

% Display the results
figure;
subplot(2,2,1); imshow(img); title('Original Image');
subplot(2,2,2); imshow(img_h, []); title('Gradient in X direction');
subplot(2,2,3); imshow(img_v, []); title('Gradient in Y direction');
subplot(2,2,4); imshow(grad_mag, []); title('Gradient magnitude');
737 chars
25 lines

Here, we load the image, convert it to grayscale (if necessary), and apply the horizontal and vertical Sobel filters using the imfilter function. Then, we calculate the gradient magnitude and direction using the sqrt and atan2d functions respectively. Finally, we display the original image and the separate gradient images using the imshow function.

gistlibby LogSnag