Sort (hex) colors to match rainbow

匿名 (未验证) 提交于 2019-12-03 08:46:08

问题:

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.

回答1:

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.



回答2:

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.



回答3:

The easiest thing to do is sort them in hue order.



回答4:

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'] 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!