1、直方圖閾值法
用 MATLAB實現直方圖閾值法:
I=imread(' c4.jpg ');
I1=rgb2gray(I);
figure;
subplot(2,2,1);
imshow(I1);
title(' 灰度圖像')
axis([50,250,50,200]);
grid on; %顯示網格線
axis on; %顯示坐標系
[m,n]=size(I1); %測量圖像尺寸參數
GP=zeros(1,256); %預創建存放灰度出現概率的向量
for k=0:255
GP(k+1)=length(find(I1==k))/(m*n); %計算每級灰度出現的概率,將其存入GP中相應位置
end
subplot(2,2,2),bar(0:255,GP,'g') %繪制直方圖
title('灰度直方圖')
xlabel('灰度值')
ylabel(' 出現概率')
I2=im2bw(I,150/255);
subplot(2,2,3),imshow(I2);
title('閾值150的分割圖像')
axis([50,250,50,200]);
grid on; %顯示網格線
axis on; %顯示坐標系
I3=im2bw(I,200/255); %
subplot(2,2,4),imshow(I3);
title('閾值200的分割圖像')
axis([50,250,50,200]);
grid on; %顯示網格線
axis on; %顯示坐標系
2、自動閾值法:Otsu法
用MATLAB實現Otsu算法:
clc
clear all
I=imread(' c4.jpg ');
subplot(1,2,1),imshow(I);
title('原始圖像')
axis([50,250,50,200]);
grid on; %顯示網格線
axis on; %顯示坐標系
level=graythresh(I); %確定灰度閾值
BW=im2bw(I,level);
subplot(1,2,2),imshow(BW);
title('Otsu 法閾值分割圖像')
axis([50,250,50,200]);
grid on; %顯示網格線
axis on; %顯示坐標系