第六章 图像分割
实例:灰度图像的阈值分割
clc;
clear;
%读入图像
A = imread('shape.jpg');
figure(1),subplot(2,2,1),imshow(A),title('原图像');
%获取灰度直方图,根据直方图人工选取阈值
h = imhist(A);
%h = imhist(A) / numel(A);
h1 = h(1:10:256);
horz = 1:10:256;
figure(2),bar(horz, h1),axis([0 255 0 15000]),title('直方图');
%人工设定阈值进行图像分割
thr1 = 100;
[m, n] = size(A);
for i = 1:m
for j = 1:n
if A(i,j) < thr1
A1(i,j) = 0;
else
A1(i,j) = 1;
end
end
end
figure(1),subplot(2,2,2),imshow(A1),title('人工设定阈值');
%使用迭代法选取阈值进行图像分割
%计算阈值初始值
thr2 = 0.5 * (double(min(A(:))) + double(max(A(:))));
%设定循环终止条件
done = false;
%循环计算阈值和分割图像
while ~done
%获取二值分割结果
A2 = A >= thr2;
%计算新阈值
tnext = 0.5 * (mean(A(A2)) + mean(A(~A2)));
%判断循环是否终止
done = abs(thr2 - tnext) < 0.5;
%阈值更新
thr2 = tnext;
end
figure(1),subplot(2,2,3),imshow(A2),title('迭代选取阈值');
%使用Otsu方法进行阈值选取和图像分割
%使用Otsu方法获取阈值
thr3 = graythresh(A) * 255;
%使用获得的阈值进行阈值分割
[m, n] = size(A);
for i = 1:m
for j = 1:n
if A(i,j) < thr3
A3(i,j) = 0;
else
A3(i,j) = 1;
end
end
end
figure(1),subplot(2,2,4),imshow(A3),title('Otsu阈值选取');
实验结果: