Search code examples
matlabgradientquantizationhandwriting-recognitionsobel

find gradient using sobel mask operator in matlab


I am using following code to mask image using sobel mask .

for i=1:size(C,1)-2
    for j=1:size(C,2)-2
        %Sobel mask for x-direction:
        Gx=((2*C(i+2,j+1)+C(i+2,j)+C(i+2,j+2))-(2*C(i,j+1)+C(i,j)+C(i,j+2)));
        %Sobel mask for y-direction:
        Gy=((2*C(i+1,j+2)+C(i,j+2)+C(i+2,j+2))-(2*C(i+1,j)+C(i,j)+C(i+2,j)));

        %The gradient of the image
        %B(i,j)=abs(Gx)+abs(Gy);
        B(i,j)=sqrt(Gx.^2+Gy.^2);
        direction = atan(Gy./Gx)

    end
end

My question is that sometimes gradient direction value is giving as "NaN", how to avoid it?

Second, how to quantize gradient direction into eight zone and find feature vector for the image? Please someone help me.


Solution

  • Here is the implementation :

    clc;clear;close;
    
    % Read the Image
    image=imread('girl.png');
    f=rgb2gray(image);
    
    %   Initializations
    Gx=zeros(size(f,1),size(f,2));
    Gy=zeros(size(f,1),size(f,2));
    Theta=zeros(size(f,1),size(f,2));
    Edges=zeros(size(f,1),size(f,2));
    
    % Sobel Filtering
    for x=2:size(f,1)-2
        for y=2:size(f,2)-2
    
        Gy(x,y)= ( f(x-1,y+1) + 2*f(x,y+1) + f(x+1,y+1) )...
            -( f(x-1,y-1) + 2*f(x,y-1) + f(x+1,y-1) );
    
        Gx(x,y)= ( f(x+1,y-1) + 2*f(x+1,y) + f(x+1,y+1) )...
            -( f(x-1,y-1) + 2*f(x-1,y) + f(x-1,y+1) );   
    
        Theta(x,y)= atan(Gx(x,y)/Gy(x,y));  % Direction
    
        Edges(x,y)=sqrt( Gx(x,y)^2 + Gy(x,y)^2);
    
        end
    end
    

    Results :

    enter image description here