MATLAB小小技巧(4)niblack二值化分割算法
前言
MATLAB进行图像处理相关的学习是非常友好的,可以从零开始,对基础的图像处理都已经有了封装好的许多可直接调用的函数,这个系列文章的话主要就是介绍一些大家在MATLAB中常用一些概念函数进行例程演示!
Niblack二值化算法是比较简单的局部阈值方法,阈值的计算公式是T = m + kv,其中m为以该像素点为中心的区域的平均灰度值,v是该区域的标准差,k是一个系数。这个区域就可以自己根据实际情况进行定义设计,比如33邻域,55邻域,或者77邻域等等。
一. MATLAB仿真
clc;clear;close;
[filename,pathname]=uigetfile('*.jpg;*.png;*.bmp','select the file');
im=[pathname,filename];
A = imread(im);
imagBW = niblack(A);
figure(1),imshow(A),title('原图');
figure(2),imshow(imagBW),title('niblack阈值二值化分割图');
function imagBW = niblack(imag)
tic;
k = -0.2; % the first manual parameter
b = 80; % the second manual parameter, about the width of the square neighborhood
choice = 1; % 1 for pixel-to-pixel computation, 2 for pixel averaging within the square neighborhood for fast computation.
imag = imag( :, :, 1);
[Hei, Wid] = size(imag);
imag = padarray(imag, [b b], 'symmetric', 'both'); % Pad image array
Hei_pad = Hei + 2 * b;
Wid_pad = Wid + 2 * b;
imagBW = false(Hei_pad, Wid_pad);
switch choice
case 1
for i = 1+b : Hei+b
for j = 1+b : Wid+b
upR = i-floor(b/2-1/2);
dnR = i+floor(b/2);
lfC = j-floor(b/2-1/2);
rtC = j+floor(b/2);
m_ij = mean(mean(imag(upR : dnR, lfC : rtC)));
sigma_squared = double(imag(upR : dnR, lfC : rtC)) - m_ij;
sigma_squared = mean(mean(sigma_squared .^2));
sigma = sqrt(sigma_squared);
th_ij = m_ij + k * sigma;
if double(imag(i,j)) > th_ij
imagBW(i,j) = 1;
end
end
end
case 2
for i = 1+b : b : Hei+b
for j = 1+b : b : Wid+b
upR = i-floor(b/2-1/2);
dnR = i+floor(b/2);
lfC = j-floor(b/2-1/2);
rtC = j+floor(b/2);
m_ij = mean(mean(imag(upR : dnR, lfC : rtC)));
sigma_squared = double(imag(upR : dnR, lfC : rtC)) - repmat(m_ij, (dnR-upR+1), (rtC-lfC+1));
sigma_squared = sigma_squared .^ 2;
sigma_squared = mean(mean(sigma_squared));
sigma = sqrt(sigma_squared);
th_ij = m_ij + k * sigma;
imagBW(upR : dnR, lfC : rtC) = double(imag(upR : dnR, lfC : rtC)) > th_ij;
end
end
otherwise
display('Wrong Choice!');
end
imagBW = imagBW(1+b : Hei+b, 1+b : Wid+b);
% figure, imshow(imagBW), title('Binarized Image');
toc;
end
二. 仿真结果
三. 小结
二值化分割是图像处理中最基础的变换,主要核心就在于找到一个最优阈值对图像进行分割,从而实现背景与前景的分割。之前提到的大津阈值法是一种全局阈值分割方法,相比全局法,局部阈值法处理相对更精细一些。每天学一个MATLAB小知识,大家一起来学习进步阿!