6

根据这个答案,我在 Python 中生成了一些均匀分布的颜色,如下所示:

>>> import colorsys
>>> num_colors = 22
>>> hsv_tuples = [(x*1.0/num_colors, 0.5, 0.5) for x in range(num_colors)]
>>> rgb_tuples = map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples)
>>> rgb_tuples
[(0.5, 0.25, 0.25), (0.5, 0.3181818181818182, 0.25), (0.5, 0.38636363636363635, 0.25), (0.5, 0.45454545454545453, 0.25), (0.4772727272727273, 0.5, 0.25), (0.4090909090909091, 0.5, 0.25), (0.34090909090909094, 0.5, 0.25), (0.2727272727272727, 0.5, 0.25), (0.25, 0.5, 0.2954545454545454), (0.25, 0.5, 0.36363636363636365), (0.25, 0.5, 0.43181818181818177), (0.25, 0.5, 0.5), (0.25, 0.4318181818181819, 0.5), (0.25, 0.36363636363636354, 0.5), (0.25, 0.2954545454545454, 0.5), (0.2727272727272727, 0.25, 0.5), (0.34090909090909083, 0.25, 0.5), (0.40909090909090917, 0.25, 0.5), (0.4772727272727273, 0.25, 0.5), (0.5, 0.25, 0.4545454545454546), (0.5, 0.25, 0.38636363636363646), (0.5, 0.25, 0.3181818181818181)]

现在如何将这些(“坐标?”)RGB 元组转换回 RGB 十六进制字符串,例如#FF00AA?可能是一个简单的问题,但我无法找到答案。

4

3 回答 3

7

对于每种颜色, floor(color * 256),以十六进制打印出来(填充到 2 个位置)。例如:

In [1]: rgb_tuples = [(0.5, 0.25, 0.25), (0.5, 0.3181818181818182, 0.25), (0.5, 0.38636363636363635, 0.25), (0.5, 0.45454545454545453, 0.25), (0.4772727272727273, 0.5, 0.25), (0.4090909090909091, 0.5, 0.25), (0.34090909090909094, 0.5, 0.25), (0.2727272727272727, 0.5, 0.25), (0.25, 0.5, 0.2954545454545454), (0.25, 0.5, 0.36363636363636365), (0.25, 0.5, 0.43181818181818177), (0.25, 0.5, 0.5), (0.25, 0.4318181818181819, 0.5), (0.25, 0.36363636363636354, 0.5), (0.25, 0.2954545454545454, 0.5), (0.2727272727272727, 0.25, 0.5), (0.34090909090909083, 0.25, 0.5), (0.40909090909090917, 0.25, 0.5), (0.4772727272727273, 0.25, 0.5), (0.5, 0.25, 0.4545454545454546), (0.5, 0.25, 0.38636363636363646), (0.5, 0.25, 0.3181818181818181)]

In [2]: for (r,g,b) in rgb_tuples:
   ...:     print '%02x%02x%02x' % (int(r*255), int(g*255), int(b*255))
   ...:     
804040
805140
806240
807440
于 2013-02-09T03:03:03.710 回答
4

1) 将浮点数乘以 256 并转换为整数。如果等于 256,则减 1。

编辑:由于我得到了很多令人困惑的评论,所以你必须乘以 256(如果它最终为 256,则减去 1)的原因是你得到与每个整数输出对应的完全相同数量的浮点值。

2) http://docs.python.org/2/library/string.html?highlight=hexadecimal#format-specification-mini-language

'x' 十六进制格式。输出以 16 为基数的数字,对 9 以上的数字使用小写字母。

使用它,将其设为大写并在它之前插入一个#。

于 2013-02-09T02:58:25.093 回答
0

最有效的方法是将 base-1 十进制 RGB 转换为 base-16 十进制或 HEX。

  r = int(input('R: '))
  g = int(input('G: '))
  b = int(input('B: '))
  def rgbToHex(r,g,b):
    rgb = [r,g,b]
    x = ''
    for i in rgb:
      x += format(i,'02x').upper()
    if x[0] == x[1] and x[2] == x[3] and x[4] == x[5]:
      x = x[0] + x[2] + x[4]
    return '#'+x
  print(rgbToHex(r,g,b))
于 2020-12-19T13:35:45.773 回答