Tuesday, November 22, 2011

Image gradient with central difference is fun

We have computed image derivatives with forward finite difference. Let us now take partial derivatives with central finite difference method.

du/dx:=(u(x+h, y)-u(x-h, y))/2h and du/dy:=(u(x, y+h)-u(x, y-h))/2h


Having written the codes one can use them to compute the image difference with central difference scheme.


Image gradient with central difference 


%==========================================================================

function [Gx, Gy]=gradient_central(u)

% Author: Prashant Athavale
% Date: 11/22/2011
% Please acknowledge my name if you use this code, thank you.

% This function computes the gradient of the image u.
% It uses central difference approximation of the derivatives 
% and thus the name gradient_central

%==========================================================================

if strcmp(class(u),'uint8')
    u=double(u);
end
Gx=Dfx_central(u);
Gy=Dfy_central(u);

end % end of the function gradient_central

%==========================================================================


%==========================================================================

function Gm=grad_central_magnitude(u)

% Author: Prashant Athavale
% Date: 11/22/2011
% Please acknowledge my name if you use this code, thank you.

% This function takes the image stored in u and gives the magnitude of the
% gradient

%==========================================================================

if strcmp(class(u),'uint8')
    u=double(u);
end
[Gx, Gy]=gradient_central(u);
Gm=sqrt(Gx.*Gx+Gy.*Gy);

end % end of the function grad_central_magnitude

%==========================================================================



Image gradient results with central difference

Here are the results of the above codes with the following commands in the command window


u=imread('barbara.png');

Gm=grad_central_magnitude(u);

ucx=Dfx_central(u); figure; imshow(ucx/255+0.4);

ucy=Dfy_central(u); figure; imshow(ucy/255+0.4);
figure; imshow(Gm/255+0.4);


Partial derivative in x-direction with central difference


Partial derivative in y-direction with central difference




Magnitude of the gradient with central difference


No comments:

Post a Comment