calculate gradient by applying sobel operator on image in matlab

To calculate the gradient of an image using the Sobel operator in MATLAB:

  1. Read in the image using the imread function.
main.m
img = imread('image.jpg');
27 chars
2 lines
  1. Convert the image to grayscale using the rgb2gray function.
main.m
img_gray = rgb2gray(img);
26 chars
2 lines
  1. Apply the horizontal and vertical Sobel filters to the grayscale image using the imfilter function.
main.m
h_sobel = [-1 -2 -1; 0 0 0; 1 2 1];
v_sobel = [-1 0 1; -2 0 2; -1 0 1];

dx = imfilter(double(img_gray), h_sobel);
dy = imfilter(double(img_gray), v_sobel);
157 chars
6 lines

The double function is used to convert the grayscale image to a double precision format as the imfilter function requires it.

  1. Calculate the gradient magnitude and orientation using the sqrt and atan2 functions, respectively.
main.m
grad_mag = sqrt(dx.^2 + dy.^2);
grad_dir = atan2(dy,dx);
57 chars
3 lines

The .^ operator is used to raise each element of the matrices dx and dy to the power of 2 before being added together. The atan2 function calculates the four-quadrant inverse tangent to find the direction of maximal increase from the horizontal and vertical gradients.

  1. Visualize the gradient magnitude and orientation using the imshow function.
main.m
figure; imshow(grad_mag, []); title('Gradient Magnitude');
figure; imshow(grad_dir, []); colormap jet; colorbar; title('Gradient Orientation');
144 chars
3 lines

The [] argument in imshow sets the display range of the image to the minimum and maximum values of the image data.

gistlibby LogSnag