Sobel算子是把图像中的每个像素的上下左右四领域的灰度值加权差,在边缘处达到极值从而检测边缘。 
图像中每个像素点都与下面两个核做卷积,一个核对垂直边缘影响最大,而另一个核对水平边缘影响最大,两个卷积的最大值作为这个像素点的输出值。 
Sobel算法能够产生较好的检测效果,而且对噪声具有平滑抑制作用,但是得到的边缘较粗,可能出现伪边缘,该算法根据具体工况合理设计。 Sobel算法程序如下: - %% Sobel
 
 - clc,clear,close all                    % 清屏、清工作区、关闭窗口
 
 - warning off                         % 消除警告
 
 - feature jit off                        % 加速代码执行
 
 - I=imread('1.jpg');  % 读入图像
 
 - r=I(:,:,1);g=I(:,:,2);b=I(:,:,3);
 
 - nI=size(r);
 
 - im = single(I) / 255;
 
  
-         yfilter = fspecial('sobel'); % sobel
 
 -         xfilter = yfilter';
 
 -         
 
 -         rx = imfilter(im(:,:,1), xfilter);
 
 -         gx = imfilter(im(:,:,2), xfilter);
 
 -         bx = imfilter(im(:,:,3), xfilter);
 
 -         
 
 -         ry = imfilter(im(:,:,1), yfilter);
 
 -         gy = imfilter(im(:,:,2), yfilter);
 
 -         by = imfilter(im(:,:,3), yfilter);
 
 -         
 
 -         Jx = rx.^2 + gx.^2 + bx.^2;
 
 -         Jy = ry.^2 + gy.^2 + by.^2;
 
 -         Jxy = rx.*ry + gx.*gy + bx.*by;
 
  
-         D = sqrt(abs(Jx.^2 - 2*Jx.*Jy + Jy.^2 + 4*Jxy.^2)); % 2x2 matrix J'*J的第一个特征值
 
 -         e1 = (Jx + Jy + D) / 2;
 
 -         %  e2 = (Jx + Jy - D) / 2;                                   %第二个特征值
 
  
- edge_magnitude = sqrt(e1);
 
 - edge_orientation = atan2(-Jxy, e1 - Jy);
 
 - % figure,
 
 - % subplot(121),imshow(edge_magnitude)                  % 梯度
 
 - % subplot(122),imshow(edge_orientation)                  % 方向
 
  
- sob=edge(edge_magnitude,'sobel',0.29);
 
 - % sob=bwareaopen(sob,100);                                  % 剔除小块
 
 - % figure,imshow(y),title('Sobel Edge Detection')
 
  
- % 3*3 sobel
 
 - f=edge_magnitude;
 
 - sx=[-1 0 1;-2 0 2;-1 0 1];                         % 卷积模板convolution mask
 
 - sy=[-1 -2 -1;0 0 0;1 2 1];                         % 卷积模板convolution mask
 
 - for x=2:1:nI(1,1)-1
 
 -     for y=2:1:nI(1,2)-1
 
 -         mod=[f(x-1,y-1),2*f(x-1,y),f(x-1,y+1);
 
 -             f(x,y-1),2*f(x,y),f(x,y+1);
 
 -             f(x+1,y-1),2*f(x+1,y),f(x+1,y+1)];
 
 -         mod=double(mod);
 
 -         fsx=sx.*mod;
 
 -         fsy=sy.*mod;
 
 -         ftemp(x,y)=sqrt((sum(fsx(:)))^2+(sum(fsy(:)))^2);
 
 -     end
 
 - end
 
 - fs=im2bw(ftemp); % fs=im2uint8(ftemp);
 
 - fs=bwareaopen(fs,500);
 
 - % figure,imshow(fs);title('Sobel Edge Detection')
 
  
- subplot(131),imshow(edge_magnitude),title('edge magnitude')
 
 - subplot(132),imshow(sob),title('edge magnitude extraction')
 
 - subplot(133),imshow(fs);title('sobel Edge Detection')
 
 
  复制代码 
 
  
 |