大津法——邊緣檢測

lifeitengup發表於2013-10-01


做個記錄

邊緣檢測:

function  E = DetectEdge(I)
%by:LiFeiteng 
%Version1.0  灰度影像  2013/5/06
%Version1.1  彩色影像  2013/5/13
if size(I,3)==3
    I = rgb2gray(I);
end
mask = fspecial('gaussian',[3 3],3);
I = imfilter(I,mask);
I = double(I);
fx = conv2(I,[-1 1], 'same');
fy = conv2(I,[-1;1], 'same');
grad = sqrt(fx.^2+fy.^2);
% grad = ordfilt2(grad,1,ones(3,3));
t = myOtsu(grad);
E = grad > t;
%E = grad;
end

大津法:

function T = myOtsu(E)
% 大津法
E = uint8(E);
E = E(:);
MN = size(E,1);
t = 0;
g = [];
for i=1:256
    n0 = E <= t;
    n1 = E > t;
    N0 = sum(n0);
    N1 = sum(n1);
    w0 = N0/MN;
    w1 = N1/MN;
    mu0 = sum(E(n0))/N0; mu1 = sum(E(n1))/N1;
    mu = w0*mu0 + w1*mu1;
    g(1,i) = w0*(mu0-mu)^2 + w1*(mu1-mu)^2;
    t = t+1;
end
[~, index] = max(g);
T = mean(index-1);

測試用例:

img = imread('lena.tif');
img = imnoise(img,'gaussian');
figure,imshow(img)
E = DetectEdge(img);
figure,imshow(E,[])




相關文章