在matlab中使用sobel mask运算符查找梯度

时间:2017-02-25 11:30:30

标签: matlab gradient quantization handwriting-recognition sobel

我使用以下代码使用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

我的问题是,有时梯度方向值会给出" NaN",如何避免它?

第二,如何将梯度方向量化为八个区域并找到图像的特征向量?请有人帮助我。

1 个答案:

答案 0 :(得分:0)

以下是实施:

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

结果:

enter image description here