MATLAB實現FCM演算法,簡單程式碼實現
阿新 • • 發佈:2019-01-05
先來看看結果好了,這是一幅原圖,經過FCM演算法之後,假設選擇3個center,將這幅彩色影象轉化後得到一個只有三種灰度值的影象,還能將每一種灰度單獨提取出來,得到對應的只含有一種灰度的三個圖。
它的數學原理為
這裡Vk取v1,v2,v3三個任意初始值,經過反覆迭代得到穩定的v1,v2,v3即可。
原理方面不再贅述。
詳細實現程式碼如下。
一開始是一個調入影象命令,讀者可以根據自己需要修改引數。
BB=imread('C:\Users\User\Desktop\san.jpeg');CC=rgb2gray(BB);
A=rgb2gray(BB);
A=CC;
A=double(A);
length=412;
width=268;
p=zeros(length,width,3);
u=zeros(length,width,3);
v1=A(8,78);
v2=A(11,82);
v3=A(2,86);
i=1;
j=1;
while(i<=length)
while(j<=width)
p(i,j,1)=abs(double(A(i,j))-double(v1));
p(i,j,2)=abs(double(A(i,j))-double(v2));
p(i,j,3)=abs(double(A(i,j))-double(v3));
j=j+1;
end
j=1;
i=i+1;
end
V1=-100;
V2=-100;
V3=-100;
x=0;
while(abs(v1-V1)>1e-5||abs(v2-V2)>1e-5||abs(v3-V3)>1e-5)
V1=v1;
V2=v2;
V3=v3;
i=1;
j=1;
while(i<=length)
while(j<=width)
if(p(i,j,1)-0<1e-5)
u(i,j,1)=1;
elseif(p(i,j,2)-0<1e-5)
u(i,j,2)=1;
elseif(p(i,j,3)-0<1e-5)
u(i,j,3)=1;
else
u(i,j,1)=1/[(p(i,j,1)/p(i,j,1))^2+(p(i,j,1)/p(i,j,2))^2+(p(i,j,1)/p(i,j,3))^2];
u(i,j,2)=1/[(p(i,j,2)/p(i,j,1))^2+(p(i,j,2)/p(i,j,2))^2+(p(i,j,2)/p(i,j,3))^2];
u(i,j,3)=1/[(p(i,j,3)/p(i,j,1))^2+(p(i,j,3)/p(i,j,2))^2+(p(i,j,3)/p(i,j,3))^2];
end
j=j+1;
end
j=1;
i=i+1;
end
i=1;
j=1;
a1=0;
a2=0;
b1=0;
b2=0;
c1=0;
c2=0;
while(i<=length)
while(j<=width)
a1=a1+u(i,j,1)^2*A(i,j);
a2=a2+u(i,j,1)^2;
b1=b1+u(i,j,2)^2*A(i,j);
b2=b2+u(i,j,2)^2;
c1=c1+u(i,j,3)^2*A(i,j);
c2=c2+u(i,j,3)^2;
j=j+1;
end
j=1;
i=i+1;
end
v1=a1/a2;
v2=b1/b2;
v3=c1/c2;
i=1;
j=1;
while(i<=length)
while(j<=width)
p(i,j,1)=abs(double(A(i,j))-double(v1));
p(i,j,2)=abs(double(A(i,j))-double(v2));
p(i,j,3)=abs(double(A(i,j))-double(v3));
j=j+1;
end
j=1;
i=i+1;
end
x=x+1;
end
Uzz=zeros(length,width);
i=1;
j=1;
while(i<=length)
while(j<=width)
max=u(i,j,1);
k=1;
l=k;
while(k<=3)
if(u(i,j,k)>max)
max=u(i,j,k);
l=k;
end
k=k+1;
end
Uzz(i,j)=l;
j=j+1;
end
j=1;
i=i+1;
end
i=1;
j=1;
while(i<=length)
while(j<=width)
if(Uzz(i,j)==1)
A(i,j)=v1;
elseif(Uzz(i,j)==2)
A(i,j)=v2;
else
A(i,j)=v3;
end
j=j+1;
end
j=1;
i=i+1;
end
A=uint8(A);
figure(1);
imshow(A);//到這裡得到FCM模糊結果影象
cluster1=zeros(length,width);
cluster2=zeros(length,width);
cluster3=zeros(length,width);
i=1;
j=1;
while(i<=length)
while(j<=width)
if(double(A(i,j))==6)
cluster1(i,j)=v1;
elseif(double(A(i,j))==66)
cluster2(i,j)=v2;
else
cluster3(i,j)=v3;
end
j=j+1;
end
j=1;
i=i+1;
end
figure(2);
imshow(cluster1)
figure(3);
imshow(cluster2)
figure(4);
imshow(cluster3);//到這裡得到對應只含一個模糊中心的三個不同影象。