1 背景
聚类根据像素点做图像分割
2 原理
Fast k-means算法是一种高效的图像分割算法,其原理基于k-means聚类算法。在图像分割方面,它可以将图像分成多个不同的区域,每个区域内都具有相似的特征。
k-means算法的基本思想是在n个数据点中选取k个质心,然后将数据点分配到最近的质心所对应的簇中。然后以簇中所有点的平均值为新的质心,重复上述过程,直到质心的位置稳定或者达到给定的迭代次数。
Fast k-means算法相比于传统的k-means算法,主要在于加速了计算速度。它的主要思路是从输入的n个数据点中随机选取一个子集,然后用这个子集计算质心。接着,对于剩余的数据点,只计算它们到质心的距离,而不是计算它们与其他数据点的距离。当质心的位置稳定或者达到给定的迭代次数时,产生的聚类结果与传统的k-means算法相同。
在图像分割中,Fast k-means算法选择的数据点就是图像中的像素点,并且将像素点的颜色值作为数据点的特征值。这样,在进行聚类时,相似颜色值的像素点将被分配到同一个簇中,从而实现了图像的分割。可以在多次迭代后获得最终的聚类结果,得到每个像素点所属的不同簇。
3 核心代码
完整代码见文末:
function [centers,mincenter,mindist,q2,quality] = kmeanss(data,initcenters,method)
% output: final centers
% input: data points and initial centers
% if initcenters is a number k, create k centers and start with these
% otherwise, use centers given as input
% method = 0: unoptimized, using n by k matrix of distances O(nk) space
% 1: vectorized, using only O(n+k) space
% 2: like 1, in addition using distance inequalities (default)
tic
if nargin < 3 method = 2; end
[n,dim] = size(data);
if max(size(initcenters)) == 1
k = initcenters;
[centers, mincenter, mindist, lower, computed] = anchors(mean(data),k,data);
total = computed;
skipestep = 1;
else
centers = initcenters;
mincenter = zeros(n,1);
total = 0;
skipestep = 0;
[k,dim2] = size(centers);
if dim ~= dim2 error('dim(data) ~= dim(centers)'); end;
end
nchanged = n;
iteration = 0;
oldmincenter = zeros(n,1);
while nchanged > 0
% do one E step, then one M step
computed = 0;
if method == 0 & ~skipestep
for i = 1:n
for j = 1:k
distmat(i,j) = calcdist(data(i,:),centers(j,:));
end
end
[mindist,mincenter] = min(distmat,[],2);
computed = k*n;
elseif (method == 1 | (method == 2 & iteration == 0)) & ~skipestep
mindist = Inf*ones(n,1);
lower = zeros(n,k);
for j = 1:k
jdist = calcdist(data,centers(j,:));
lower(:,j) = jdist;
track = find(jdist < mindist);
mindist(track) = jdist(track);
mincenter(track) = j;
end
computed = k*n;
elseif method == 2 & ~skipestep
computed = 0;
4 效果