最简单的方法是用matlab自带的函数:
BW2 = bwmorph(BW,'thin',n);
n是要细化迭代的次数,也可以是Inf(没有引号)。Inf表示算法会一直迭代直到图像不再改变。
算法原理参考 [1]。
Zhang-Suen算法
原理简介:http://www.cnblogs.com/mikewolf2002/p/3321732.html
算法实现:http://www.chinabaike.com/t/9642/2014/0624/2547871.html
将下列三个m文件和主m文件放到一起,主m文件这样调用:BW2=zs(BW1);
zs.m
%zs.m
function out=zs(im)
%
%zs appises the Zhang-Suen skeletonization algorithm to image IM. IM must
%be binary.
%
luteven=makelut('zseven',3);
lutodd=makelut('zsodd',3);
done=0;
N=2;
last=im;
previous=applylut(last ,lutodd);
current=applylut(previous,luteven);
while done==0,
if all(current(:)==last(:)),
done=1;
end
N=N+1;
last=previous;
previous=current;
if mod(N,2)==0,
current=applylut(current,luteven);
else
current=applylut(current,lutodd);
end;
end;
out=current;
end
zseven.m
%zseven.m
function out=zseven(nbhd)
s=sum(nbhd(:))-nbhd(5);
temp1=(2<=s)&&(s<=6);
p=[nbhd(1) nbhd(4) nbhd(7) nbhd(8) nbhd(9) nbhd(6) nbhd(3) nbhd(2)];
pp=[p(2:8) p(1)];
xp=sum((1-p).*pp);
temp2=(xp==1);
prod1=nbhd(4)*nbhd(8)*nbhd(2);
prod2=nbhd(4)*nbhd(6)*nbhd(2);
temp3=(prod1==0)&&(prod2==0);
if temp1&temp2&temp3&nbhd(5)==1
out=0;
else
out=nbhd(5);
end;
end
zsodd.m
%zsodd.m
function out=zsodd(nbhd)
s=sum(nbhd(:))-nbhd(5);
temp1=(2<=s)&&(s<=6);
p=[nbhd(1) nbhd(4) nbhd(7) nbhd(8) nbhd(9) nbhd(6) nbhd(3) nbhd(2)];
pp=[p(2:8) p(1)];
xp=sum((1-p).*pp);
temp2=(xp==1);
prod1=nbhd(4)*nbhd(8)*nbhd(6);
prod2=nbhd(8)*nbhd(6)*nbhd(2);
temp3=(prod1==0)&&(prod2==0);
if temp1&temp2&temp3&nbhd(5)==1
out=0;
else
out=nbhd(5);
end;
end
参考[2]中骨架化的算法,不知道是算法写错了,还是本来论文就没有论述清楚,总是会把左上角给弄断,先记在下面,以后再改吧。
Isrc = imread('pic/0.bmp');
if ndims(Isrc) == 3
I = rgb2gray(Isrc);
else
I = Isrc;
end
I = im2bw(I,0.5);
%外围扩展边界
[H,W] = size(I);
I = [zeros(2,W);I;zeros(2,W)];
I = [zeros(H+4,2),I,zeros(H+4,2)];
[H,W] = size(I);
for k = 1:10 %迭代次数
p = zeros(8,1);
NzI = zeros(H,W);
ZI = zeros(H,W);
P024I = zeros(H,W);
P246I = zeros(H,W);
I2 = I;
for i = 2:H-1
for j = 2:W-1
if I(i,j)
p(1) = I(i,j+1);
p(2) = I(i-1,j+1);
p(3) = I(i-1,j);
p(4) = I(i-1,j-1);
p(5) = I(i,j-1);
p(6) = I(i+1,j-1);
p(7) = I(i+1,j);
p(8) = I(i+1,j+1);
NzI(i,j) = sum(p);
ZI(i,j) = sum(abs(diff(p)))+abs(p(8)-p(1));
P024I(i,j) = p(1) * p(3) * p(5);
P246I(i,j) = p(3) * p(5) * p(7);
end
end
end
for i = 3:H-1
for j = 3:W-1
if I(i,j)
if ((NzI(i,j) >= 2) && (NzI(i,j) <= 6)) && ...
(ZI(i,j) == 2) && ...
((P024I(i,j)==0)||(ZI(i,j-1)~=2)) && ...
((P246I(i,j)==0)||(ZI(i-1,j)~=2))
I2(i,j) = 0;
end
end
end
end
I = I2;
end
figure(1);
subplot(121);
imshow(Isrc);
subplot(122);
imshow(I2);
[1]: Lam, L., Seong-Whan Lee, and Ching Y. Suen, “Thinning Methodologies-A Comprehensive Survey,” IEEE Transactions on Pattern Analysis and Machine Intelligence, Vol 14, No. 9, September 1992, page 879, bottom of first column through top of second column.
[2]周凤香. 工业生产线标签字符识别系统的设计与实现[D].电子科技大学,2013.