Color Reduction Using K-Means Clustering

Although nowadays displays are able to handle 24-bit graphics efficiently, it is still useful in many areas to reduce color space. Below, I’ll show how we can reduce the color space using k-means clustering algorithm.
For this example, we have a 24-bit image Irish eye flowers.
imshow(image);
Irish Flowers Image
Reconstructing the image in double vectors form, suitable for Matlab’s kmeans function,
r = image(:,:,1);
g = image(:,:,2);
b = image(:,:,3);
imagek(:,1) = r(:);
imagek(:,2) = g(:);
imagek(:,3) = b(:);
imagek = double(imagek);
Setting the number of colors (clusters) ‘N’  to be 16 and using kmeans,
N=16;
[IDX, C] = kmeans(imagek, N, 'EmptyAction', 'singleton');
k-means clustering is a method of cluster analysis which aims to partition S observations into N clusters in which each observation belongs to the cluster with the nearest mean. In colour images, each color plane matrix cell could have 256 values (observations) and we want to partition them to just N values.
We use ‘singleton’ option, if a cluster loses all its member observations it will create a new cluster consisting of the one point furthest from its centroid.
Reconstructing the data to an image matrix form,
s=size(image);
IDX= uint8(IDX);
C2=round(C);
imageNew = zeros(s(1),s(2),3);
temp = reshape(IDX, [s(1) s(2)]);
for i = 1 : 1 : s(1)
 for j = 1 : 1 : s(2)
  imageNew(i,j,:) = C2(temp(i,j),:);
 end
end
imageNew=uint8(imageNew);
And we have our new color reduced image.
Flowers Image after color reduction