matlab中分水岭函数并不能直接得到想要的分割结果。网络上有下面三种处理方式:
代码1:
filename=‘1.jpg';
f=imread(filename);
f=rgb2gray(f);
b1=im2bw(f,0.6);
out=edge(f,'canny',0.3);
se=strel('disk',1);
b=imclose(b1,se);
b=imopen(b,se);
[X,Y]=size(b);
d=bwdist(b);
I=watershed(-d);
w=I==0;
wait=imfill(w,'holes');
g=f;
g2=imimposemin(d,w);
I2=watershed(g2);
g(w)=0;
wait=imopen(wait,se);
imshow(w);
代码2:
filename='1.jpg';
f=imread(filename);
f=rgb2gray(f);
b=im2bw(f,graythresh(f));
[X,Y]=size(b);
h=fspecial('sobel');
fd=double(f);
g=sqrt(imfilter(fd,h,'replicate').^2+imfilter(fd,h','replicate').^2);
I=watershed(g);
wr=I==0;
g2=imclose(imopen(g,ones(3,3)),ones(3,3));
I2=watershed(g2);
wr2=I2==0;
f2=f;
f2(wr2)=0;
imshow(f);
代码3:
filename='1.jpg';
f=imread(filename);
f=rgb2gray(f);
b=im2bw(f,graythresh(f));
[X,Y]=size(b);
h=fspecial('sobel');
fd=double(f);
g=sqrt(imfilter(fd,h,'replicate').^2+imfilter(fd,h','replicate').^2);
I=watershed(g);
wr=I==0;
rm=imregionalmin(g);
im=imextendedmin(f,50);
lim=watershed(bwdist(im));
em=lim==0;
g2=imimposemin(g,im|em);
I2=watershed(g2);
f2=f;
f2(I2==0)=0;
imshow(f2);
上述的第三种方法为最优方法,不过还是会由于背景的不均匀造成大量的误分割。在做该部分内容时,基于图像重建来去除噪声并进行保留细节特征。代码如下:
clc;
clear;
img=imread('1.jpg');
I=rgb2gray(img);
se = strel('disk', 5);
Ie=imerode(I,se);
Io=imopen(I,se);
subplot(1,2,1);imshow(I,[]);title('gray');
subplot(1,2,2);imshow(Ie);title('腐蚀');
figure;imshow(Io);title('开运算');
Iobr=imreconstruct(Ie,I);
figure;
imshow(Iobr,[]);title('基于开的重建图像');
Iobrd = imdilate(Iobr, se);
Iobrcbr = imreconstruct(imcomplement(Iobrd), imcomplement(Iobr));
Iobrcbr = imcomplement(Iobrcbr);
figure;
imshow(Iobrcbr,[]);title('基于开闭操作的重建图像');
f=Iobrcbr;
%f=rgb2gray(f);
b=im2bw(f,graythresh(f));
%bb=im2bw(ff,graythresh(f));
[X,Y]=size(b);
h=fspecial('sobel');
fd=double(f);
g=sqrt(imfilter(fd,h,'replicate').^2+imfilter(fd,h','replicate').^2);
I=watershed(g);
wr=I==0;
rm=imregionalmin(g);
im=imextendedmin(f,13);
lim=watershed(bwdist(im));
em=lim==0;
g2=imimposemin(g,im|em);
I2=watershed(g2);
f2=f;
f2(I2==1)=255;
figure;
subplot(1,2,1);imshow(b);
subplot(1,2,2);imshow(f2);
figure;
imshow(I2);