k means clustering shows only blank image if i loop it k times

22 views (last 30 days)
Anirudh Kochhar
Anirudh Kochhar on 22 Oct 2021
Answered: Image Analyst on 8 Nov 2021 at 13:45
If i loop for i = 1:2 i get clustering otherwise i just get a blank image. any idea why?
im = imread("irobot.jpg");
im_as_col = double(im(:));
cluster_membs = kmeans(im_as_col, 3)
cluster_membs = 6912000×1
2 2 2 2 2 2 2 2 2 2
labelim = zeros(size(im));
for i=1:3
inds = find(cluster_membs==i);
meanval = mean(im_as_col(inds));
labelim(inds) = meanval;
end
imshow(im)
imshow(labelim);
  2 Comments
Anirudh Kochhar
Anirudh Kochhar on 22 Oct 2021
hey sorry i forgot to add the image to the question. now that it is attached it should be easier to see. I dont get to see the k mean clustered image for some reason. it is a white image.

Sign in to comment.

Accepted Answer

yanqi liu
yanqi liu on 5 Nov 2021 at 8:00
clc; clear all; close all;
im = imread("https://ww2.mathworks.cn/matlabcentral/answers/uploaded_files/774998/irobot.jpg");
im_as_col = double(im(:));
cluster_membs = kmeans(im_as_col, 3);
labelim = zeros(size(im));
for i=1:3
inds = find(cluster_membs==i);
meanval = mean(im_as_col(inds));
labelim(inds) = meanval;
end
figure; imshow(im,[])
figure; imshow(mat2gray(labelim),[]);
  3 Comments
yanqi liu
yanqi liu on 8 Nov 2021 at 5:44
yes,sir,its make 3 color class,and use label to display different gray level,that can be ref label2rgb

Sign in to comment.

More Answers (2)


Image Analyst
Image Analyst on 8 Nov 2021 at 13:45
For what it's worth, attached is my Color Classifier that is based on Discrminant Analysis instead of kmeans. Basically you draw regions that are representative of the colors you want to have as your classes. Then it classifies all the pixels in the image into one of those classes.
Also attaching a KNN classifier demo.
Adapt as needed.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!