matlab 自带kmeans是k-均值聚汪核类函数。例如:
rng default
X = [randn(100,2)*0.75+ones(100,2) randn(100,2)*0.5-ones(100,2)]
opts = statset('Display'肆返,'final')
[idx,C,sumd,D] = kmeans(X,2,'Distance','cityblock'困雹掘,'Replicates',5,'Options',opts)
直接用kmeans函数。。。idx = kmeans(X,k)
idx = kmeans(X,k,Name,Value)
[idx,C] = kmeans(___)
[idx,C,sumd] = kmeans(___)
[idx,C,sumd,D] = kmeans(___)
idx = kmeans(X,k) performs k-means clustering to partition the observations of the n-by-p data matrix X into k clusters, and returns an n-by-1 vector (idx) containing cluster indices of each observation. Rows of X correspond to points and columns correspond to variables.
By default, kmeans uses the squared Euclidean distance measure and the k-means++ algorithm for cluster center initialization.
example
idx = kmeans(X,k,Name,Value) returns the cluster indices with additional options specified by one or more Name,Value pair arguments.
For example, specify the cosine distance, the number of times to repeat the clustering using new initial values, or to use parallel computing.
example
[idx,C] = kmeans(___) returns the k cluster centroid locations in the k-by-p matrix C.
example
[idx,C,sumd] = kmeans(___) returns the within-cluster sums of point-to-centroid distances in the k-by-1 vector sumd.
example
[idx,C,sumd,D] = kmeans(___) returns distances from each point to every centroid in the n-by-k matrix D.
close allclear
I_rgb = imread('color-cam4-f0.bmp') %读取文件数据
figure(1)
subplot(1,2,1)
imshow(I_rgb) %显示原图
title('原始图像')
%将彩耐行色图像从昌姿哗RGB转化到lab彩色空间
C = makecform('srgb2lab') %设置转册衡换格式
I_lab = applycform(I_rgb, C)
%进行K-mean聚类将图像分割成3个区域
ab = double(I_lab(:,:,2:3)) %取出lab空间的a分量和b分量
nrows = size(ab,1)
ncols = size(ab,2)
ab = reshape(ab,nrows*ncols,2)
nColors = 4 %分割的区域个数为
[cluster_idx cluster_center] = kmeans(ab,nColors,'distance','sqEuclidean','Replicates',100) %重复聚类3次
pixel_labels = reshape(cluster_idx,nrows,ncols)
figure(1)
subplot(1,2,2)
imshow(pixel_labels,[]), title('聚类结果')
%显示分割后的各个区域
segmented_images = cell(1,nColors)
rgb_label = repmat(pixel_labels,[1 1 3])
for k = 1:nColors
color = I_rgb
color(rgb_label ~= k) = 0
segmented_images{k} = color
end
for i=1:nColors
figure(2),subplot(1,nColors,i)imshow(segmented_images{i}), title('分割结果')
end
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)