Right after the first line, add
I = repmat( rgb2gray(I), 1, 1, 3);
That will make the code take grayscale intensity of the color image, and then copies the intensities to all three planes (making a gray RGB image). The code should work from there.
There are more efficient ways of doing this, but they require more code changes. If you are going to do extensive code changes then the best approach would be to just call the MATLAB kmeans() routine.
Best Answer