calculate the gradient of an image in matlab in matlab

To calculate the gradient of an image in MATLAB, you can use the gradient function. The gradient function calculates the directional derivative of an image, which is the rate of change of pixel values in the x and y directions.

Here's an example of how to use the gradient function:

main.m
% Read in an image
img = imread('peppers.png');

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

% Calculate the gradient in the x and y directions
[Gx, Gy] = gradient(double(gray_img));

% Compute the magnitude of the gradient
Gmag = sqrt(Gx.^2 + Gy.^2);

% Display the original image and the gradient magnitude
subplot(1,2,1);
imshow(gray_img);
title('Original Image');
subplot(1,2,2);
imshow(Gmag,[]);
title('Gradient Magnitude');
446 chars
20 lines

In this example, we first read in an image and convert it to grayscale. We then use the gradient function to calculate the directional derivatives in the x and y directions. Finally, we compute the magnitude of the gradient using the x and y derivatives, and display the original image and the gradient magnitude.

gistlibby LogSnag