This reminds me a bit of the octree quantization implementation I hacked up to improve speed of generating Racket's animated gifs.
* https://github.com/racket/racket/commit/6b2e5f4014ed95c9b883...
* https://github.com/racket/racket/commit/f2a1773422feaa4ec112...