Finding boundaries of kmeans clustering

21 views (last 30 days)
Miel Achten
Miel Achten on 18 Dec 2018
Answered: the cyclist on 18 Dec 2018
Hello,
For a project I'm using kmeans clustering to find color differences in an image. I'm using five different grayscale colors to categorise the colors in the image. I however need to find the boundaries of each grayscale color. So which rgb values are classified as grayscale 1, which rgb values are classified as grayscale 2, etc.. Are there any formulas or scripts to find these boundaries?
Thank you in advance.
Miel Achten
I'm using the following code:
rgbImage = imread('ISIC_0000041.jpg');
mask = imread('ISIC_0000041_segmentation.png');
he = combineRgbWithMask(rgbImage,mask); %formula to combine mask and rgbImage
lab_he = rgb2lab(he);
ab = lab_he(:,:,2:3);
nrows = size(ab,1);
ncols = size(ab,2);
ab = reshape(ab,nrows*ncols,2);
nColors = 5;
% 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);
imshow(pixel_labels,[]), title('image labeled by cluster index');
  1 Comment
Jan
Jan on 18 Dec 2018
Please do not post a question twice. See https://www.mathworks.com/matlabcentral/answers/436298-finding-boundaries-kmeans-clustering . This confuses the readers and wastes time, if someone posts an answer, which has been given already. I recommend to delete one of the threads.

Sign in to comment.

Answers (1)

the cyclist
the cyclist on 18 Dec 2018
Use the centroid coordinates as input to the voronoi command.
xy1 = [randn(50,1) randn(50,1)];
xy2 = [randn(50,1)+5 randn(50,1)];
xy3 = [randn(50,1) randn(50,1)+5];
[idx,c] = kmeans([xy1; xy2; xy3],3)
figure
hold on
plot(xy1(:,1),xy1(:,2),'ro')
plot(xy2(:,1),xy2(:,2),'go')
plot(xy3(:,1),xy3(:,2),'bo')
voronoi(c(:,1),c(:,2))
The code above will just plot the boundaries, but you can get output from the voronoi command that will identify the endpoints of the line segments.

Tags

Community Treasure Hunt

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

Start Hunting!