2016-04-14 116 views
0

我正在学习如何使用kmean聚类来分割颜色,就像matlab 2015a中的示例一样。但每次运行代码时,我想要的颜色都在不同的群集中。例如,对于第一次运行,它将显示黄色在群集1中,蓝色在群集2中。当我再次运行它时,它们将切换到不同的群集。如何使黄色和蓝色在特定的群集中,即使我一次又一次地运行它?请帮帮我。在此先感谢为什么kmean颜色分割每次都显示不同的颜色?

这是我使用的代码:

[FileName,PathName] = uigetfile('*.jpg','Select the MATLAB code file'); 

he1= imread(FileName); 
cform = makecform('srgb2lab'); 
lab_he = applycform(he1,cform); 
figure (2) 
imshow (lab_he) 


ab = double(lab_he(:,:,2:3)); 
nrows = size(ab,1); 
ncols = size(ab,2); 
ab = reshape(ab,nrows*ncols,2); 

nColors = 3; 
% repeat the clustering 3 times to avoid local minima 
[cluster_idx, cluster_center] = kmeans(ab,nColors,'distance','sqEuclidean',   ... 
            'Replicates',3); 



pixel_labels = reshape(cluster_idx,nrows,ncols); 
figure (3) 
imshow(pixel_labels,[]), title('image labeled by cluster index'); 

segmented_images = cell(1,3); 
rgb_label = repmat(pixel_labels,[1 1 3]); 

for k = 1:nColors 
    color = he1; 
    color(rgb_label ~= k) = 0; 
    segmented_images{k} = color; 
end 
%% 
figure (4) 
imshow(segmented_images{1}), title('objects in cluster 1'); 

%% 
figure (5) 
imshow(segmented_images{2}), title('objects in cluster 2'); 

%% 
figure (6) 
imshow(segmented_images{3}), title('objects in cluster 3'); 
%% 
a = im2bw (segmented_images{2},0.05); 
figure (7) 
imshow (a); 

b = im2bw (segmented_images{3},0.05); 
figure (8) 
imshow (b); 

在我的情况,与黄色的区域应该是在第2组和蓝色区域的面积应在集群3.请出示我该怎么做

回答

1

kmeans的第一个输出是索引的集群而不是颜色。您所指的颜色是MATLAB在显示时显示的颜色。

使用kmeans,从输入数据中随机选择初始聚类中心。因此,的订单是随机的。因此,每次调用算法时,哪个簇索引被分配给一个像素将会不同,但是一个簇内的像素应该被放置在相同的簇内,并且在连续调用时具有与彼此相同的簇索引

如果您需要与每个群集对应的实际颜色,则需要使用second outputkmeans(群集质心)将群集索引映射为颜色。您可以使用ind2rgb轻松做到这一点。

pixel_labels = ind2rgb(cluster_idx, cluster_center); 
imshow(pixel_labels) 

如果您只是想在群集索引值连续调用后保持不变,则可以使用cluster_center,以确保一致的指标分配

[cluster_idx, cluster_center] = kmeans(ab, nColors); 
[~, ind] = sortrows(cluster_center); 

pixel_labels = reshape(cluster_idx, nrows, ncols); 

for k = 1:numel(ind) 
    pixel_labels(cluster_idx == k) = ind(k); 
end 

如果你想有一个具体的可以修改此颜色在特定的群集中。

%// Define yellow 
yellow = [1 1 0]; 

%// Define blue 
blue = [0 0 1]; 

%// Find the centroid closest to yellow 
[~, yellowind] = min(sum(bsxfun(@minus, cluster_center, yellow).^2, 2)); 

%// Find the one closest to blue 
[~, blueind] = min(sum(bsxfun(@minus, cluster_center, blue).^2, 2)); 

%// Now assign them to clusters with yellow as 2 and blue as 3 
segmented_images{1} = cluster_idx == setdiff(1:3, [yellowind, blueind]); 
segmented_images{2} = cluster_idx == yellowind; 
segmented_images{3} = cluster_idx == blueind; 
+0

即时通讯对不起,先生,你能向我解释这是如何工作的吗? –

+0

@badrulhisham我已经更新了答案,希望能让它更加清晰 – Suever

+0

非常感谢您的帮助先生,我会尽力将这些写入我的编码 –

相关问题