OTSU算法(二)

%使用OTSU算法进行二值化后的图像

close all;clear all;clc

%%

I = imread('C.jpg');

scoreImage0=rgb2gray(I);

scoreImage=double(scoreImage0); 

[height,length]=size(scoreImage); 

totalPixel=height*length; 

% maxPixNumber=max(max(scoreImage)); 

% 这个地方为了以后计算方便 就不这样计算了 而是默认最大的为255   

pixelCount=zeros(1,256);%统计各个像素值的个数 

                                     % 0-256 

for i=1:length     

  for j=1:height

          number=scoreImage(j,i)+1;

          pixelCount(number)=pixelCount(number)+1;

      end 

end   

 

%概率 

pf=pixelCount/totalPixel; 

 

%前向累计概率密度函数 

cpf=zeros(1,256); 

cpf(1)=pf(1); 

for i=2:256

      cpf(i)=cpf(i-1)+pf(i); 

end 

 

%后向累计概率密度函数 

bpf=zeros(1,256); 

bpf(256)=pf(256); 

for j=256:-1:2

      bpf(j-1)=bpf(j)+pf(j-1); 

end      

 

%前向累计期望 

meanForward=zeros(1,256); 

meanForward(1)=1; 

for i=2:256

      meanForward(i)=meanForward(i-1)*(cpf(i-1)/cpf(i))+(pf(i)/cpf(i))*i; 

end   

 

%后向累计期望 

meanBack=zeros(1,256); 

meanBack(max(max(scoreImage)))=max(max(scoreImage)); 

for i=max(max(scoreImage)):-1:2

      meanBack(i-1)=meanBack(i)*(bpf(i)/bpf(i-1))+(pf(i-1)/bpf(i-1))*(i-1); 

end     

 

delta=cpf.*bpf.*(meanForward-meanBack).^2; 

[value,index]=max(delta); 

% 返回的是逻辑的图像 

binariedImage=scoreImage>index;

figure;

subplot(1,2,1);imshow(scoreImage0); title('原图');

subplot(1,2,2);imshow(binariedImage); title('处理图');

 

此处参考原文为:http://blog.sina.com.cn/s/blog_98ddf7cb0101chu3.html

posted @ 2016-04-08 10:50  一个人的素城、  阅读(226)  评论(0编辑  收藏  举报