例9.10 用改进watershed算法分割图像. f=imread('rice.bmp'); subplot(2,3,1); imshow(f);
title('(a)原始图像'); %计算梯度图 f=double(f);
hv=fspecial('prewitt'); hh=hv.':
gv=abs(imfilter(f,hv,'replicate')); gh=abs(imfilter(f,hh,'replicate')); g=sqrt(gv.^2+gh.^2); %计算距离函数 subplot(2,3,2); df=bwdist(f);
imshow(uint8(df*8));
title('(b)原图像的距离变换'); %计算外部约束 L=watershed(df); em=L= =0; subplot(2,3,3); imshow(em);
title('(c)标记外部约束'); %计算内部约束
im=imextendedmax(f,20); subplot(2,3,4); imshow(im);
title('(d)标记内部约束'); %重构梯度图
g2=imimposemin(g,im|em);
subplot(2,3,5); imshou(g2);
title('(d)标记内部约束'); %watershed(g2);
title('(e)由标记内外约束重构的梯度图'); %watershed算法分割 L2=watershed(g2); wr2=L2= =0; subplot(2,3,6); wr2=L2= =0; f(wr2)=255;
imshow(uint8(f)); title('(f)分割及结果');
9.11用区域生长法分割图像.
f=imread('pepper.bmp'); subplot(2,2,1); imshow(f);
seedx=[30,76,86];
seedy=[110,81,110];%选择3个种子点 hold on
plot(seedx,seedy,'gs','linewidth',1); title('原始图像及种子点位置'); f=double(f);
markerim=f= =f(seedy(1),seedx(1)); for i=2:length(seedx)
markerim=markerim|(f= =f(seedy(i),seedx(i))); end
thresh=[12,6,12];%3个种子点区域的阈值 maskim=zeros(size(f)); for i=1:length(seedx)
g=abs(f-f(seedy(i),seedx(i)))<=thresh(i); maskim=maskim|g end
[g,nr]=bwlabel(imreconstruct(markim,maskim),8); g=mat2gray(g); subplot(2,2,2); imshow(g); imshow(g);
title('三个种子点区域生长结果');
9.12用分裂合并法分割图像 f=imread('peppers.bmp'); [m,n]=size(f);
pow2size=2^nextpow2(max(m,n)); if m~=n|m~=pow2size
error('图像必须是方的且大小为2的整数次幂'); end
subplot(2,2,1); imshow(f);
title('原始图像'); std_thresh=10; min_dim=2;
g=split_merge(f,min_dim,@predicate_fun,std_thresh); g=mat2gray(g); subplot(2,2,2); imshow(g);
title('分裂最小子区域大小2*2');
function g=split_merge(f,min_dim,predicate_fun,std_thresh)
spare_qtim=qtdecomp(f,@split_test_fun,min_dim,@predicate_fun,std_thresh); max_block_size=full(max(spare_qtim(:))); maskim=zeros(size(f)); markerim=zeros(size(f));
for i=1:max_block_size
[val,r,c]=qtgetblk(f,spare_qtim,i); if numel(val)~=0
for numel(val)~=0 for j=1:length(r) xlow=r(j); ylow=c(j);
xhigh=xlow+i-1; yhigh=ylow+i-1;
subblock=f(xlow:xhigh,ylow:yhigh);
flag=feval(predicate_fun,subblock,std_thresh); if flag
maskim(xlow:xhigh,ylow:yhigh)=1; markerim(xlow:xhigh,ylow:yhigh)=1; end end end end
g=bwlabel(imreconstruct(markerim,maskim),8);
function splitflag=split_test_fun(subblocks_im,min_dim,predicate_fun,std_thresh) block_num=size(subblocks_im,3); splitflag((1:block_num)=false; for i=1:block_num
subblock=subblocks_im(:,:,i); if(size(subblock,1))<=min_dim splitflag(i)=false; continue end
flag=feval(predicate_fun,subblock,std_thresh); if flag
splitflag(i)=true; end end
function flag=predicate_fun(subblock_im,std_thresh) stdval=std2(subblock_im); flag=stdval>std_thresh;