I = imread('E:\test\lena.png','png');
I = double(I);
[height,width] = size(I);
size = height * width; % the size of the image
G_min = min(min(I)); % the min gray value of the image
G_max = max(max(I)); % the max gray value of the iamge
I_2Dhist = zeros(G_max+1,G_max+1); % the array to store the 2D hist of the image
I_mean = zeros(height,width); % the mean value of the local image
I_seg = zeros(height,width);
WS = 3; % mean filter's window size 3*3
nr = floor(WS/2);
I_big=zeros(height+2*nr,width+2*nr); % the bigger array used to mean filter
I_big(nr+1:height+nr,nr+1:width+nr)=I; % copy data from the original image
%%%%%%%%%% mean filter %%%%%%%%%%%
%%%%%% 获取局部区域灰度信息%%%%%
for i=1:height
for j=1:width
sum = 0;
num = 0;
for h=-nr:nr
for w=-nr:nr
sum = sum + I_big(i+h,j+w);
num = num + 1;
end
end
I_mean(i,j) = sum/num;
end
end
%%%% 构建2D直方图,横轴上以点象素灰度表示,纵轴上以局部区域灰度表示%%%%
for i=1:height
for j=1:width
h = I(i,j)+1; % 横轴信息,避免0,所以加1,象素灰度
w = I_mean(i,j)+1; % 纵轴信息,避免0,所以加1,局部区域灰度
I_2Dhist(h,w) = I_2Dhist(h,w) + 1; % 统计灰度对的出现次数,构建2D直方图
end
end
% find the best thresh : hor_thresh,and ver_thresh %
for ver_thresh=0:G_max
for hor_thresh=0:G_max
sum1 = 0;
sum2 = 0;
H1 = 0;
H2 = 0;
for i=0:ver_thresh
for j=0:hor_thresh
sum1 = sum1 + I_2Dhist(i+1,j+1);
end
end
for i=0:ver_thresh
for j=0:hor_thresh
P1 = I_2Dhist(i+1,j+1)/sum1;
H1 = H1 + P1*log(P1);
end
end
if i < G_max & j < G_max
for i=ver_thresh+1:G_max
for j=hor_thresh+1:G_max
sum2 = sum2 + I_2Dhist(i+1,j+1);
end
end
for i=ver_thresh+1:G_max
for j=hor_thresh+1:G_max
P2 = I_2Dhist(i+1,j+1)/sum2;
H2 = H2 +P2*log(P2);
end
end
end
H_total = H1 + H2;
if H_total > max
max = H_total;
ver_Tbest = ver_thresh;
hor_Tbest = hor_thresh;
end
end
end
%%%%%% 分割%%%%%%%%
for i=1:height
for j=1:width
if I(i,j) < ver_Tbest & I_mean(i,j) < hor_Tbest
I_seg(i,j) = 0;
elseif I(i,j) >= ver_Tbest & I_mean(i,j) >= hor_Tbest
I_seg(i,j) = 255;
end
end
end
T_best
figure;
imshow(uint8(I_seg));
figure;
imhist(uint8(I));
[本帖最后由 mooni 于 2009-5-31 11:49 编辑]