Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort (hex) colors to match rainbow

I have a list of colors represented in hex - I need to sort them to match the order of colors in a rainbow. - I could hardcode a sort order - but I feel there's a cleaner way.

like image 742
NFicano Avatar asked Jan 18 '12 18:01

NFicano


1 Answers

Here's a function that, given a color specification in hex RGB, returns its HSV color:

import colorsys

def get_hsv(hexrgb):
    hexrgb = hexrgb.lstrip("#")   # in case you have Web color specs
    r, g, b = (int(hexrgb[i:i+2], 16) / 255.0 for i in xrange(0,5,2))
    return colorsys.rgb_to_hsv(r, g, b)

Now you can use this to sort your list of RGB hex colors by hue:

color_list = ["000050", "005000", "500000"]  # GBR
color_list.sort(key=get_hsv)
print color_list

By sorting using the entire HSV tuple, you ensure that colors that have no hue (i.e. grayscales) sort in a consistent place, and that colors with the same hue but different saturations/values sort in a consistent order relative to their more-saturated/valued counterparts.

You will still have something of a mess if colors vary widely by saturation (intensity) or value (brightness), but there's no getting around that.

like image 105
kindall Avatar answered Oct 02 '22 07:10

kindall