[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

How to make "rainbow" RGB values?

Simon Forman

2/25/2008 12:52:00 AM

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)]
2 Answers

Andrew McNamara

2/25/2008 1:09:00 AM

0

>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.

--
Andrew McNamara, Senior Developer, Object Craft
http://www.object-cra...

Simon Forman

2/25/2008 2:15:00 AM

0

On Feb 24, 5:09 pm, Andrew McNamara <andr...@object-craft.com.au>
wrote:
> >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.
>
> --
> Andrew McNamara, Senior Developer, Object Crafthttp://www.object-cra...

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