Search code examples
matlabk-meansreshapehsv

how to use kmeans on a hsv matrix


I am trying to use kmeans clustering only on the h matrix (from the original picture) and I am having trouble with the size of the matrix that I use with kmeans. I know that I need to reshape it , but noting I tried works.
Here is what I tried :

x = imread('4.jpg');
hsv=rgb2hsv(x);
H=c(:,:,1);
[m,n]=size(H);
X = reshape(H,[m,n,3]);
X = double(squeeze(X));
IDX = kmeans(double(H),3);

I get the error:

to reshape the number of elements must not change.

Please help, Thank you!


Solution

  • Note your reshape will not work because the original size is m*n and your are trying to reshape into something with a size of m*n*3. You can't change the size with reshape.

    This works:

    x = imread('peppers.png');
    hsv=rgb2hsv(x);
    H=hsv(:,:,1); %******H=c(:,:,1);
    [m,n]=size(H);
    figure(1), imshow(H);
    %X = reshape(H,[m,n,3]);
    %X = double(squeeze(X)); 
    IDX = kmeans(double(H(:)),3);  % NOTE change to this line
    H = reshape(IDX,[m,n]);
    figure(2), imagesc(H)