【发布时间】:2016-08-05 21:55:19
【问题描述】:
我正在学习如何使用 kmean 聚类来分割颜色,就像 matlab 2015a 中的示例一样。但是每次我运行代码时,我想要的颜色都在不同的集群中。例如,第一次运行时,它会显示黄色在集群 1 中,蓝色在集群 2 中。当我再次运行时,它们将切换到不同的集群。即使我一次又一次地运行它,如何使黄色和蓝色处于特定的集群中?请帮我。提前致谢
这是我使用的代码:
[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 中。请告诉我如何做到这一点
【问题讨论】:
标签: image matlab image-processing colors image-segmentation