3
votes

In Matlab, I want to display the gradient magnitude and direction of a grayscale image. Here is the code I am trying:

image = imread('gray_image.bmp');
[gmag, gdir] = imgradient(image);
figure, imshow(image);
figure, imshow(gmag);
figure, imshow(gdir);

However, gmag and gdir seem to be quantized to just two values: black and white. Every pixel in gmag and gdir is either black, or white. My image itself has a range of gradient magnitudes and directions. Why are these not showing up in the gmag and gdir images? Yes, I would expect gmag to have pure black for pixels with zero gradient, and pure white for pixels with maximum gradient, but I would also expect a range of gray values for gradients between those. Similarly, I would expect a range of gray values in gdir representing the range of angles.

For example, here is the grayscale image:

Original Grayscale Image

Here is gmag:

Gradient Magnitude

And here is gdir:

Gradient Direction

Why are gmag and gdir only displaying black or white, with no intermediate gray values?

1

1 Answers

4
votes

Two issues

  • 'gmag' and 'gdir' calculated with IMGRADIENT have double datatype. Thus, if you want to display them as such, MATLAB would treat them as intensity images and would expect them to be in the range [0 1]. Thus, we need to normalize ‘gmag’ and ‘gdir’, which is shown in the code later on.
  • If you wish to save these images, MATLAB expects UINT8 datatype and the values must lie in the range [0 255].Thus, before saving you need to multiply it by 255 and then convert to UINT8.

Code

image = imread('gray_image.bmp');
[gmag, gdir] = imgradient(image);

%%// Normalize gmag and gdir
gmag = (gmag-min(gmag(:)))./(max(gmag(:))-min(gmag(:)));
gdir = (gdir-min(gdir(:)))./(max(gdir(:))-min(gdir(:)));

%%// Display images
figure, imshow(image);
figure, imshow(gmag);
figure, imshow(gdir);

%%// Save gradient images
imwrite(uint8(255.*gmag),'Lena_gmag.bmp');
imwrite(uint8(255.*gdir),'Lena_gdir.bmp');

Ouput images

GMAG -

enter image description here

GDIR -

enter image description here

As a test, one can notice the bar-like structure right behind Lena in the GDIR image now, which wasn't visible before.