2016-04-14 113 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

非常感謝您的幫助先生,我會盡力將這些寫入我的編碼 –

相關問題