sobel算子原理以及运用
Sobel邊緣檢測算法:
主要用作邊緣檢測,在技術(shù)上,它是一離散性差分算子,用來運算圖像亮度函數(shù)的灰度之近似值。在圖像的任何一點使用此算子,將會產(chǎn)生對應(yīng)的灰度矢量或是其法矢量
?
Sobel卷積因子為:
?
該算子包含兩組3x3的矩陣,分別為橫向及縱向,將之與圖像作平面卷積,即可分別得出橫向及縱向的亮度差分近似值。如果以A代表原始圖像,Gx及Gy分別代表經(jīng)橫向及縱向邊緣檢測的圖像灰度值,其公式如下:
?
?
具體計算如下:
Gx = (-1)*f(x-1, y-1) + 0*f(x,y-1) + 1*f(x+1,y-1)
????? +(-2)*f(x-1,y) + 0*f(x,y)+2*f(x+1,y)
????? +(-1)*f(x-1,y+1) + 0*f(x,y+1) + 1*f(x+1,y+1)
= [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)]
?
Gy =1* f(x-1, y-1) + 2*f(x,y-1)+ 1*f(x+1,y-1)
????? +0*f(x-1,y) 0*f(x,y) + 0*f(x+1,y)
????? +(-1)*f(x-1,y+1) + (-2)*f(x,y+1) + (-1)*f(x+1, y+1)
= [f(x-1,y-1) + 2f(x,y-1) + f(x+1,y-1)]-[f(x-1, y+1) + 2*f(x,y+1)+f(x+1,y+1)]
?
其中f(a,b),?表示圖像(a,b)點的灰度值;
?
圖像的每一個像素的橫向及縱向灰度值通過以下公式結(jié)合,來計算該點灰度的大小:
?
通常,為了提高效率?使用不開平方的近似值:
?
如果梯度G大于某一閥值?則認為該點(x,y)為邊緣點。
?
然后可用以下公式計算梯度方向:
?
?
?
Sobel算子根據(jù)像素點上下、左右鄰點灰度加權(quán)差,在邊緣處達到極值這一現(xiàn)象檢測邊緣。對噪聲具有平滑作用,提供較為精確的邊緣方向信息,邊緣定位精度不夠高。當對精度要求不是很高時,是一種較為常用的邊緣檢測方法。
實驗代碼:
y = filter(b,a,X) ?函數(shù)法:
Y = filter2(h,X,shape) returnsthe part of Y specified by the shape parameter. shape isa string with one of these values:
'full'
Returns the full two-dimensional correlation. In thiscase, Y is larger than X.
'same'
(default) Returns the central part of the correlation.In this case, Y is the same size as X.
'valid'
Returns only those parts of the correlation that arecomputed without zero-padded edges. In this case, Y issmaller than X.
代碼:
I=imread('lena.jpg');
subplot(2,2,1);
imshow(I);
title('原圖像');
Gx=[-1 -2 -1;0 0 0;1 2 1];
Gy=Gx';
GIx=filter2(Gx,I,'same');% ?same 是代表圖像邊緣的像素怎么處理,
GIx=abs(GIx);
subplot(2,2,2);
imshow(GIx);
title('x方向的梯度');
GIy=filter2(Gy,I,'same');
GIy=abs(GIy);
subplot(2,2,3);
imshow(GIy);
title('y方向的梯度');
G=GIx+GIy;
subplot(2,2,4);
imshow(G,[]);
title('圖像的sobel梯度');
代碼的詳細過程:
I=imread('lena.jpg');
subplot(2,2,1);
imshow(I);
title('原圖像');
Gx=[-1 -2 -1;0 0 0;1 2 1];
Gy=Gx';
[m n]=size(I);
I1=zeros(m,n);
for i=2:m-1
? ? for j=2:n-1
? ? ? for k=-1:1
? ? ? ? ? for p=-1:1
? ? ? ? ? ? ? I1(i,j)= I1(i,j)+I(i+k,j+p)*Gx(k+2,p+2);
? ? ? ? ? end
? ? ? end
? ? end
end
subplot(2,2,2);
imshow(I1,[]);
title('x方向');
%%
[m n]=size(I);
I2=zeros(m,n);
for i=2:m-1
? ? for j=2:n-1
? ? ? for k=-1:1
? ? ? ? ? for p=-1:1
? ? ? ? ? ? ? I2(i,j)= I2(i,j)+I(i+k,j+p)*Gy(k+2,p+2);
? ? ? ? ? end
? ? ? end
? ? end
end
subplot(2,2,3);
imshow(I2,[]);
title('y方向');
%% ?sobel梯度
I3=I1+I2;
subplot(2,2,4);
imshow(I3,[])
總結(jié)
以上是生活随笔為你收集整理的sobel算子原理以及运用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 递归函数的理解 (三种类型)
- 下一篇: Robert算子的运用