我正在尝试将rgb图像转换为灰度图像,然后使用matlab的kmean函数对其进行聚类。
这是我的代码
he = imread('tumor2.jpg');
%convert into a grayscale image
ab=rgb2gray(he);
nrows = size(ab,1);
ncols = size(ab,2);
%convert the image into a column vector
ab = reshape(ab,nrows*ncols,1);
%nColors=no of clusters
nColors = 3;
%cluster_idx is a n x 1 vector where cluster_idx(i) is the index of cluster assigned to ith pixel
[cluster_idx, cluster_center ,cluster_sum] = kmeans(ab,nColors,'distance','sqEuclidean','Replicates',1,'EmptyAction','drop' );
figure;
%converting vector into a matrix of dimensions equal to that of original
%image dimensions (nrows x ncols)
pixel_labels = reshape(cluster_idx,nrows,ncols);
pixel_labels
imshow(pixel_labels,[]), title('image labeled by cluster index');
问题
1)输出图像始终是纯白图像。 我尝试了下面链接中给出的解决方案,但在这种情况下,图像的输出是纯灰色图像。
2)当我第二次执行我的代码时,执行不会超越k-mean函数(它就像是一个无限循环)。因此在这种情况下没有输出。
答案 0 :(得分:3)
实际上,看起来当你进行颜色分割时kmeans
已知属于局部最小值。这意味着通常情况下,它不会找到您想要的聚类数量,因为最小化不是最好的(这就是为什么很多人使用其他类型的细分,例如水平集或简单区域增长)。
一个选项是增加重复次数(kmeans尝试找到答案的次数)。目前您将其设置为1,但您可以尝试3或4,它可能会以这种方式达到解决方案。
在this问题中,接受的答案建议使用专为图像分割而创建的kmeans
版算法。我没有尝试过,但我觉得它值得一试。