sohna pathak
sohna pathak

Reputation: 37

How to apply kmeans clustering on gray scale image in matlab

skin cancer image I want to apply K means clustering on grayscale image, code is as follow

    im = imread('SSM1_2_orig.jpg');
im = rgb2gray(im);
[idx centroids]=kmeans(double(im(:)),3,'distance','sqEuclidean','Replicates',3);
%imseg = zeros(size(im,1),size(im,2));
%{for i=1:max(idx)
    %imseg(idx==i)=i;
    %end}
segmented_images = cell(1,3);
for k = 1:3
    color = im;
    color(im ~= k) = 0;
    segmented_images{k} = color;
end

figure(),imshow(segmented_images{1});
figure(),imshow(segmented_images{2});
figure(),imshow(segmented_images{3});

but it gives me the black output only

Upvotes: 1

Views: 3178

Answers (1)

Ander Biguri
Ander Biguri

Reputation: 35525

Here is the working code. Notes:

You are never using the result of the clustering,you are comparing the original pixel values with k, instead of the clustered pixel values idx.

Also, remember to use imshow(____, []) if your images are not [0-1] or [0-255].

im = imread('https://i.sstatic.net/ZYp7r.jpg');
im = rgb2gray(im);
[idx, centroids]=kmeans(double(im(:)),3,'distance','sqEuclidean','Replicates',3);

segmented_images = cell(1,3);
for k = 1:3
    color = zeros(size(im));
    color(idx==k) = im(idx==k);
    segmented_images{k} = color;
end

figure(),imshow(segmented_images{1},[]);
figure(),imshow(segmented_images{2},[]);
figure(),imshow(segmented_images{3},[]);

Upvotes: 1

Related Questions