# 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 FeaturesL = [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 SegmentationCENTS = F( ceil(rand(K,1)*size(F,1)) ,:);             % Cluster CentersDAL   = zeros(size(F,1),K+2);                         % Distances and LabelsKMI   = 10;                                           % K-means Iterationfor 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   endendX = zeros(size(F));for i = 1:Kidx = find(DAL(:,K+1) == i);X(idx,:) = repmat(CENTS(i,:),size(idx,1),1); endIkm = reshape(X(:,1:3),size(I,1),size(I,2),3);end``

``I = repmat( rgb2gray(I), 1, 1, 3);``