用MATLAB 編寫的meanshift 尋找聚類中心的程序 有些簡陋
%% mean shift
%% 產生隨機點
x1 = 30 + sqrt(9) * randn(1,100);
y1 = 30 +sqrt(9) * randn(1,100);
x2 =20+sqrt(7) * randn(1,100);
y2 =20+sqrt(7) * randn(1,100);
x3 =10+sqrt(6) * randn(1,100);
y3 =40+sqrt(6) * randn(1,100);
x=[x1 x2 x3];
y=[y1 y2 y3];
h =5;
pointx =[x(1),y(1)];
points=[x' y'];
%%
%%
ddd =size(points);
centers=zeros(10,2);
count =1;
for i=1:ddd(1);
pointx =points(i,:);
flag=0;
while(1)
[number,mh]=FindPoint(pointx,points,h);%返回漂移向量mh。
if sqrt(mh(1)^2+mh(2)^2)<0.001
break;
end
pointx=pointx+mh;
end
if count==1
tempcenter=centers(count,:);
else
tempcenter=centers(count-1,:);
end
if sqrt((pointx(1)-tempcenter(1))^2+(pointx(2)-tempcenter(2))^2)>5
for ii=1:count
tep =centers(ii,:);
if sqrt((tep(1)-pointx(1))^2+(tep(2)-pointx(2))^2)<1
flag=1;
break;
end
end
if flag==0
centers(count,:)=pointx;
count=count+1;
end
end
end
scatter(x,y,3,'filled');
axis([0 50 0 50]);
hold on
scatter(centers(:,1),centers(:,2),5,[1 0 0],'filled');
FindPoint求出均值漂移向量
function [ number,mh] = FindPoint( pointx,points,radis )
%FINDPOINT Summary of this function goes here
% Detailed explanation goes here
a=size(points);
num=0;
sum=[0,0];
total =a(1);
for i=1:total
temppoint =points(i,:);
r=sqrt((pointx(1)-temppoint(1))*(pointx(1)-temppoint(1))+(pointx(2)-temppoint(2))*(pointx(2)-temppoint(2)));
if(r<=radis)
num=num+1;
sum=sum+[temppoint(1)-pointx(1),temppoint(2)-pointx(2)];
end
end
number=num;
mh=sum/num;
end
效果圖: