MATLAB小小技巧(3)otsu二值化分割算法
前言
MATLAB进行图像处理相关的学习是非常友好的,可以从零开始,对基础的图像处理都已经有了封装好的许多可直接调用的函数,这个系列文章的话主要就是介绍一些大家在MATLAB中常用一些概念函数进行例程演示!
OSTU又叫大津法, 由日本学者大津于1979年提出。
(1)从大津法的原理上来讲,该方法又称作最大类间方差法,因为按照大津法求得的阈值进行图像二值化分割后,前景与背景图像的类间方差最大。
(2)它是按图像的灰度特性,将图像分成背景和前景两部分。因方差是灰度分布均匀性的一种度量, 背景和前景之间的类间方差越大,说明构成图像的两部分的差别越大, 当部分前景错分为背景或部分背景错分为前景都会导致两部分差别变小。因此, 使类间方差最大的分割意味着错分概率最小。
一. MATLAB仿真
clc;clear;close;
tic
[filename,pathname]=uigetfile('*.jpg;*.png;*.bmp','select the file');
im=[pathname,filename];
A = imread(im);
imagBW = otsu(A);
figure(1),imshow(A),title('原图');
figure(2),imshow(imagBW),title('otsu阈值二值化分割图');
toc
function imagBW = otsu(imag)
imag = imag(:, :, 1);
[counts, x] = imhist(imag); % counts are the histogram. x is the intensity level.
GradeI = length(x); % the resolusion of the intensity. i.e. 256 for uint8.
varB = zeros(GradeI, 1); % Between-class Variance of binarized image.
prob = counts ./ sum(counts); % Probability distribution
meanT = 0; % Total mean level of the picture
for i = 0 : (GradeI-1)
meanT = meanT + i * prob(i+1);
end
varT = ((x-meanT).^2)' * prob;
% Initialization
w0 = prob(1); % Probability of the first class
miuK = 0; % First-order cumulative moments of the histogram up to the kth level.
varB(1) = 0;
% Between-class variance calculation
for i = 1 : (GradeI-1)
w0 = w0 + prob(i+1);
miuK = miuK + i * prob(i+1);
if (w0 == 0) || (w0 == 1)
varB(i+1) = 0;
else
varB(i+1) = (meanT * w0 - miuK) .^ 2 / (w0 * (1-w0));
end
end
maxvar = max(varB);
em = maxvar / varT % Effective measure
index = find(varB == maxvar);
index = mean(index);
th = (index-1)/(GradeI-1)
imagBW = im2bw(imag, th);
% thOTSU = graythresh(imag)
% imagBWO = im2bw(imag, thOTSU);
end
二. 仿真结果
三. 小结
类间方差法对噪音和目标大小十分敏感,它仅对类间方差为单峰的图像产生较好的分割效果。当目标与背景的大小比例悬殊时,类间方差准则函数可能呈现双峰或多峰,此时效果不好,但是类间方差法计算量少,是用时最少的。
二值化分割是图像处理中最基础的变换,主要核心就在于找到一个最优阈值对图像进行分割,从而实现背景与前景的分割。每天学一个MATLAB小知识,大家一起来学习进步阿!