views:

333

answers:

2

I want to generate a list of color specifications in the form of (r, g, b) tuples, that span the entire color spectrum with as many entries as I want. So for 5 entries I would want something like:

  • (0, 0, 1)
  • (0, 1, 0)
  • (1, 0, 0)
  • (1, 0.5, 1)
  • (0, 0, 0.5)

Of course, if there are more entries than combination of 0 and 1 it should turn to use fractions, etc. What would be the best way to do this?

+9  A: 

Use the HSV/HSB/HSL color space (three names for more or less the same thing). Generate N tuples equally spread in hue space, then just convert them to RGB.

Sample code:

import colorsys
N = 5
HSV_tuples = [(x*1.0/N, 0.5, 0.5) for x in range(N)]
RGB_tuples = map(lambda x: colorsys.hsv_to_rgb(*x), HSV_tuples)
kquinn
Right, that's what I want, but how do I generate those tuples? :)
Sverre Rabbelier
Easy, that's just a simple linear series. I've put in some basic sample code above, as one way to do it.
kquinn
Cool, then using colorsys.hsv_to_rgb I get exactly what I need :).[colorsys.hsv_to_rgb(x*1.0/N, 0.5, 0.5) for x in range(N)].
Sverre Rabbelier
Excellent pythonic answer.
akent
+1  A: 

This has already been answered in http://stackoverflow.com/questions/470690/how-to-automatically-generate-n-distinct-colors so you can use that in python too

also look at this thread http://mail.python.org/pipermail/python-list/2004-June/266748.html

Anurag Uniyal