How to make "rainbow" RGB values?

S

Simon Forman

Hey all,
I want to map an int to a color on a rainbow spectrum, i.e. for an int
n in the range 0..N, low values (near 0) should map to the red end,
and high values (near N) to the blue/violet end.

The return values should be R, G, B tuples (well, "#xxxxxx" color
codes, but that's not the hard part.)

The trouble I'm having is in coming up with a good way to generate
color values that approximates the "ROY G BIV" rainbow spectrum. This
is just a simple, non-scientific, non-photographic application,
nothing fancy.

I've tried a simple scheme of overlapping sines, but this resulted in
too much red and blue, and no indigo/violet.

Any suggestions? I'm searching on the web now but not coming up with
much, so I thought I'd ask here.


TIA,
~Simon

Here's the sinecode I tried:


def g(n):
'''
map sine [-1.0 .. 1.0] => color byte [0 .. 255]
'''
return 255 * (n + 1) / 2.0


def f(start, stop, N):

interval = (stop - start) / N

for n in range(N):
coefficient = start + interval * n
yield g(sin(coefficient * pi))

n = 150
RED = f(0.5, 1.5, n)
GREEN = f(1.5, 3.5, n)
BLUE = f(1.5, 2.5, n)

RGBs = [('#%02x%02x%02x' % rgb) for rgb in zip(RED, GREEN, BLUE)]
 
A

Andrew McNamara

I want to map an int to a color on a rainbow spectrum, i.e. for an int
n in the range 0..N, low values (near 0) should map to the red end,
and high values (near N) to the blue/violet end. [...]
I've tried a simple scheme of overlapping sines, but this resulted in
too much red and blue, and no indigo/violet.

Consider using an HSV->RGB conversion function. Saturation (S) and value
(V) should remain constant, while Hue (H) varies to get your rainbow
effect.
 
S

Simon Forman

I want to map an int to a color on a rainbow spectrum, i.e. for an int
n in the range 0..N, low values (near 0) should map to the red end,
and high values (near N) to the blue/violet end. [...]
I've tried a simple scheme of overlapping sines, but this resulted in
too much red and blue, and no indigo/violet.

Consider using an HSV->RGB conversion function. Saturation (S) and value
(V) should remain constant, while Hue (H) varies to get your rainbow
effect.

Hey thank you very much, that worked like a charm! :]

There's even a library function in the colorsys module (http://
docs.python.org/lib/module-colorsys.html)

Cheers,
~Simon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,825
Latest member
VernonQuy6

Latest Threads

Top