MATLAB: Reducing the number of distinct colors without using rgb2ind

ccolormapdigital image processingimage processingmatlab coder

How can I reduce the number of distinct colors (color quantization) in an image without using rgb2ind or other complex functions. I also need it to be fast.
I can't use rgb2ind because I don't want to write my code in Matlab. I've tried to convert my code to C++ using Matlab Coder but rgb2ind isn't supported. I can implement simple Matlab code in C++ myself (without using Coder). I just want to know how rgb2ind works. I've tried to reduce the number of distinct colors in images in C++ using OpenCV and kmeans which worked fine but it's >100x slower than rgb2ind. Does anyone know how rgb2ind work?
Any help would be appreciated.

Best Answer

Then imquantize()
Note: code generation is supported for both of these routines.