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 -
GDIR -
As a test, one can notice the bar-like structure right behind Lena in the GDIR image now, which wasn't visible before.