根据OSTU大津法使用Matlab实现数字图像处理segmentation的graythresh函数

时间:2022-05-20 20:24:34

OSTU大津法算法思想:

一幅有depth个灰度级,根据每个灰度级t,可以将一幅图分为前景和背景。

前景指所有灰度级低于等于t的像素点,背景指大于t的像素点。

w0指前景像素个数;

w1指背景像素个数;

u0指前景加权平均,即

temp=0;

for i=1:t

    temp=temp+i*hist(i)

end

u0=temp/w0;

其中w0=hist(0)+hist(1)+……+hist(t)

hist指各个灰度级上的像素个数

u1对应是背景加权平均

u对应整幅图的加权平均

u=u0*w0+u1*w1.(*)

大津法的结果指使得g最大的t值:

g=w0*(u0-u)^2+w1*(u1-u)^2=w0*w1*(u1-u0)^2 (代入*式可得)

实现代码:

function level = Mygraythresh(I)
%GRAYTHRESH Global image threshold using Otsu's method.
%   LEVEL = Mygraythresh(I) computes a global threshold (LEVEL) that can be
%   used to convert an intensity image to a binary image with IM2BW. LEVEL
%   is a normalized intensity value that lies in the range [0, 1].
%   GRAYTHRESH uses Otsu's method, which chooses the threshold to minimize
%   the intraclass variance of the thresholded black and white pixels.
%
%   Example
%   -------
%       I = imread('coins.png');
%       level = Mygraythresh(I);
%       BW = im2bw(I,level);
%       figure, imshow(BW)
%
%   See also IM2BW.
%I=rgb2gray(I);
I=im2uint8(I(:));
depth=256;
counts=imhist(I,depth);
w=cumsum(counts);
ut=counts .* (1:depth)';
u=cumsum(ut);
MAX=0;
level=0;


for t=1:depth
    u0=u(t,1)/w(t,1);
    u1=(u(depth,1)-u(t,1))/(w(depth,1)-w(t,1));
    w0=w(t,1);
    w1=w(depth,1)-w0;
    g=w0*w1*(u1-u0)*(u1-u0);
    if g > MAX
        MAX=g;
        level = t;
    end
end
level=level/256;


实验结果与matlab自带的graythresh略有差别。