MATLAB: K means image segmentation based on intensity and spatial

classificationimage processingimage segmentationkmeansStatistics and Machine Learning Toolbox

In the below code can segment image based on color and spatial. how can I convert it to work with intensity instead of color?
function Ikm = Km2(I,K)
%%color + spatial (option: K (Number of Clusters))
I = im2double(I);
[x,y] = meshgrid(1:size(I,2),1:size(I,1)); % Spatial Features
L = [y(:)/max(y(:)),x(:)/max(x(:))];
C = reshape(I,size(I,1)*size(I,2),3); % Color Features
F = [C,L]; % Color & Spatial Features
%%Kmeans Segmentation
CENTS = F( ceil(rand(K,1)*size(F,1)) ,:); % Cluster Centers
DAL = zeros(size(F,1),K+2); % Distances and Labels
KMI = 10; % K-means Iteration
for n = 1:KMI
for i = 1:size(F,1)
for j = 1:K
DAL(i,j) = norm(F(i,:) - CENTS(j,:));
end
[Distance CN] = min(DAL(i,1:K)); % 1:K are Distance from Cluster Centers 1:K
DAL(i,K+1) = CN; % K+1 is Cluster Label
DAL(i,K+2) = Distance; % K+2 is Minimum Distance
end
for i = 1:K
A = (DAL(:,K+1) == i); % Cluster K Points
CENTS(i,:) = mean(F(A,:)); % New Cluster Centers
if sum(isnan(CENTS(:))) ~= 0 % If CENTS(i,:) Is Nan Then Replace It With Random Point
NC = find(isnan(CENTS(:,1)) == 1); % Find Nan Centers
for Ind = 1:size(NC,1)
CENTS(NC(Ind),:) = F(randi(size(F,1)),:);
end
end
end
end
X = zeros(size(F));
for i = 1:K
idx = find(DAL(:,K+1) == i);
X(idx,:) = repmat(CENTS(i,:),size(idx,1),1);
end
Ikm = reshape(X(:,1:3),size(I,1),size(I,2),3);
end

Best Answer

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.