matlab实现

I=imread('10.tif');

imgray = rgb2gray(I);%灰度转化
[m,n]=size(imgray);
N=m*n ; %灰度值的总数
hist=imhist(imgray);%图像灰度直方图.

下面开始上调用otsu函数的代码

matlab版

function T = OTSU(hist)
   sum_num = sum(hist);
   pro = hist./sum_num;
   T = 1;
   delta_max = 0;
   temp = [];
   for i = 1:256
       w0 = 0;w1 = 0;u0_temp = 0;u1_temp = 0;u0 = 0;u1 = 0;
delta_temp = 0;
       for j=1:256
           if(j<=i)
               w0 =  pro(j) + w0;
               u0_temp = j*pro(j)+u0_temp;
           else
               w1 = w1+pro(j);
               u1_temp = u1_temp + j*pro(j);
           end
       end 
       if(w0>0)
         u0 = u0_temp / w0;
       end
       if(w1>0)
       u1 = u1_temp / w1;
       end
       delta_temp = w0*w1*(u0-u1)^2;
       temp = [temp;delta_temp];
       if(delta_temp > delta_max)
          delta_max = delta_temp;
            T = i;
       end
   end
   T = T-1;
end

 

 

更多推荐