Grayscale image processing using k-mean

I am trying to convert an rgb image to grayscale and then group it using the kmean function from matlab.

here is my code

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');

      

Problems

1) the output image is always a plain white image. I tried the solution given in the link below, but in this case, the image result will be a plain gray image.

find the found solution

2) when I execute my code a second time, the execution is not done outside the k-mean function (he likes an infinite loop). therefore, there is no way out in this case.

+3


source to share


1 answer


In fact, it looks like when you segment the color kmeans

it is known to hit local lows. This means that often it doesn't find the number of clusters you want as minimizing is not the best (which is why many people use a different type of segmentation such as level sets or simply increasing the area).

The option is to increase the number of Replicates (the number of times kmeans will try to find the answer). For now, you set it to 1, but you can try 3 or 4 and it can reach a solution this way.



In this question, the accepted answer recommends using the version kmeans

for an algorithm specifically created for image segmentation. I haven't tried it myself, but I think it's worth it.

Link to FEX

+2


source







All Articles