0

I was dealing with color segmentation with MATLAB. I used k-means clustering based on this document and come this far codewise;

global imgRGB; global imgLAB; img = imgRGB; cform = makecform('srgb2lab'); imgLAB = applycform(img, cform); ab = double(imgLAB(:,:,2:3)); rows = size(ab,1) cols = size(ab,2); ab = reshape(ab, rows*cols, 2); cluster = 5; [idx center] = kmeans(ab, cluster, 'distance', 'sqEuclidean', 'Replicates', 5); label = reshape(idx, rows, cols); figure; imshow(label, []); imgSeg = cell(5); rgb_label = repmat(pixel_labels, [1 1 3]); for k=1:cluster color = img; color(rgb_label ~= k) = 0; imgSeg{k} = color; end figure; imshow(imgSeg{1}); 

I take image as input that is why it is defined global.

For a colored image like the one in link, it produces the grayscale output.

I think it assigns gray tones as colors but I need to assign a color to each cluster. I mean not gray tone but a color. How can I achieve that?

1 Answer 1

1

You should use a different colormap for your figure, when displaying the labels directly.

Try:

figure; imshow(label, []); colormap( rnad(max(imgSeg{1}(:))+1, 3) ); % use random color map 

However, if you wish to convert the pixel_labels to an RGB image (3 color channels per pixel), you want to use ind2rgb (instead of replicating the labels to all channels). Replace rgb_label = repmat(pixel_labels, [1 1 3]); with

rgb_label = ind2rgb(pixel_labels, rand(max(pixel_labels(:)),3)); 
Sign up to request clarification or add additional context in comments.

2 Comments

I am sorry that didn't work. Should I use colormap function elsewhere in code?
Nope, still not working. I wonder if it is because of this line; rgb_label = repmat(pixel_labels, [1 1 3]);

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.