K-means聚类算法采用的是将N*P的矩阵X划分为K个类,使得类内对象之间的距离最小,而类之间的距离最大。
matlab自带Kmeans 函数 使用方法: Idx=Kmeans(X,K) [Idx,C]=Kmeans(X,K) [Idx,C,sumD]=Kmeans(X,K) [Idx,C,sumD,D]=Kmeans(X,K) […]=Kmeans(…,’Param1’,Val1,’Param2’,Val2,…) 各输入输出参数介绍: X N*P的数据矩阵 K 表示将X划分为几类,为整数 Idx N*1的向量,存储的是每个点的聚类标号 C K*P的矩阵,存储的是K个聚类质心位置 sumD 1*K的和向量,存储的是类间所有点与该类质心点距离之和 D N*K的矩阵,存储的是每个点与所有质心的距离 […]=Kmeans(…,'Param1',Val1,'Param2',Val2,…) 这其中的参数Param1、Param2等,主要可以设置为如下: 1. ‘Distance’(距离测度) ‘sqEuclidean’ 欧式距离(默认时,采用此距离方式) ‘cityblock’ 绝度误差和,又称:L1 ‘cosine’ 针对向量 ‘correlation’ 针对有时序关系的值 ‘Hamming’ 只针对二进制数据 2. ‘Start’(初始质心位置选择方法) ‘sample’ 从X中随机选取K个质心点 ‘uniform’ 根据X的分布范围均匀的随机生成K个质心 ‘cluster’ 初始聚类阶段随机选择10%的X的子样本(此方法初始使用’sample’方法) matrix 提供一K*P的矩阵,作为初始质心位置集合 3. ‘Replicates’(聚类重复次数) 整数 %%%%%%%%%%%%%%%%%%%% 图片处理的一个实例: clc
clear all close all video=mmreader('che2.AVI'); I1=read(video,589); %I2=read(video,590); % I1=rgb2gray(I1); % I2=rgb2gray(I2); he=I1; figure,imshow(he), title('Your Image'); text(size(he,2),size(he,1)+15,... 'DIA-SA07006042-ZhangM,USTC', ... 'FontSize',7,'HorizontalAlignment','right'); %Step 2: Convert image from RGB color space to L*a*b* color space cform = makecform('srgb2lab'); lab_he = applycform(he,cform); %lab_he=rgb2hsi(he); %Step 3: Classify the colors in 'a*b*' space using K-means clustering ab = double(lab_he(:,:,2:3)); nrows = size(ab,1); ncols = size(ab,2); ab = reshape(ab,nrows*ncols,2); % 把ab变成nrows*ncols行2列 N=3; %How many color there are in the image. nColors = N; % repeat the clustering 3 times to avoid local minima [cluster_idx,cluster_center] = kmeans(ab,nColors,'distance','sqEuclidean', ... 'Replicates',N); m=4; %Step 4: Label every pixel in the image using the results from kmeans pixel_labels = reshape(cluster_idx,nrows,ncols); figure,imshow(pixel_labels,[]), title('image labeled by cluster index'); %Step 5: Create images that segment the H&E image by color. segmented_images = cell(1,N); rgb_label = repmat(pixel_labels,[1 1 N]); for k = 1:nColors color = he; color(rgb_label ~= k) = 0; segmented_images{k} = color; end figure, subplot(131),imshow(segmented_images{1}), title('objects in cluster 1'); subplot(132),imshow(segmented_images{2}), title('objects in cluster 2'); subplot(133),imshow(segmented_images{3}), title('objects in cluster 3'); |
|