function d=sobel(x,n,dir)
d=x;
if dir==1
operator=[1,2,1;0,0,0;-1,-2,-1];
else
operator=[1,0,-1;2,0,-2;1,0,-1]
end
[width,height]=size(x);
for ii=1:width-(n-1)
for jj=1:height-(n-1)
tmp=x(ii:ii+n-1,jj:jj+n-1).*operator;
p=sum(sum(tmp));
d(ii+(n-1)/2,jj+(n-1)/2)=p;
end
d=x;
if dir==1
operator=[1,2,1;0,0,0;-1,-2,-1];
else
operator=[1,0,-1;2,0,-2;1,0,-1]
end
[width,height]=size(x);
for ii=1:width-(n-1)
for jj=1:height-(n-1)
tmp=x(ii:ii+n-1,jj:jj+n-1).*operator;
p=sum(sum(tmp));
d(ii+(n-1)/2,jj+(n-1)/2)=p;
end
end
%============================================================================================================
%author:王同乐
%date:2016/10/30
img=imread('lena.png');
img=rgb2gray(img);
img=im2double(img);%输入图像类型为uint8,将其转换为double类型进行运算
%=====================================sobel算子
subplot(1,3,1);imshow(img);title('原图');
subplot(1,3,2);imshow(sobel(img,3,1));title('soble提取垂直边缘后的图像')
subplot(1,3,3);imshow(sobel(img,3,2));title('sobel提取水平边缘后的图像');