Reputation: 1075
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.
Upvotes: 6
Views: 12811
Reputation: 900
Modifying kindall answer to allow short color specifications in hex (e.g. #f0f
, #005
):
import colorsys
def get_hsv(hexrgb):
hexrgb = hexrgb.lstrip("#") # in case you have Web color specs
lh = len(hexrgb)
# Allow short and long hex codes
r, g, b = (int(hexrgb[i:i+lh/3], 16) / 255.0 for i in xrange(0, lh, lh/3))
return colorsys.rgb_to_hsv(r, g, b)
Now you can use the function to sort the list by hue:
color_list = ["#005", "#000500", "#500000"]
color_list.sort(key=get_hsv)
print color_list
>> ['#500000', '#000500', '#005']
Upvotes: 2
Reputation: 184465
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.
Upvotes: 17
Reputation: 33197
Look up the HSV color representation: https://en.wikipedia.org/wiki/HSL_and_HSV
By sorting first by Hue, you can sort by perceived color. You can freely convert between RGB and HSV.
Upvotes: 5