Forgive me in advance for my ignorance.

Using the PHP function imagecolorat, I have a solution that presently delivers a set of the most dominant hex color codes available inside of an image.

Is there a known library that will allow me to then take the hex color code, RGB code (or any other standard color code) and simplify them down, or rather "match" them to a limited set of "common colors", such as red, brown, green, yellow, grey, blue, etc?

For example, #944D70, which is a shade of purple, would be matched to the color 'purple'.


Is there a particular pattern or range to RGB colors that would allow me to write such a library myself?

For example, 0,0,0 thru 20,20,20 might all be considered a "black" color. However, it seems as if organizing such a library would be very exhausting if done manually.


1 Answer 1


Problem is that people do not really agree on a 1:1 mapping of color names. But yes such tools exists, this is a simple nearest neighborhood test. You could use any spatial query module to do this. Here is a simple (naive) python example:

from __future__ import print_function
import webcolors
from scipy.spatial import KDTree

# lets populate some names into spatial name database
hexnames = webcolors.css3_hex_to_names
names = []
positions = []

for hex, name in hexnames.iteritems():

spacedb = KDTree(positions)

# query nearest point
querycolor = (10,88, 200)
dist, index = spacedb.query(querycolor)

print('The color %r is closest to %s.'%(querycolor, names[index]))

Which results in: The color (10, 88, 200) is closest to royalblue.

I'm using here the 140 css3 defined colors. Bigger and more comprehensive lists can be found online, if you want a smallerlist that would also work. Theres all kinds of possible things you could do, you could for example linearize the sRGB space before calculating distances to name. You could ask for 3 closest names and give double names if the names are halfway.

  • $\begingroup$ This will certainly help. Are you aware of any simpler hextocolor conversions, much narrower? Was thinking more like 8 or 16 different color names $\endgroup$ Sep 26, 2015 at 14:23
  • $\begingroup$ This would work with any number of colors. $\endgroup$
    – joojaa
    Sep 26, 2015 at 14:33
  • $\begingroup$ No, no, I understand that. But I want to limit the results to an extremely limited palette consisting of red, blue, green, white, orange, purple, brown and grey, for example $\endgroup$ Sep 26, 2015 at 16:11
  • $\begingroup$ Web or CSS colors have a very high number of possible matches $\endgroup$ Sep 26, 2015 at 16:11
  • $\begingroup$ Yes, whats the problem? Instead of taking the color names form web colors supply your own $\endgroup$
    – joojaa
    Sep 26, 2015 at 16:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.