通常情况下,为了算法的稳定性,图像处理算法需要具有自适应调节阈值并进一步阈值分割,这里给出一种图像动态二值化的图像预处理算法,并在最后给出图像处理的效果。
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%动态二值化
%Author:Zhu
%时间:2022.6
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clc;
image = imread("E:\\1.jpg");
image_matrix=image(:,:,1);
image_matrix=double(image_matrix);
[height,width,channels]=size(image);
%迭代阈值
threshold1 = 127;
threshold2 = 0;
%临时变量
temp1=0;
temp2=0;
temp3=0;
temp4=0;
%直方图统计
gray_map = zeros(1,256);
for i=1:height
for j=1:width
T = image_matrix(i,j)+1;
%灰度统计计数
gray_map(T)=gray_map(T)+1;
end
end
while(1)
%计算下一个迭代阈值
for i=1:threshold1
temp1=temp1+gray_map(i)*i;
temp2=temp2+gray_map(i);
end
for i=threshold1:256
temp3=temp1+gray_map(i)*i;
temp4=temp2+gray_map(i);
end
threshold2 =(temp1/temp2+temp3/temp4)/2;
threshold2=ceil(threshold2);
%看迭代结果是否收敛
if(threshold1==threshold2)
threshold1=ceil(threshold1);
break;
else
threshold1 = threshold2;
end
end
%对各像素进行灰度转换
for i =1:height
for j=1:width
currentPixel = image_matrix(i,j);
if(currentPixel<threshold1)
currentPixel = 0;
else
currentPixel = 255;
end
image_matrix(i,j)=currentPixel;
end
end
%显示图
image_out = uint8(image_matrix);
subplot(1,2,1);
imshow(image);
subplot(1,2,2);
imshow(image_out);
