我正在學習如何使用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.請出示我該怎麼做
即時通訊對不起,先生,你能向我解釋這是如何工作的嗎? –
@badrulhisham我已經更新了答案,希望能讓它更加清晰 – Suever
非常感謝您的幫助先生,我會盡力將這些寫入我的編碼 –