How to apply color quantization to an image

In the other thread, @Kevin also shares some code he wrote to do k-means color clustering using opencv.Mat.