Resolved: How to map colors in an image to a palette fast with numpy?

In this post, we will see how to resolve How to map colors in an image to a palette fast with numpy?


I have two arrays. One is an image array and the other is a palette array. Both have elements containing 8-bit RGB channels. I need to replace every color in the image with the closest color in the palette.
Currently I’m measuring distance in the RGB-space, which is not ideal, but easy to implement.
This is my implementation:
The palette has 4096 random colors (simple conversion is not possible). When mapping a 600×448 sized image this takes roughly a minute even on my core i5 machine. I plan to use this on lower-end devices like a raspberry pi, where it takes roughly 3 minutes to map a small image.
This is way too slow. I believe this can be sped up significantly when the full loop is implemented with numpy syntax, but I can’t figure out how to do this.
How do I get from the original image to the mapped one all implemented with numpy syntax?

Best Answer:

You can try using cKDTree function from scipy.
This program runs for approximately 0.8 seconds.

If you have better answer, please add a comment about this, thank you!