matlab图像分割实现代码
时间: 2024-09-09 20:02:56 浏览: 82
根据提供的引用内容,可以看出有三种不同的图像分割实现代码,分别是迭代法二值化、模糊聚类和分水岭算法。下面分别介绍这三种方法的实现代码:
1.迭代法二值化:
```matlab
clear,clc,close all;
Image=im2double(rgb2gray(imread('card1.jpg')));
figure,imshow(Image),title('原始图像');
T=(max(Image(:))+min(Image(:)))/2;
equal=false;
while ~equal
rb=find(Image>=T);
ro=find(Image<T);
NewT=(mean(Image(rb))+mean(Image(ro)))/2;
equal=abs(NewT-T)<1/256;
T=NewT;
end
result=im2bw(Image,T);
figure,imshow(result),title('迭代方法二值化图像 ');
imwrite(result,'card1diedai.jpg');
```
2.模糊聚类:
```matlab
clear,clc,close all;
Image=rgb2gray(imread('card1.jpg'));
figure,imshow(Image),title('原始图像');
hist=imhist(Image);
bottom=min(Image(:))+1;
top=max(Image(:))+1;
C=double(top-bottom);
S=zeros(256,1);
J=10^10;
for t=bottom+1:top-1
miuo=0;
for j=bottom:t
miuo=miuo+hist(j)*double(j);
end
pixelnum=sum(hist(bottom:t));
miuo=miuo/pixelnum;
for j=bottom:t
miuf=1/(1+abs(double(j)-miuo)/C);
S(j)=-miuf*log(miuf)-(1-miuf)*log(1-miuf);
end
miub=0;
for j=t+1:top
miub=miub+hist(j)*double(j);
end
pixelnum=sum(hist(t+1:top));
miub=miub/pixelnum;
for j=t+1:top
miuf=1/(1+abs(double(j)-miub)/C);
S(j)=-miuf*log(miuf)-(1-miuf)*log(1-miuf);
end
currentJ=sum(hist(bottom:top).*S(bottom:top));
if currentJ<J
J=currentJ;
thresh=t;
end
end
result=zeros(size(Image));
result(Image>thresh)=1;
figure,imshow(result);
imwrite(result,'card1fuzzy.jpg');
```
3.分水岭算法:
```matlab
clear,clc,close all;
image=im2double(rgb2gray(imread('card1.jpg')));
figure,imshow(image),title('原图');
hv=fspecial('prewitt');
hh=hv.';
gv=abs(imfilter(image,hv,'replicate'));
gh=abs(imfilter(image,hh,'replicate'));
% g=sqrt(gv.^2+gh.^2);
g=abs(gv)+abs(gh);
figure,imshow(g),title('梯度图像');
L=watershed(g);
wr=L==0;
figure,imshow(wr),title('分水岭');
image(wr)=0;
figure,imshow(image),title('分割结果');
% imwrite(g,'watergrad.jpg');
% imwrite(wr,'fenshuiling.jpg');
% imwrite(image,'waterresult.jpg');
```
阅读全文