Sunday, April 17, 2011

How to calculate vertical and Horizontal Gradients, binarize and find vertical and horizontal projections of an Image in Matlab


The following code snippet shows the few steps for calculating horizontal and vertical gradients,  binarize and find vertical and horizontal projections of an Image of an image and show the corresponding results in the respective figures:
%Function starts here

function calcGradients()
close all;%Closes all opened figures
img=imread(PATH); % provide the path from where u want to load your image
gimg=rgb2gray(img); %To show how to convert color image into grayscale image
 figure, imshow(gimg); %Display gray image
 title('Gray Image');
%Define vertical gradient mask
maskV =[-1, 0, 1;
        -2, 0, 2;
        -1, 0, 1];
%Define Horizontal gradient mask
maskH =[-1, -2, -1;
         0,  0,  0;
         1,  2,  1];

grdv=imfilter(gimg,maskV);%Use matlab imfilter function to calculate vertical gradients with mask given above
figure, imshow(grdv,[]);
title('Vertical Edge');

grdh=imfilter(gimg,maskH);%Use matlab imfilter function to calculate Horizonal gradients with mask
figure, imshow(grdh,[]);
title('Horizontal Edge');

%Binarize the images

level = graythresh(grdv);
BWv = im2bw(grdv,level);
figure,imshow(BWv,[]);
title('Binarized image Vertical');

level = graythresh(grdh);
BWh = im2bw(grdh,level);
figure,imshow(BWh,[]);
title('Binarized image Horizontal');


%Dilation

dv =ones(3,4);
dilateBWv = imdilate (BWv, dv);
figure, imshow(dilateBWv,[]);
title('Dilated vertical image ');

dh=ones(3,6);
dilateBWh = imdilate (BWh, dh);
figure, imshow(dilateBWh,[]);
title('Dilated Horizontal Image');

%Combine vertical and horizontal images into one image by AND operation
finalImg=dilateBWh & dilateBWv;

figure, imshow(finalImg,[]);
title('finalImg Image');

pH=sum(finalImg,1); %Projection Horizontal
pV=sum(finalImg,2); %Projection Vertical
figure, plot(pH);
title('horitozntal projection');
figure, plot(pV);
title('Vertical projection');
end

1 comment: