Sunday, April 10, 2016

Matlab: Gradient Using manually convolution 2d

%page=167
%Gradient Using manually convolution 2d


clc;
clear all;
close all;

A=imread('8.jpg');
A=rgb2gray(A);
A=imread('rice.tif');


subplot(2,2,1);
imshow(A);
title('Original Image');

mx=[-1 -2 -1; 0 0 0; 1 2 1];

my=[-1 0 1; -2 0 2; -1 0 1];


%H = conv2(double(A),double(mx));
%V = conv2(double(A),double(my));

H=conv_img2(double(mx),double(A)) ;
%H=corr_img(double(mx),double(A)) ;

V=conv_img2(double(my),double(A));


subplot(2,2,2);
imshow(uint8(H));
title('Horizontal delp/delx');

subplot(2,2,3);
imshow(uint8(V));
title('Vertical delp/dely');


subplot(2,2,4);
imshow(uint8(sqrt(H.^2 + V.^2)));
%imshow(uint8(H));
title('Gradient Image');




%---------function

%convolution of image
function [Output] = img_conv2( mask,Input)

v=flipdim(mask,2);
w = flipdim(v,1);

[x y] = size(Input);
[m n]=size(w);

k1=(m-1)/2;
k2=(n-1)/2;
tempInput=padarray(Input,[k1 k2]);

for i = 1 : x
    for j = 1 : y
         aValue = tempInput(i,j)*w(1,1)+tempInput(i,j+1)*w(1,2)+tempInput(i,j+2)*w(1,3)+tempInput(i+1,j)*w(2,1)+tempInput(i+1,j+1)*w(2,2)+tempInput(i+1,j+2)*w(2,3)+                  tempInput(i+2,j)*w(3,1)+tempInput(i+2,j+1)*w(3,2)+tempInput(i+2,j+2)*w(3,3);
         Output(i,j)= aValue;
    end
end