img= imread('rice.png');
img = medfilt2(img);
subplot(1,2,1),imshow(img);
title('原图像')
[M,N] = size(img);
sum_total = sum(img(:));
ave_total = sum_total/(M*N);
[a,b] = imhist(img);
a = a';
b = b';
T_optimal = 1;
h_max =0;
for T=2:255
% 将直方图分开
a1 = a(1:T);
a2 = a(T:256);
b1 = b(1:T);
b2 = b(T:256);
% 分别求两部分的各自均值
a1_ave = sum(a1.*b1)/sum(a1);
a2_ave = sum(a2.*b2)/sum(a2);
w1 = sum(a1)/(M*N);
w2 = sum(a2)/(M*N);
% 目标函数为w1*(a1_ave-ave_total)^2+w2*(a2_ave-ave_total)^2
h = w1*(a1_ave-ave_total)^2+w2*(a2_ave-ave_total)^2;
if h>h_max
h_max = h;
T_optimal = T;
else
continue
end
end
T_optimal
h_max
for i=1:M
for j=1:N
if img(i,j)<T_optimal
img(i,j) = 0;
else
img(i,j) = 255;
end
end
end
subplot(1,2,2),imshow(img);
title('阈值分割后的图像')
先展示一下最后的求解结果
基本的思想就是循环求解各个组的平均值和计算目标函数的最大值,最后实现了一个基于求解的阈值的图像二值化操作,自我感觉还不错
graythresh()
可以用来直接求解灰度图像的ostu阈值,做了一个简单的对比,发现自己的计算结果还是可以的